From c068c64bce9a2cfe7826e46dfe69a922978f9952 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 17 May 2015 00:47:08 +0300 Subject: [PATCH 01/11] Refactored sharepoint.d.ts to use microsoft.ajax.d.ts, added\fixed some definitions --- README.md | 0 angularjs/angular.d.ts | 0 chrome/chrome.d.ts | 0 microsoft-ajax/microsoft.ajax.d.ts | 992 ++++++----------- sharepoint/SharePoint.d.ts | 1642 ++++++++++++++++++++++++---- 5 files changed, 1768 insertions(+), 866 deletions(-) mode change 100644 => 100755 README.md mode change 100755 => 100644 angularjs/angular.d.ts mode change 100755 => 100644 chrome/chrome.d.ts diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100755 new mode 100644 diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts old mode 100755 new mode 100644 diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 1c8968f44..7100b8c51 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -18,7 +18,7 @@ * Object Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397554(v=vs.100).aspx} */ -interface Object { +interface ObjectConstructor { /** * Formats a number by using the invariant culture. */ @@ -34,173 +34,9 @@ interface Object { * Array Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb383786(v=vs.100).aspx} */ -interface Array { - - //#region lib.d.ts - - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): boolean; - prototype: Array; - - ///** - // * Returns a string representation of an array. - // */ - //toString(): string; - //toLocaleString(): string; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: U[]): T[]; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: T[]): T[]; - ///** - // * Adds all the elements of an array separated by the specified separator string. - // * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - // */ - //join(separator?: string): string; - ///** - // * Removes the last element from an array and returns it. - // */ - //pop(): T; - ///** - // * Appends new elements to an array, and returns the new length of the array. - // * @param items New elements of the Array. - // */ - //push(...items: T[]): number; - ///** - // * Reverses the elements in an Array. - // */ - //reverse(): T[]; - ///** - // * Removes the first element from an array and returns it. - // */ - //shift(): T; - ///** - // * Returns a section of an array. - // * @param start The beginning of the specified portion of the array. - // * @param end The end of the specified portion of the array. - // */ - //slice(start?: number, end?: number): T[]; - - ///** - // * Sorts an array. - // * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - // */ - //sort(compareFn?: (a: T, b: T) => number): T[]; - - ///** - // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - // * @param start The zero-based location in the array from which to start removing elements. - // */ - //splice(start: number): T[]; - - ///** - // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - // * @param start The zero-based location in the array from which to start removing elements. - // * @param deleteCount The number of elements to remove. - // * @param items Elements to insert into the array in place of the deleted elements. - // */ - //splice(start: number, deleteCount: number, ...items: T[]): T[]; - - ///** - // * Inserts new elements at the start of an array. - // * @param items Elements to insert at the start of the Array. - // */ - //unshift(...items: T[]): number; - - ///** - // * Returns the index of the first occurrence of a value in an array. - // * @param searchElement The value to locate in the array. - // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - // */ - //indexOf(searchElement: T, fromIndex?: number): number; - - ///** - // * Returns the index of the last occurrence of a specified value in an array. - // * @param searchElement The value to locate in the array. - // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - // */ - //lastIndexOf(searchElement: T, fromIndex?: number): number; - - ///** - // * Determines whether all the members of an array satisfy the specified test. - // * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - ///** - // * Determines whether the specified callback function returns true for any element of an array. - // * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - ///** - // * Performs the specified action for each element in an array. - // * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - - ///** - // * Calls a defined callback function on each element of an array, and returns an array that contains the results. - // * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - - ///** - // * Returns the elements of an array that meet the condition specified in a callback function. - // * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - - ///** - // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - ///** - // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - ///** - // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - ///** - // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - ///** - // * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - // */ - //length: number; - - //[n: number]: T; - - //#endregion +interface ArrayConstructor { + //#region Extensions /** @@ -210,55 +46,55 @@ interface Array { * @param item * */ - add(array: any[], element: any): void; + add(array: T[], element: T): void; /** * Copies all the elements of the specified array to the end of an Array object. */ - addRange(array: any, items: any): void; + addRange(array: T[], items: T[]): void; /** * Removes all elements from an Array object. */ - clear(): void; + clear(array: T[]): void; /** * Creates a shallow copy of an Array object. */ - clone(): any[]; + clone(array: T[]): T[]; /** * Determines whether an element is in an Array object. */ - contains(element: any): boolean; + contains(array: T[], element: T): boolean; /** * Removes the first element from an Array object. */ - dequeue(): any; + dequeue(array: T[]): T; /** * Adds an element to the end of an Array object. Use the add function instead of the Array.enqueue function. */ - enqueue(element: any): void; + enqueue(array: T[], element: T): void; /** * Performs a specified action on each element of an Array object. */ - forEach(array: any[], method: Function, instance: any[]): void; + forEach(array: T[], method: (element: T, index: number, array: T[]) => void, instance: any): void; /** * Searches for the specified element of an Array object and returns its index. */ - indexOf(array: any[], item: any, startIndex?: number): number; + indexOf(array: T[], item: T, startIndex?: number): number; /** * Inserts a value at the specified location in an Array object. */ - insert(array: any[], index: number, item: any); + insert(array: T[], index: number, item: T): void; /** * Creates an Array object from a string representation. */ - parse(value: string): any[]; + parse(value: string): T[]; /** * Removes the first occurrence of an element in an Array object. */ - remove(array: any[], item: any): boolean; + remove(array: T[], item: T): boolean; /** * Removes an element at the specified location in an Array object. */ - removeAt(array: any[], index: number): void; + removeAt(array: T[], index: number): void; //#endregion } @@ -277,6 +113,10 @@ interface Number { * Formats a number by using the current culture. */ localeFormat(format: string): string; +} + +interface NumberConstructor { + /** * Returns a numeric value from a string representation of a number. This function is static and can be called without creating an instance of the object. */ @@ -297,11 +137,14 @@ interface Date { /** * Formats a date by using the invariant (culture-independent) culture. */ - format(value: string): string; + format(format: string): string; /** * Formats a date by using the current culture. This function is static and can be invoked without creating an instance of the object. */ - localeFormat(value: string): string; + localeFormat(format: string): string; +} + +interface DateConstructor { /** * Creates a date from a locale-specific string by using the current culture. This function is static and can be invoked without creating an instance of the object. * @exception (Debug) formats contains an invalid format. @@ -310,9 +153,8 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseLocale(value: string): string; - parseLocale(value: string, formats?: string[]): string; - parseLocale(value: string, ...formats: string[]): string; + parseLocale(value: string, formats?: string[]): Date; + parseLocale(value: string, ...formats: string[]): Date; /** * Creates a date from a string by using the invariant culture. This function is static and can be invoked without creating an instance of the object. * @return If value is a valid string representation of a date in the invariant format, an object of type Date; otherwise, null. @@ -321,352 +163,172 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseInvariant(value: string): string; parseInvariant(value: string, formats?: string[]): string; parseInvariant(value: string, ...formats: string[]): string; } -declare module MicrosoftAjaxBaseTypeExtensions { + +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception +* details and support for application-compilation modes (debug or release). +* @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} +*/ +interface FunctionConstructor { + + //#region Extensions /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception - * details and support for application-compilation modes (debug or release). - * @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} - */ - interface Function { - - //#region lib.d.ts - - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - prototype: Function; - - //#endregion - - //#region Extensions - - /** - * Creates a delegate function that retains the context first used during an objects creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } - */ - createCallback(method: Function, ...context: any[]): Function; - /** - * Creates a callback function that retains the parameter initially used during an object's creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } - */ - createDelegate(instance: any, method: Function): Function; - - /** - * A function that does nothing. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } - */ - emptyMethod(): Function; - - /** - * Validates the parameters to a method are as expected. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } - */ - validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - - //#endregion - } + * Creates a delegate function that retains the context first used during an objects creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } + */ + createCallback(method: Function, ...context: any[]): Function; + /** + * Creates a callback function that retains the parameter initially used during an object's creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } + */ + createDelegate(instance: any, method: Function): Function; /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). - * Error Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} - */ - interface Error { - - //#region lib.d.ts - - name: string; - message: string; - - new (message?: string): Error; - (message?: string): Error; - prototype: Error; - - //#endregion - - //#region Extensions - - /** - * Creates an Error object that represents the Sys.ParameterCountException exception. - */ - parameterCount(message?: string): Error; - /** - * Creates an Error object that represents the Sys.NotImplementedException exception. - */ - notImplemented(message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentException exception. - */ - argument(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentNullException exception. - */ - argumentNull(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. - */ - argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentTypeException exception. - */ - argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. - */ - argumentUndefined(paramName?: string, message?: string): Error; - /** - * Creates an Error object that can contain additional error information. - */ - create(message?: string, errorInfo?: Object): Error; - /** - * Creates an Error object that represents the Sys.FormatException exception. - */ - format(message?: string): Error; - /** - * Creates an Error object that represents the Sys.InvalidOperationException exception. - */ - invalidOperation(message?: string): Error; - /** - * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. - */ - popStackFrame(): void; - - //#endregion - } + * A function that does nothing. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } + */ + emptyMethod(): Function; /** - * Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. - * String Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} - */ - interface String { + * Validates the parameters to a method are as expected. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } + */ + validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - //#region lib.d.ts + //#endregion +} - new (value?: any): String; - (value?: any): string; - prototype: String; - fromCharCode(...codes: number[]): string; +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). +* Error Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} +*/ +interface ErrorConstructor { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): string[]; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): string[]; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Returns the length of a String object. */ - length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - [index: number]: string; - - //#endregion - - //#region Extensions - - /** - * Formats a number by using the invariant culture. - * @returns true if the end of the String object matches suffix; otherwise, false. - */ - endsWith(suffix: string): boolean; - /** - * Replaces each format item in a String object with the text equivalent of a corresponding object's value. - * @returns A copy of the string with the formatting applied. - */ - format(format: string, ...args: any[]): string; - /** - * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. - * @returns A copy of the string with the formatting applied. - */ - localeFormat(format: string, ...args: any[]): string; - /** - * Removes leading and trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start and end of the string. - */ - trim(): string; - /** - * Removes trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the end of the string. - */ - trimEnd(): string; - /** - * Removes leading white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start of the string. - */ - trimStart(): string; - - //#endregion - } + //#region Extensions /** - * Provides extensions to the base ECMAScript (JavaScript) Boolean object. - * Boolean Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} + * Creates an Error object that represents the Sys.ParameterCountException exception. */ - interface Boolean { + parameterCount(message?: string): Error; + /** + * Creates an Error object that represents the Sys.NotImplementedException exception. + */ + notImplemented(message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentException exception. + */ + argument(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentNullException exception. + */ + argumentNull(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. + */ + argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentTypeException exception. + */ + argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. + */ + argumentUndefined(paramName?: string, message?: string): Error; + /** + * Creates an Error object that can contain additional error information. + */ + create(message?: string, errorInfo?: Object): Error; + /** + * Creates an Error object that represents the Sys.FormatException exception. + */ + format(message?: string): Error; + /** + * Creates an Error object that represents the Sys.InvalidOperationException exception. + */ + invalidOperation(message?: string): Error; - //#region lib.d.ts - new (value?: any): Boolean; - (value?: any): boolean; - prototype: Boolean; + //#endregion +} - //#endregion +interface Error { + /** + * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. + */ + popStackFrame(): void; +} - //#region Extensions - /** - * Converts a string representation of a logical value to its Boolean object equivalent. - */ - parse(value: string): Boolean; - //#endregion - } +interface String { + + //#region Extensions + + /** + * Formats a number by using the invariant culture. + * @returns true if the end of the String object matches suffix; otherwise, false. + */ + endsWith(suffix: string): boolean; + + /** + * Removes leading and trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start and end of the string. + */ + trim(): string; + /** + * Removes trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the end of the string. + */ + trimEnd(): string; + /** + * Removes leading white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start of the string. + */ + trimStart(): string; + + //#endregion +} + +/** +* Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. +* String Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} +*/ +interface StringConstructor { + /** +* Replaces each format item in a String object with the text equivalent of a corresponding object's value. +* @returns A copy of the string with the formatting applied. +*/ + format(format: string, ...args: any[]): string; + /** + * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. + * @returns A copy of the string with the formatting applied. + */ + localeFormat(format: string, ...args: any[]): string; +} + + +/** +* Provides extensions to the base ECMAScript (JavaScript) Boolean object. +* Boolean Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} +*/ +interface BooleanConstructor { + + //#region Extensions + + /** + * Converts a string representation of a logical value to its Boolean object equivalent. + */ + parse(value: string): Boolean; + + //#endregion } //#endregion @@ -908,7 +570,7 @@ declare function $find(id: string, parent?: HTMLElement): Sys.Component; * @param handler The event handler to add. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandler(element: Sys.UI.DomElement, eventName: string, handler: Function, autoRemove?: boolean): void; +declare function $addHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void, autoRemove?: boolean): void; /** * Provides a shortcut to the addHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -918,7 +580,7 @@ declare function $addHandler(element: Sys.UI.DomElement, eventName: string, hand * @param handlerOwner (Optional) The object instance that is the context for the delegates that should be created from the handlers. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOwner?: any, autoRemove?: boolean): void; +declare function $addHandlers(element: HTMLElement, events: { [event: string]: (e: Sys.UI.DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Provides a shortcut to the clearHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -926,21 +588,19 @@ declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOw * @see {@link http://msdn.microsoft.com/en-us/library/bb310959(v=vs.100).aspx} * @param The DOM element that exposes the events. */ -declare function $clearHandlers(element: Sys.UI.DomElement): void; +declare function $clearHandlers(element: HTMLElement): void; /** -* Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class. +* Provides a shortcut to the getElementById method of the HTMLElement class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397717(v=vs.100).aspx} * @param id * The ID of the DOM element to find. * @param element * The parent element to search. The default is the document element. * @return -* The Sys.UI.DomElement +* The HTMLElement */ -declare function $get(id: string): any; // Examples use HTMLElement and DomElement declare function $get(id: string, element?: HTMLElement): HTMLElement; -declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; /** * Provides a shortcut to the removeHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -949,9 +609,7 @@ declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElemen * @param eventName The name of the DOM event. * @param handler The event handler to remove. */ -declare function $removeHandler(element: any, eventName: string, handler: Function): void; -declare function $removeHandler(element: HTMLElement, eventName: string, handler: Function): void; -declare function $removeHandler(element: Sys.UI.DomElement, eventName: string, handler: Function): void; +declare function $removeHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void): void; //#endregion @@ -973,7 +631,7 @@ declare module Sys { * The members can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb384161(v=vs.100).aspx} */ - interface Application { + interface Application extends Component, IContainer { //#region Constructors @@ -986,27 +644,27 @@ declare module Sys { /** * Raised after all scripts have been loaded but before objects are created. */ - add_init(handler: Function): void; + add_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded but before objects are created. */ - remove_init(handler: Function): void; + remove_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - add_load(handler: Function): void; + add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - remove_load(handler: Function): void; + remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - add_navigate(handler: Function): void; + add_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - remove_navigate(handler: Function): void; + remove_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. @@ -2175,67 +1833,67 @@ declare module Sys { //#endregion //#region Exception Types + // Really not a types + ///** + //* Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. + //*/ + //class ArgumentException { - /** - * Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. - */ - class ArgumentException { + //} + ///** + //* Raised when an argument has an invalid value of null. + //*/ + //class ArgumentNullException { - } - /** - * Raised when an argument has an invalid value of null. - */ - class ArgumentNullException { + //} + ///** + //* Raised when an argument value is outside an acceptable range. + //*/ + //class ArgumentOutOfRangeException { - } - /** - * Raised when an argument value is outside an acceptable range. - */ - class ArgumentOutOfRangeException { + //} + ///** + //* Raised when a parameter is not an allowed type. + //*/ + //class ArgumentTypeException { - } - /** - * Raised when a parameter is not an allowed type. - */ - class ArgumentTypeException { + //} + ///** + //* Raised when an argument for a required method parameter is undefined. + //*/ + //class ArgumentUndefinedException { - } - /** - * Raised when an argument for a required method parameter is undefined. - */ - class ArgumentUndefinedException { + //} + ///** + //* + //*/ + //class FormatException { - } - /** - * - */ - class FormatException { + //} + ///** + //* Raised when a call to a method has failed, but the reason was not invalid arguments. + //*/ + //class InvalidOperationException { - } - /** - * Raised when a call to a method has failed, but the reason was not invalid arguments. - */ - class InvalidOperationException { + //} + ///** + //* Raised when a requested method is not supported by an object. + //*/ + //class NotImplementedException { - } - /** - * Raised when a requested method is not supported by an object. - */ - class NotImplementedException { + //} + ///** + //* Raised when an invalid number of arguments have been passed to a function. + //*/ + //class ParameterCountException { - } - /** - * Raised when an invalid number of arguments have been passed to a function. - */ - class ParameterCountException { + //} + ///** + //* Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. + //*/ + //class ScriptLoadFailedException { - } - /** - * Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. - */ - class ScriptLoadFailedException { - - } + //} //#endregion @@ -2252,7 +1910,28 @@ declare module Sys { * Enables your application to call Web services asynchronously by using ECMAScript (JavaScript). * @see {@link http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx} */ - // Cannot create definitions for generated proxy classes. + class WebServiceProxy { + static invoke( + servicePath: string, + methodName: string, + useGet?: boolean, + params?: any, + onSuccess?: (result: string, eventArgs: EventArgs) => void, + onFailure?: (error: WebServiceError) => void, + userContext?: any, + timeout?: number, + enableJsonp?: boolean, + jsonpCallbackParameter?: string): WebRequest; + } + + class WebServiceError { + get_errorObject(): any; + get_exceptionType(): any; + get_message(): string; + get_stackTrace(): string; + get_statusCode(): number; + get_timedOut(): boolean; + } /** * Contains information about a Web request that is ready to be sent to the current Sys.Net.WebRequestExecutor instance. @@ -2261,7 +1940,7 @@ declare module Sys { * * @see {@link http://msdn.microsoft.com/en-us/library/bb397488(v=vs.100).aspx} */ - class NetWorkRequestEventArgs { + class NetworkRequestEventArgs { //#region Constructors @@ -2310,6 +1989,19 @@ declare module Sys { //#endregion //#region Members + get_url(): string; + set_url(value: string): void; + get_httpVerb(): string; + set_httpVerb(value: string): void; + get_timeout(): number; + set_timeout(value: number): void; + get_body(): string; + set_body(value: string): void; + get_headers(): { [key: string]: string; }; + get_userContext(): any; + set_userContext(value: any): void; + get_executor(): WebRequestExecutor; + set_executor(value: WebRequestExecutor): void; /** * Registers a handler for the completed request event of the Web request. @@ -2387,7 +2079,7 @@ declare module Sys { * Gets the value of the specified response header. * @return The specified response header. */ - getResponseHeader(): string; + getResponseHeader(key: string): string; //#endregion @@ -2478,13 +2170,13 @@ declare module Sys { * @param handler * The function registered to handle the completed request event. */ - add_completedRequest(handler: (sender: any, eventArgs: any) => void): void; + add_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Registers a handler for processing the invoking request event of the WebRequestManager. * @param handler * The function registered to handle the invoking request event. */ - add_invokingRequest(handler: (sender: any, networkRequestEventArgs: any) => void): void; + add_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; /** * Sends Web requests to the default network executor. * This member supports the client-script infrastructure and is not intended to be used directly from your code. @@ -2498,14 +2190,14 @@ declare module Sys { * @param handler * The function that handles the completed request event. */ - remove_completedRequest(handler: Function): void; + remove_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Removes the event handler set by the add_invokingRequest method. * Use the remove_invokingRequest method to remove the event handler you set using the add_invokingRequest method. * @param handler * The function that handles the invoking request event. */ - remove_invokingRequest(handler: Function): void; + remove_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; //#endregion @@ -2943,16 +2635,16 @@ declare module Sys { * Gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element. This member a static member and can be invoked without creating an instance of the class. * @return The specified Behavior object, if found; otherwise, null. */ - static getBehaviorByName(element: Sys.UI.DomElement, name: string): Behavior; + static getBehaviorByName(element: HTMLElement, name: string): Behavior; /** * Gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element. This method is static and can be invoked without creating an instance of the class. * @return An array of all Behavior objects of the specified type that are associated with the specified DOM element, if found; otherwise, an empty array. */ - static getBehaviorsByType(element: Sys.UI.DomElement, type: Sys.UI.Behavior): Behavior[]; + static getBehaviorsByType(element: HTMLElement, type: Sys.UI.Behavior): Behavior[]; /** * Gets the Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to search. + * The HTMLElement object to search. * @return An array of references to Behavior objects, or null if no references exist. */ static getBehaviors(element: DomElement): Behavior[]; @@ -2971,10 +2663,10 @@ declare module Sys { * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Behavior object is associated with. * @return The DOM element that the current Behavior object is associated with. */ - get_element(): Sys.UI.DomElement; + get_element(): HTMLElement; /** * Gets or sets the identifier for the Sys.UI.Behavior object. - * A generated identifier that consists of the ID of the associated Sys.UI.DomElement, the "$" character, and the name value of the Behavior object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Behavior object. */ get_id(): string; /** @@ -3050,11 +2742,11 @@ declare module Sys { * When called from a derived class, initializes a new instance of that class. * The Control constructor is a complete constructor function. However, because the Control class is an abstract base class, the constructor should be called only from derived classes. * @param element - * The Sys.UI.DomElement object that the control will be associated with. + * The HTMLElement object that the control will be associated with. * * @throws Error.invalidOperation Function */ - constructor(element: Sys.UI.DomElement); + constructor(element: HTMLElement); //#endregion @@ -3122,6 +2814,33 @@ declare module Sys { toggleCssClass(className: string): void; //#endregion + + //#region Properties + + /** + * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Control object is associated with. + * @return The DOM element that the current Control object is associated with. + */ + get_element(): HTMLElement; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Control object. + */ + get_id(): string; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * @param value + * The string value to use as the identifier. + */ + set_id(value: string): void; + /* + * Gets or sets the name of the Sys.UI.Control object. + * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Control object. The name property remains null until it is accessed. + * @param value + * A string value to use as the name. + */ + + //#endregion } /** * Defines static methods and properties that provide helper APIs for manipulating and inspecting DOM elements. @@ -3131,11 +2850,7 @@ declare module Sys { //#region Constructors - /** - * Initializes a new instance of the Sys.UI.DomElement class. - */ - constructor(): void; - + //#endregion //#region Methods @@ -3144,38 +2859,38 @@ declare module Sys { * Adds a CSS class to a DOM element if the class is not already part of the DOM element. This member is static and can be invoked without creating an instance of the class. * If the element does not support a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to add the CSS class to. + * The HTMLElement object to add the CSS class to. * @param className * The name of the CSS class to add. */ - addCssClass(element: Sys.UI.DomElement, className: string): void; + addCssClass(element: HTMLElement, className: string): void; /** * Gets a value that indicates whether the DOM element contains the specified CSS class. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to test for the CSS class. + * The HTMLElement object to test for the CSS class. * @param className * The name of the CSS class to test for. * @return * true if the element contains the specified CSS class; otherwise, false. */ - containsCssClass(element: Sys.UI.DomElement, className: string): boolean; + containsCssClass(element: HTMLElement, className: string): boolean; /** * Gets a set of integer coordinates that represent the position, width, and height of a DOM element. This member is static and can be invoked without creating an instance of the class. * * @param element - * The Sys.UI.DomElement instance to get the coordinates of. + * The HTMLElement instance to get the coordinates of. * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the upper-left corner, the width, and the height of the element in pixels. */ - getBounds(element: Sys.UI.DomElement): Object; + getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; /** * @param id * The ID of the element to find. * @param element * (optional) The parent element to search in. The default is the document element. */ - getElementById(id: string): Sys.UI.DomElement; - getElementById(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; + getElementById(id: string): HTMLElement; + getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element: any): any; /** @@ -3185,17 +2900,15 @@ declare module Sys { * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the element in pixels. */ - getLocation(element: Sys.UI.DomElement): Sys.UI.Point; - getLocation(element: any): Object; + getLocation(element: HTMLElement): Sys.UI.Point; /* - * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. This member is static and can be invoked without creating an instance of the class. + * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. This member is static and can be invoked without creating an instance of the class. * @param element * The target DOM element. * @return * A Sys.UI.VisibilityMode enumeration value that indicates the layout characteristics of element when it is hidden by invoking the setVisible method. */ - getVisibilityMode(element: Sys.UI.DomElement): Sys.UI.VisibilityMode; - getVisibilityMode(element: any): Sys.UI.VisibilityMode; + getVisibilityMode(element: HTMLElement): Sys.UI.VisibilityMode; /** * Gets a value that indicates whether a DOM element is currently visible on the Web page. This member is static and can be invoked without creating an instance of the class. * @param element @@ -3219,16 +2932,15 @@ declare module Sys { * @param args * The event arguments */ - raiseBubbleEvent(source: Sys.UI.DomElement, args: EventArgs): void; - raiseBubbleEvent(source: any, args: any): void; + raiseBubbleEvent(source: HTMLElement, args: EventArgs): void; /** * Removes a CSS class from a DOM element. This member is static and can be invoked without creating an instance of the class. If the element does not include a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to remove the CSS class from. + * The HTMLElement object to remove the CSS class from. * @param className * The name of the CSS class to remove. */ - removeCssClass(element: Sys.UI.DomElement, className: string): void; + removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: any, className: string): void; /** @@ -3241,9 +2953,7 @@ declare module Sys { * @return * A DOM element. */ - resolveElement(elementOrElementId: Sys.UI.DomElement, containerElement?: Sys.UI.DomElement): Sys.UI.DomElement; - resolveElement(elementOrElementId: HTMLElement, containerElement?: HTMLElement): HTMLElement; - resolveElement(elementOrElementId: string): any; + resolveElement(elementOrElementId: string|HTMLElement, containerElement?: HTMLElement): HTMLElement; /** * Sets the position of a DOM element. This member is static and can be invoked without creating an instance of the class. * he left and top style attributes (upper-left corner) of an element specify the relative position of an element. @@ -3252,14 +2962,12 @@ declare module Sys { * @param x The x-coordinate in pixels. * @param y The y-coordinate in pixels. */ - setLocation(element: Sys.UI.DomElement, x: number, y: number): void; setLocation(element: HTMLElement, x: number, y: number): void; - setLocation(element: any, x: number, y: number): void; /** - * Sets the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Sets the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * This member is static and can be invoked without creating an instance of the class. * - * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * For example, if value is set to Sys.UI.VisibilityMode.collapse, the element uses no space on the page when the setVisible method is called to hide the element. * * @param element @@ -3267,41 +2975,37 @@ declare module Sys { * @param value * A Sys.UI.VisibilityMode enumeration value. */ - setVisibilityMode(element: Sys.UI.DomElement, value: Sys.UI.VisibilityMode): void; + setVisibilityMode(element: HTMLElement, value: Sys.UI.VisibilityMode): void; /** * Sets a DOM element to be visible or hidden. This member is static and can be invoked without creating an instance of the class. * * Use the setVisible method to set a DOM element as visible or hidden on the Web page. * If you invoke this method with value set to false for an element whose visibility mode is set to "hide," the element will not be visible. * However, it will occupy space on the page. If the element's visibility mode is set to "collapse," the element will occupy no space in the page. - * For more information about how to set the layout characteristics of hidden DOM elements, see Sys.UI.DomElement setVisibilityMode Method. + * For more information about how to set the layout characteristics of hidden DOM elements, see HTMLElement setVisibilityMode Method. * * @param element * The target DOM element. * @param value * true to make element visible on the Web page; false to hide element. */ - setVisible(element: Sys.UI.DomElement, value: boolean): void; setVisible(element: HTMLElement, value: boolean): void; - setVisible(element: any, value: boolean): void; /** * Toggles a CSS class in a DOM element. This member is static and can be invoked without creating an instance of the class. * Use the toggleCssClass method to hide a CSS class of an element if it is shown, or to show a CSS class of an element if it is hidden. * * @param element - * The Sys.UI.DomElement object to toggle. + * The HTMLElement object to toggle. * @param className * The name of the CSS class to toggle. */ - toggleCssClass(element: Sys.UI.DomElement, className: string): void; toggleCssClass(element: HTMLElement, className: string): void; - toggleCssClass(element: any, className: string): void; //#endregion } - var DomElement: Sys.UI.DomElement; + var DomElement: DomElement; /** * Provides cross-browser access to DOM event properties and helper APIs that are used to attach handlers to DOM element events. @@ -3312,12 +3016,11 @@ declare module Sys { //#region Constructors /** - * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified DomElement object. + * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified HTMLElement object. * @param domElement - * The DomElement object to associate with the event. + * The HTMLElement object to associate with the event. */ - constructor(domElement: DomElement); - constructor(domElement: any); + constructor(domElement: HTMLElement); //#endregion @@ -3337,7 +3040,7 @@ declare module Sys { * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ - static addHandler(element: any, eventName: string, handler: Function, autoRemove?: boolean): void; + static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean); /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. @@ -3359,7 +3062,7 @@ declare module Sys { * @throws Error.invalidOperation - (Debug) One of the handlers specified in events is not a function. * */ - static addHandlers(element: any, events: any, handlerOwner?: any, autoRemove?: boolean): void; + static addHandlers(element: HTMLElement, events: { [event: string]: (e: DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Removes all DOM event handlers from a DOM element that were added through the Sys.UI.DomEvent addHandler or the Sys.UI.DomEvent addHandlers methods. * This member is static and can be invoked without creating an instance of the class. @@ -3368,7 +3071,7 @@ declare module Sys { * @param element * The element that exposes the events. */ - static clearHandlers(element: any): void; + static clearHandlers(element: HTMLElement): void; /** * Removes a DOM event handler from the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. * @@ -3379,7 +3082,7 @@ declare module Sys { * @param handler * The event handler to remove. */ - static removeHandler(element: any, eventName: string, handler: Function): void; + static removeHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void): void; /** * Prevents the default DOM event action from happening. * Use the preventDefault method to prevent the default event action for the browser from occurring. @@ -3544,10 +3247,21 @@ declare module Sys { * Describes mouse button locations. */ enum MouseButton { - // todo + /** + * Represents the left mouse button. + */ + leftButton, + /** + * Represents the middle mouse button. + */ + middleButton, + /** + * Represents the right mouse button. + */ + rightButton } /** - * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the Sys.UI.DomElement class returns a Point object. + * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the HTMLElement class returns a Point object. * @see {@link http://msdn.microsoft.com/en-us/library/bb383992(v=vs.100).aspx} * */ class Point { @@ -3829,7 +3543,7 @@ declare module Sys { * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of
elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. */ - get_panelsDeleted(): HTMLDivElement[]; + get_panelsDeleting(): HTMLDivElement[]; /** * Gets an array of HTML
elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding
elements. diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 1f7a2feaf..026658ef8 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,157 +1,13 @@ -// Type definitions for sptypescript +// Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Sys { - export class EventArgs { - static Empty: Sys.EventArgs; - } - export class StringBuilder { - /** Appends a string to the string builder */ - append(s: string): void; - /** Appends a line to the string builder */ - appendLine(s: string): void; - /** Clears the contents of the string builder */ - clear(): void; - /** Indicates wherever the string builder is empty */ - isEmpty(): boolean; - /** Gets the contents of the string builder as a string */ - toString(): string; - } - export class Component { - get_id(): string; - static create(type: Component, properties?: any, events?: any, references?: any, element?: Node); - initialize(): void; - updated(): void; - } - - export interface IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - } - - export class Application extends Component implements IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - - static add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - static remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - } - - export class ApplicationLoadEventArgs { - constructor(components: Component[], isPartialLoad: boolean); - public components: Component[]; - public isPartialLoad: boolean; - } - - module UI { - export class Control extends Component { } - export class DomEvent { - static addHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - static removeHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - } - - export class DomElement { - static getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; - } - } - module Net { - export class WebRequest { - get_url(): string; - set_url(value: string): void; - get_httpVerb(): string; - set_httpVerb(value: string): void; - get_timeout(): number; - set_timeout(value: number): void; - get_body(): string; - set_body(value: string): void; - get_headers(): { [key: string]: string; }; - get_userContext(): any; - set_userContext(value: any): void; - get_executor(): WebRequestExecutor; - set_executor(value: WebRequestExecutor): void; - - getResolvedUrl(); string; - invoke(): void; - completed(args: Sys.EventArgs): void; - - add_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - remove_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - } - - export class WebRequestExecutor { - get_aborted(): boolean; - get_responseAvailable(): boolean; - get_responseData(): string; - get_object(): any; - get_started(): boolean; - get_statusCode(): number; - get_statusText(): string; - get_timedOut(): boolean; - get_xml(): Document; - get_webRequest(): WebRequest; - abort(): void; - executeRequest(): void; - getAllResponseHeaders(): string; - getResponseHeader(key: string): string; - } - - export class NetworkRequestEventArgs extends EventArgs { - get_webRequest(): WebRequest; - } - - - export class WebRequestManager { - static get_defaultExecutorType(): string; - static set_defaultExecutorType(value: string): void; - static get_defaultTimeout(): number; - static set_defaultTimeout(value: number): void; - - static executeRequest(request: WebRequest): void; - static add_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static remove_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static add_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - static remove_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - } - - export class WebServiceProxy { - static invoke( - servicePath: string, - methodName: string, - useGet?: boolean, - params?: any, - onSuccess?: (result: string, eventArgs: EventArgs) => void, - onFailure?: (error: WebServiceError) => void, - userContext?: any, - timeout?: number, - enableJsonp?: boolean, - jsonpCallbackParameter?: string): WebRequest; - } - - export class WebServiceError { - get_errorObject(): any; - get_exceptionType(): any; - get_message(): string; - get_stackTrace(): string; - get_statusCode(): number; - get_timedOut(): boolean; - } - } - interface IDisposable { - dispose(): void; - } - -} - -declare var $get: { (id: string): HTMLElement; }; -declare var $addHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; -declare var $removeHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; +/// +declare var _spBodyOnLoadFunctions: Function[]; +declare var _spBodyOnLoadFunctionNames: string[]; +declare var _spBodyOnLoadCalled: boolean; declare module SP { export class SOD { @@ -463,7 +319,8 @@ interface ContextInfo extends SPClientTemplates.RenderContext { } -declare function GetCurrentCtx():ContextInfo; +declare function GetCurrentCtx(): ContextInfo; +declare function SetFullScreenMode(fullscreen: boolean); declare module SP { export enum RequestExecutorErrors { requestAbortedOrTimedout, @@ -490,7 +347,7 @@ declare module SP { method?: string; headers?: { [key: string]: string; }; /** Can be string or bytearray depending on binaryStringRequestBody field */ - body?: any; + body?: string|Uint8Array; binaryStringRequestBody?: boolean; /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ @@ -509,7 +366,7 @@ declare module SP { headers?: { [key: string]: string; }; contentType?: string; /** Can be string or bytearray depending on request.binaryStringResponseBody field */ - body?: any; + body?: string|Uint8Array; state?: any; } @@ -1116,8 +973,8 @@ declare module SPClientTemplates { Type: string; } -/** Represents field schema in Grid mode and on list forms. - Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ + /** Represents field schema in Grid mode and on list forms. + Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ export interface FieldSchema_InForm extends FieldSchema { /** Description for this field. */ Description: string; @@ -1166,6 +1023,7 @@ declare module SPClientTemplates { FormUniqueId: string; ListData: ListData_InForm; ListSchema: ListSchema_InForm; + CSRCustomLayout?: boolean; } @@ -1389,7 +1247,7 @@ declare module SPClientTemplates { StateInitDone: boolean; TableCbxFocusHandler: any; TableMouseOverHandler: any; - TotalListItems: any; + TotalListItems: number; verEnabled: number; /** Guid of the view. */ view: string; @@ -1404,10 +1262,10 @@ declare module SPClientTemplates { } export interface RenderContext_FieldInView extends RenderContext_ItemInView { /** If in grid mode (context.inGridMode == true), cast to FieldSchema_InForm, otherwise cast to FieldSchema_InView */ - CurrentFieldSchema: any; + CurrentFieldSchema: FieldSchema_InForm | FieldSchema_InView; CurrentFieldValue: any; FieldControlsModes: { [fieldInternalName: string]: ClientControlMode; }; - FormContext: any; + FormContext: ClientFormContext; FormUniqueId: string; } @@ -1417,6 +1275,7 @@ declare module SPClientTemplates { export interface Group { Items: Item[]; } + type RenderCallback = (ctx: RenderContext) => void; export interface RenderContext { BaseViewID?: number; @@ -1426,8 +1285,8 @@ declare module SPClientTemplates { CurrentSelectedItems?: any; CurrentUICultureName?: string; ListTemplateType?: number; - OnPostRender?: any; - OnPreRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; + OnPreRender?: RenderCallback | RenderCallback[]; onRefreshFailed?: any; RenderBody?: (renderContext: RenderContext) => string; RenderFieldByName?: (renderContext: RenderContext, fieldName: string) => string; @@ -1484,18 +1343,18 @@ declare module SPClientTemplates { } export interface Templates { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplates; } @@ -1505,18 +1364,18 @@ declare module SPClientTemplates { } export interface TemplateOverrides { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplateMap; } @@ -1525,10 +1384,10 @@ declare module SPClientTemplates { Templates?: TemplateOverrides; /** �allbacks called before rendering starts. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPreRender?: any; + OnPreRender?: RenderCallback | RenderCallback[]; /** �allbacks called after rendered html inserted into DOM. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPostRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; /** View style (SPView.StyleID) for which the templates should be applied. If not defined, the templates will be applied only to default view style. */ @@ -1538,11 +1397,11 @@ declare module SPClientTemplates { ListTemplateType?: number; /** Base view ID (SPView.BaseViewID) for which the template should be applied. If not defined, the templates will be applied to all views. */ - BaseViewID?: any; + BaseViewID?: number|string; } export class TemplateManager { static RegisterTemplateOverrides(renderCtx: TemplateOverridesOptions): void; - static GetTemplates(renderCtx: any): Templates; + static GetTemplates(renderCtx: RenderContext): Templates; } export interface ClientUserValue { @@ -1616,13 +1475,13 @@ declare module SPClientTemplates { EnableVesioning: boolean; Id: string; }; - registerInitCallback(fieldname: string, callback: () => void ): void; - registerFocusCallback(fieldname: string, callback: () => void ): void; - registerValidationErrorCallback(fieldname: string, callback: (error: any) => void ): void; + registerInitCallback(fieldname: string, callback: () => void): void; + registerFocusCallback(fieldname: string, callback: () => void): void; + registerValidationErrorCallback(fieldname: string, callback: (error: any) => void): void; registerGetValueCallback(fieldname: string, callback: () => any): void; updateControlValue(fieldname: string, value: any): void; registerClientValidator(fieldname: string, validator: SPClientForms.ClientValidation.ValidatorSet): void; - registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void ); + registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void); } } @@ -1653,6 +1512,14 @@ declare module SPClientForms { } } +declare class SPMgr { + NewGroup(listItem: Object, fieldName: string): boolean; + RenderHeader(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema): string; + RenderField(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; + RenderFieldByName(renderCtx: SPClientTemplates.RenderContext, fieldName: string, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; +} + +declare var spMgr: SPMgr; declare module SPAnimation { export enum Attribute { @@ -7241,7 +7108,7 @@ declare module SP { } export class Status { - static addStatus(strTitle: string, strHtml: string, atBegining: boolean): string; + static addStatus(strTitle: string, strHtml?: string, atBegining?: boolean): string; static appendStatus(sid: string, strTitle: string, strHtml: string): string; static updateStatus(sid: string, strHtml: string): void; static setStatusPriColor(sid: string, strColor: string): void; @@ -7378,19 +7245,19 @@ declare module SP { @param url overrides options.url @param callback overrides options.dialogResultValueCallback @param args overrides options.args */ - static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback: SP.UI.DialogReturnValueCallback, args: any): void; + static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback?: SP.UI.DialogReturnValueCallback, args?: any): void; /** Refresh the page if specified dialogResult equals to SP.UI.DialogResult.OK */ static RefreshPage(dialogResult: SP.UI.DialogResult): void; /** Show page specified by the url in a modal dialog. If the dialog returns SP.UI.DialogResult.OK, the page is refreshed. */ static ShowPopupDialog(url: string): void; /** Show modal dialog specified by url, callback, height and width. */ - static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width: number, height: number): void; + static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width?: number, height?: number): void; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel/close button is not shown. */ - static showWaitScreenWithNoClose(title: string, message: string, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenWithNoClose(title: string, message?: string, height?: number, width?: number): SP.UI.ModalDialog; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel button is shown. If user clicks it, the callbackFunc is called. */ - static showWaitScreenSize(title: string, message: string, callbackFunc: SP.UI.DialogReturnValueCallback, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenSize(title: string, message?: string, callbackFunc?: SP.UI.DialogReturnValueCallback, height?: number, width?: number): SP.UI.ModalDialog; static showPlatformFirstRunDialog(url: string, callbackFunc: SP.UI.DialogReturnValueCallback): SP.UI.ModalDialog; - static get_childDialog: any; + static get_childDialog: ModalDialog; /** Closes the dialog using the specified dialog result. */ close(dialogResult: SP.UI.DialogResult): void; } @@ -7469,6 +7336,11 @@ declare module SP { } } + export module Workplace { + export function add_resized(handler: Function); + export function remove_resized(handler:Function); + } + export module UIUtility { export function generateRandomElementId(): string; export function cancelEvent(evt: Event): void; @@ -8410,11 +8282,11 @@ declare module SP.WorkflowServices { /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - get_restrictScope(): string; + get_restrictToScope(): string; /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - set_restrictScope(value: string): string; + set_restrictToScope(value: string): string; /** RestrictToType determines the possible event source type for a workflow subscription that uses this definition. Possible values include "List", "Site", the empty string, or null. */ get_restrictToType(): string; @@ -9441,6 +9313,7 @@ interface ISPClientAutoFillData { AutoFillMenuOptionType?: number; } + declare class SPClientPeoplePicker { static ValueName: string; // = 'Key'; static DisplayTextName: string; // = 'DisplayText'; @@ -9460,54 +9333,112 @@ declare class SPClientPeoplePicker { }; static InitializeStandalonePeoplePicker(clientId: string, value: ISPClientPeoplePickerEntity[], schema: ISPClientPeoplePickerSchema): void; + static ParseUserKeyPaste(userKey: string): string; + static GetTopLevelControl(elmChild: HTMLElement): HTMLElement; + static AugmentEntity(entity: ISPClientPeoplePickerEntity): ISPClientPeoplePickerEntity; + static AugmentEntitySuggestions(pickerObj: SPClientPeoplePicker, allEntities: ISPClientPeoplePickerEntity[], mergeLocal?: boolean): ISPClientPeoplePickerEntity[]; + static PickerObjectFromSubElement(elmSubElement: HTMLElement): SPClientPeoplePicker; + static TestLocalMatch(strSearchLower: string, dataEntity: ISPClientPeoplePickerEntity): boolean; + static BuildUnresolvedEntity(key: string, dispText: string): ISPClientPeoplePickerEntity; + static AddAutoFillMetaData(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[], numOpts: number): ISPClientPeoplePickerEntity[]; + static BuildAutoFillMenuItems(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[]): ISPClientPeoplePickerEntity[]; + static IsUserEntity(entity: ISPClientPeoplePickerEntity): boolean; + static CreateSPPrincipalType(acctStr: string): number; - public TopLevelElementId: string;// '', - public EditorElementId: string;//'', - public AutoFillElementId: string;//'', - public ResolvedListElementId: string;//'', - public InitialHelpTextElementId: string;//'', - public WaitImageId: string;//'', - public HiddenInputId: string;//'', - public AllowEmpty: boolean;//true, - public ForceClaims: boolean;//false, - public AutoFillEnabled: boolean;//true, - public AllowMultipleUsers: boolean;//false, + + public TopLevelElementId: string; // '', + public EditorElementId: string; //'', + public AutoFillElementId: string; //'', + public ResolvedListElementId: string; //'', + public InitialHelpTextElementId: string; //'', + public WaitImageId: string; //'', + public HiddenInputId: string; //'', + public AllowEmpty: boolean; //true, + public ForceClaims: boolean; //false, + public AutoFillEnabled: boolean; //true, + public AllowMultipleUsers: boolean; //false, public OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public UrlZone: string;//null, - public AllUrlZones: boolean;//false, - public SharePointGroupID: number;//0, - public AllowEmailAddresses: boolean;//false, + public UrlZone: SP.UrlZone; //null, + public AllUrlZones: boolean; //false, + public SharePointGroupID: number; //0, + public AllowEmailAddresses: boolean; //false, public PPMRU: SPClientPeoplePickerMRU; - public UseLocalSuggestionCache: boolean;//true, - public CurrentQueryStr: string;//'', - public LatestSearchQueryStr: string;// '', + public UseLocalSuggestionCache: boolean; //true, + public CurrentQueryStr: string; //'', + public LatestSearchQueryStr: string; // '', public InitialSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - public VisibleSuggestions: number;//5, - public PrincipalAccountType: string;//'', + public VisibleSuggestions: number; //5, + public PrincipalAccountType: string; //'', public PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - public EnabledClaimProviders: string;//'', - public SearchPrincipalSource: SP.Utilities.PrincipalSource;//null, - public ResolvePrincipalSource: SP.Utilities.PrincipalSource;//null, - public MaximumEntitySuggestions: number;//30, - public EditorWidthSet: boolean;//false, - public QueryScriptInit: boolean;//false, - public AutoFillControl: string;//null, - public TotalUserCount: number;//0, - public UnresolvedUserCount: number;//0, - public UserQueryDict: ISPClientPeoplePickerEntity; - public ProcessedUserList: ISPClientPeoplePickerEntity; - public HasInputError: boolean;//false, - public HasServerError: boolean;//false, - public ShowUserPresence: boolean;//true, - public TerminatingCharacter: string;//';', - public UnresolvedUserElmIdToReplace: string;//'', - public WebApplicationID: SP.Guid;//'{00000000-0000-0000-0000-000000000000}', - + public EnabledClaimProviders: string; //'', + public SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, + public ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, + public MaximumEntitySuggestions: number; //30, + public EditorWidthSet: boolean; //false, + public QueryScriptInit: boolean; //false, + public AutoFillControl: SPClientAutoFill; //null, + public TotalUserCount: number; //0, + public UnresolvedUserCount: number; //0, + public UserQueryDict: { [index: string]: SP.StringResult }; + public ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; + public HasInputError: boolean; //false, + public HasServerError: boolean; //false, + public ShowUserPresence: boolean; //true, + public TerminatingCharacter: string; //';', + public UnresolvedUserElmIdToReplace: string; //'', + public WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', public GetAllUserInfo(): ISPClientPeoplePickerEntity[]; + + public SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void + public AddUserKeys(userKeys: string, bSearch: boolean): void; + public BatchAddUserKeysOperation(allKeys: string[], numProcessed: number); + public ResolveAllUsers(fnContinuation: () => void): void; + public ExecutePickerQuery(queryIds: string, onSuccess: (queryId: string, result: SP.StringResult) => void, onFailure: (queryId: string, result: SP.StringResult) => void, fnContinuation: () => void): void; + public AddUnresolvedUserFromEditor(bRunQuery?: boolean): void; + public AddUnresolvedUser(unresolvedUserObj: ISPClientPeoplePickerEntity, bRunQuery?: boolean): void; + public UpdateUnresolvedUser(results: SP.StringResult, user: ISPClientPeoplePickerEntity): void; + public AddPickerSearchQuery(queryStr: string): string; + public AddPickerResolveQuery(queryStr: string): string; + public GetPeoplePickerQueryParameters(): SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters; + public AddProcessedUser(userObject: ISPClientPeoplePickerEntity, fResolved?: boolean): string; + public DeleteProcessedUser(elmToRemove: HTMLElement): void; + public OnControlValueChanged(): void; + public OnControlResolvedUserChanged(): void; + public EnsureAutoFillControl(): void; + public ShowAutoFill(resultsTable: ISPClientAutoFillData[]): void; + public FocusAutoFill(): void; + public BlurAutoFill(): void; + public IsAutoFillOpen(): boolean; + public EnsureEditorWidth(): void; + public SetFocusOnEditorEnd(): void; + public ToggleWaitImageDisplay(bShowImage?: boolean): void; + public SaveAllUserKeysToHiddenInput(): void; + public GetCurrentEditorValue(): string; + public GetControlValueAsJSObject(): ISPClientPeoplePickerEntity[]; + public GetAllUserKeys(): string; + public GetControlValueAsText(): string; + public IsEmpty(): boolean; + public IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; + public HasResolvedUsers(): boolean; + public Validate(): void; + public ValidateCurrentState(): void + public GetUnresolvedEntityErrorMessage(): string; + public ShowErrorMessage(msg: string): void; + public ClearServerError(): void; + public SetServerError(): void; + public OnControlValidate(): void; + public SetEnabledState(bEnabled: boolean): void; + public DisplayLocalSuggestions(): void; + public CompileLocalSuggestions(input: string): void; + public PlanningGlobalSearch(): boolean; + public AddLoadingSuggestionMenuOption(): void; + public ShowingLocalSuggestions(): boolean; + public ShouldUsePPMRU(): boolean; + public AddResolvedUserToLocalCache(resolvedEntity: ISPClientPeoplePickerEntity, resolveText: string); } interface ISPClientPeoplePickerSchema { @@ -9583,11 +9514,38 @@ interface ISPClientPeoplePickerEntity { Department: string; Email: string; }; - MultipleMatches: Object[]; + MultipleMatches: ISPClientPeoplePickerEntity[]; DomainText?: string; [key: string]: any; } +declare class SPClientPeoplePickerProcessedUser { + UserContainerElementId: string;// '', + DisplayElementId: string;// '', + PresenceElementId: string;// '', + DeleteUserElementId: string;// '', + SID: string;// '', + DisplayName: string;// '', + SIPAddress: string;// '', + UserInfo: ISPClientPeoplePickerEntity;// null, + ResolvedUser: boolean;// true, + Suggestions: ISPClientAutoFillData[];// null, + ErrorDescription: string;// '', + ResolveText: string;// '', + public UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; + public UpdateSuggestions(entity: ISPClientPeoplePickerEntity); + public BuildUserHTML(): string; + public UpdateUserMaxWidth(): void; + public ResolvedAsUnverifiedEmail(): string; + + static BuildUserPresenceHtml(elmId: string, strSip: string, bResolved?: boolean): string; + static GetUserContainerElement(elmChild: HTMLElement): HTMLElement; + static HandleProcessedUserClick(ndClicked: HTMLElement): void; + static DeleteProcessedUser(elmToRemove: HTMLElement): void; + static HandleDeleteProcessedUserKey(e: Event): void; + static HandleResolveProcessedUserKey(e: Event): void; +} + declare module Microsoft { export module Office { export module Server { @@ -9757,4 +9715,1234 @@ declare module SPThemeUtils { export function Suspend(): void; } +declare module SP { + export module JsGrid { + export enum TextDirection { + Default, //0, + RightToLeft, //1, + LeftToRight //2 + } + + export enum PaneId { + MainGrid, //0, + PivotedGrid, //1, + Gantt //2 + } + + export enum PaneLayout { + GridOnly, //0, + GridAndGantt, //1, + GridAndPivotedGrid //2 + + } + export enum EditMode { + ReadOnly, //0, + ReadWrite, //1, + ReadOnlyDefer, //2, + ReadWriteDefer, //3, + Defer //4 + } + + export enum GanttDrawBarFlags { + LeftLink, //0x01, + RightLink //0x02 + + } + export enum GanttBarDateType { + Start, //0, + End //1 + } + + export enum ValidationState { + Valid, //0, + Pending, //1, + Invalid //2 + } + + export enum HierarchyMode { + None, //0, + Standard, //1, + Grouping //2 + } + + export enum EditActorWriteType { + Both, //1, + LocalizedOnly, //2, + DataOnly, //3, + Either //4 + } + + export enum EditActorReadType { + Both, //1, + LocalizedOnly, //2, + DataOnly //3 + } + + export enum EditActorUpdateType { + Committed, //0, + Uncommitted, //1 + } + + export enum SortMode { + Ascending, //1, + Descending, //-1, + None //0 + } + + export module RowHeaderStyleId { + export var Transfer: string; //'Transfer', + export var Conflict: string; //'Conflict' + + } + + export module RowHeaderAutoStyleId { + export var Dirty:string; //'Dirty', + export var Error: string; //'Error', + export var NewRow: string; //'NewRow' + } + + export enum RowHeaderStatePriorities { + Dirty, //10, + Transfer, //30, + CellError, //40, + Conflict, //50, + RowError, //60, + NewRow //90 + } + + export enum UpdateSerializeMode { + Cancel, //0, + Default, //1, + PropDataOnly, //2, + PropLocalizedOnly, //3, + PropBoth //4 + } + + export enum UpdateTrackingMode { + PropData, //2, + PropLocalized, //3, + PropBoth //4 + } + + export module UserAction { + export var UserEdit:string; //'User Edit':string; + export var DeleteRecord:string; //'Delete Record':string; + export var InsertRecord:string; //'Insert Record':string; + export var Indent:string; //'Indent':string; + export var Outdent:string; //'Outdent':string; + export var Fill:string; //'Fill':string; + export var Paste:string; //'Paste':string; + export var CutPaste: string; //'Cut/Paste' + } + + export enum ReadOnlyActiveState { + ReadOnlyActive, //0, + ReadOnlyDisabled, //1 + } + + export interface IValue { + data?: any; + localized?:string; + } + + + export class JsGridControl { + constructor(parentNode: HTMLElement, bShowLoadingBanner: boolean); + /** Returns true if Init method has been executed successfully */ + IsInitialized(): boolean; + /** Replaces the control TableCache object with the provided one */ + ResetData(cache: SP.JsGrid.TableCache): void; + /** Initialize the control */ + Init(parameters: SP.JsGrid.JsGridControl.Parameters): void; + Cleanup(): void; + /** Removes all event handlers and markup associated with the control */ + Dispose(): void; + + // todo + NotifyDataAvailable(): void; + NotifySave(): void; + NotifyHide(): void; + NotifyResize(): void; + ClearTableView(): void; + HideInitialLoadingBanner(): void; + ShowInitialGridErrorMsg(errorMsg: string): void; + ShowGridErrorMsg(errorMsg: string): void; + LaunchPrintView(additionalScriptFiles, beforeInitFnName, beforeInitFnArgsObj, title, bEnableGantt, optGanttDelegateNames, optInitTableViewParamsFnName, optInitTableViewParamsFnArgsObj, optInitGanttStylesFnName, optInitGanttStylesFnArgsObj): void; + GetAllDataJson(fnOnFinished, optFnGetCellStyleID?): void; + SetTableView(tableViewParams): void; + SetRowView(rowViewParams): void; + + /** Enable grid after Disable. */ + Enable(): void; + /** Covers the grid with the semi-transparent panel, preventing any operations with it. + Additionally, displays loading animated gif and optMsg as the message next to it. + If optMsg is not specified, displays "Loading..." text. */ + Disable(optMsg?: string): void; + /** Enables grid editing */ + EnableEditing(): void; + /** Disables grid editing: all the records become readonly */ + DisableEditing(): void; + /** Switches the currently selected cell into edit mode: displays edit control and sets focus into it. + Returns true if success. */ + TryBeginEdit(): boolean; + FinalizeEditing(fnContinue, fnError): void; + /** Get diff tracker object that tracks changes to the grid data. */ + GetDiffTracker(): SP.JsGrid.Internal.DiffTracker; + /** Moves focus to the JsGrid control */ + Focus(): void; + + /** Try saving the new record row (aka entry row) if it was edited. */ + TryCommitFirstEntryRecords(fnCommitComplete: { (): void }): void; + /** Removes all new record rows (aka entry rows), including unsaved and even empty ones. + The latter seems to be a bug, as I haven't found any easy way to restore the empty entry row. */ + ClearUncommitedEntryRecords(): void; + /** Returns true if there are any unsaved new record rows (aka entry rows). */ + AnyUncommitedEntryRecords(): boolean; + + + // todo + AnyUncomittedProvisionalRecords(): boolean; + + /** Gets record based on the recordKey + @recordKey internal unique id of a row. You can get recordKey from view index via GetRecordKeyByViewIndex method. */ + GetRecord(recordKey: number): IRecord; + /** Get entry record with the specified key. + Entry record is a special type of record because it represents a new record that doesn't exist yet. */ + GetEntryRecord(key): any; + /** Determine if the specified record key identifies valid entry row. */ + IsEntryRecord(recordKey: number): boolean; + /** Determine whether the specified cell is editable. */ + IsCellEditable(record: IRecord, fieldKey: string, optPaneId?): boolean; + /** Adds one of builtin row state indicator icons into the row header. + Please pass one of the values of SP.JsGrid.RowHeaderStyleId + Row header is the leftmost gray column of the table. */ + AddBuiltInRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + /** Adds the specified state into the row header. + There can be several row header states for one row. Only one is shown (according to the Priority). + Row header is the leftmost gray column of the table. */ + AddRowHeaderState(recordKey: number, rowHeaderState: SP.JsGrid.RowHeaderState): void; + /** Removes header state with specified id from the row. */ + RemoveRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + + GetCheckSelectionManager(): any; + UpdateProperties(propertyUpdates, changeName, optChangeKey?): any; + GetLastRecordKey(): string; + InsertProvisionalRecordBefore(beforeRecordKey: number, newRecord, initialValues): any; + InsertProvisionalRecordAfter(afterRecordKey: number, newRecord, initialValues): any; + IsProvisionalRecordKey(recordKey: number): boolean; + InsertRecordBefore(beforeRecordKey: number, newRecord, optChangeKey?): any; + InsertRecordAfter(afterRecordKey: number, newRecord, optChangeKey?): any; + InsertHiddenRecord(recordKey: number, changeKey, optAfterRecordKey?): any; + DeleteRecords(recordKeys, optChangeKey?): any; + IndentRecords(recordKeys, optChangeKey?): any; + OutdentRecords(recordKeys, optChangeKey?): any; + ReorderRecords(beginRecordKey: number, endRecordKey: number, afterRecordKey: number, bSelectAfterwards: boolean): any; + GetContiguousRowSelectionWithoutEntryRecords(): { begin; end; keys }; + CanMoveRecordsUpByOne(recordKeys): boolean; + CanMoveRecordsDownByOne(recordKeys): boolean; + MoveRecordsUpByOne(recordKeys): any; + MoveRecordsDownByOne(recordKeys): any; + GetReorderRange(recordKeys): any; + GetNodeExpandCollapseState(recordKey): any; + ToggleExpandCollapse(recordKey: number): void; + + /** Attach event handler to a particular event type */ + AttachEvent(eventType: JsGrid.EventType, fnOnEvent: { (args: IEventArgs): void }): void; + /** Detach a previously set event handler */ + DetachEvent(eventType: JsGrid.EventType, fnOnEvent): void; + + /** Set a delegate. Delegates are way to replace default functionality with custom one. */ + SetDelegate(delegateKey: JsGrid.DelegateType, fn): void; + /** Get current delegate. */ + GetDelegate(delegateKey: JsGrid.DelegateType): any; + + /** Re-render the specified row in the view. */ + RefreshRow(recordKey: number): void; + /** Re-render all rows in the view. + It can be used e.g. if you have some custom display controls and they are rendered differently depending on some external settings. + In this case, if you update the external settings, obviously you have to then update the view for these settings to take effect. */ + RefreshAllRows(): void; + /** Clears undo queue, and also differencies tracker state and versions manager state. */ + ClearChanges(): void; + + GetGanttZoomLevel(): any; + SetGanttZoomLevel(level: any): void; + ScrollGanttToDate(date): void; + + /** Get top record view index. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRecordIndex(): number; + /** Get number of rows displayed in the current view. */ + GetViewRecordCount(): number; + /** Get record key for a row that is specified by the viewIdx. + viewIdx - index of the row in the view, use GetTopRecordIndex to get the first one. + Returns recordKey, which is a unique numeric identifier of a row within a dataset. + Main difference between viewIdx and recordKey is that viewIdx is only unique within a view, + e.g. if you do paging, it can be same for different records. + */ + GetRecordKeyByViewIndex(viewIdx: number): number; + /** Opposite to GetRecordKeyByViewIndex, resolves the view index of the record based on record key. + recordKey - unique numeric identifier of a row in the current dataset. + Returns viewIdx - index of the row in the current view */ + GetViewIndexOfRecord(recordKey: number): number; + /** Get top row index. Usually returns 0. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRowIndex(): number; + + GetOutlineLevel(record): any; + GetSplitterPosition(): any; + SetSplitterPosition(pos): void; + GetLeftColumnIndex(optPaneId?): any; + EnsurePaneWidth(): void; + + /** Show a previously hidden column at a specified position. + If atIdx is not defined, column will be shown at it's previous position. */ + ShowColumn(columnKey: string, atIdx?: number): void; + /** Hide the specified column from grid */ + HideColumn(columnKey: string): void; + /** Update column descriptions */ + UpdateColumns(columnInfoCollection: ColumnInfoCollection): void; + GetColumns(optPaneId?): ColumnInfo[]; + /** Get ColumnInfo object by fieldKey + @fieldKey when working with SharePoint data sources, fieldKey corresponds to field internal name */ + GetColumnByFieldKey(fieldKey: string, optPaneId?): ColumnInfo; + /** Adds a column, based on the specified grid field */ + AddColumn(columnInfo: ColumnInfo, gridField: GridField): void; + + /** Switches column header in rename mode, showing textbox and thus giving the user possibility to rename this column. */ + RenameColumn(columnKey: string): void; + /** Shows a dialog where user can reorder columns and change their widths. */ + ShowColumnConfigurationDialog(): void; + + + /** Returns true, if there are any errors in the JsGrid */ + AnyErrors(): boolean; + /** Returns true, if there are any errors in a specified row */ + AnyErrorsInRecord(recordKey: number): boolean; + /** Set error for the specified by recordKey and fieldKey cell. + Returns id of the error, so that later you can clear the error using this id. */ + SetCellError(recordKey: number, fieldKey: string, errorMessage: string): number; + /** Set error for the specified by recordKey row. + In the leftmost column of this row, exclamation mark error indicator will appear. + Clicking on this indicator will cause the specified error message appear in form of a reddish tooltip. + Returns id of the error, so that later you can clear the error using this id. */ + SetRowError(recordKey: number, errorMessage: string): number; + /** Clear specified by id error that was previously set on the specified by recordKey and fieldKey cell. */ + ClearCellError(recordKey: number, fieldKey: string, id: number): void; + /** Clear all errors in the specified cell. */ + ClearAllErrorsOnCell(recordKey: number, fieldKey: string): void; + /** Clear specified by id error that was previously set on the specified by recordKey row. */ + ClearRowError(recordKey: number, id: number): void; + /** Clear all errors in the specified row. */ + ClearAllErrorsOnRow(recordKey: number): void; + /** Get error message for the specified cell. + If many errors are set on the cell, only first is returned. + If there are no errors in the cell, returns null. */ + GetCellErrorMessage(recordKey: number, fieldKey: string): string; + /** Get error message for the specified row. + If many errors are set on the row, only first is returned. + If there are no errors in the row, returns null. */ + GetRowErrorMessage(recordKey: number): string; + /** This method is used mostly when you have a rather tall JSGrid and you want to ensure that user sees + that some error has occured. + You can specify the minId or/and filter function. + If minId is specified, method searches for an error with first id which is greater than minId. + Scrolls to the Returns the id of the found record. + If there aren't any errors, that satisfy the conditions, method does nothing and returns null. */ + ScrollToAndExpandNextError(minId?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }): any; + /** Same as ScrollToAndExpandNextError, but searches within the specified record. + recordKey should be not null, otherwise you'll get an exception. + bDontExpand controls whether the error tooltip will be shown (if bDontExpand=true, tooltip will not be shown). */ + ScrollToAndExpandNextErrorOnRecord(minId?: number, recordKey?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }, bDontExpand?: boolean): any; + + GetFocusedItem(): any; + SendKeyDownEvent(eventInfo:Sys.UI.DomEvent): any; + /** Moves cursor to entry record (the row that is used to add new records) */ + JumpToEntryRecord(): void; + + SelectRowRange(rowIdx1, rowIdx2, bAppend, optPaneId?): void; + SelectColumnRange(colIdx1, colIdx2, bAppend, optPaneId?): void; + SelectCellRange(rowIdx1, rowIdx2, colIdx1, colIdx2, bAppend, optPaneId): void; + SelectRowRangeByKey(rowKey1, rowKey2, bAppend, optPaneId?): void; + SelectColumnRangeByKey(colKey1, colKey2, bAppend, optPaneId?): void; + SelectCellRangeByKey(recordKey1: string, recordKey2: string, colKey1, colKey2, bAppend, optPaneId?): void; + + ChangeKeys(oldKey, newKey): void; + GetSelectedRowRanges(optPaneId?): any; + GetSelectedColumnRanges(optPaneId?): any; + GetSelectedRanges(optPaneId?): any; + MarkPropUpdateInvalid(recordKey: number, fieldKey, changeKey, optErrorMsg?): any; + GetCurrentChangeKey(): any; + CreateAndSynchronizeToNewChangeKey(): any; + CreateDataUpdateCmd(bUseCustomInitialUpdate: boolean): any; + IsChangeKeyApplied(changeKey): any; + GetChangeKeyForVersion(version): any; + TryReadPropForChangeKey(recordKey: number, fieldKey, changeKey): any; + GetUnfilteredHierarchyMap(): any; + GetHierarchyState(bDecompressGuidKeys: boolean): any; + IsGroupingRecordKey(recordKey: number): boolean; + IsGroupingColumnKey(recordKey: number): boolean; + GetSelectedRecordKeys(bDuplicatesAllowed: boolean): any; + /** Cut data from currently selected cells into the clipboard. + Will not work if current selection contains entry row or readonly cells. */ + CutToClipboard(): void; + /** Copy data from currently selected cells into the clipboard. */ + CopyToClipboard(): void; + /** Paste data from clipboard into currently selected cells. */ + PasteFromClipboard(): void; + TryRestoreFocusAfterInsertOrDeleteColumns(origFocus): void; + /** Get undo manager for performing undo/redo operations programmatically. */ + GetUndoManager(): SP.JsGrid.CommandManager; + /** Gets number of records visible in the current view, including the entry row. */ + GetVisibleRecordCount(): number; + /** Returns index of the system RecordIndicatorCheckBoxColumn. If not present in the view, returns null. */ + GetRecordIndicatorCheckBoxColumnIndex(): number; + /** Determines if the specified record is visible in the current view. */ + IsRecordVisibleInView(recordKey: number): boolean; + GetHierarchyQueryObject(): any; + GetSpCsrRenderCtx(): any; + } + + export interface IChangeKey { + Reserve(): void; + Release(): void; + GetVersionNumber(): number; + CompareTo(changeKey: IChangeKey): number; + } + + export enum EventType { + OnCellFocusChanged, + OnRowFocusChanged, + OnCellEditBegin, + OnCellEditCompleted, + OnRightClick, + OnPropertyChanged, + OnRecordInserted, + OnRecordDeleted, + OnRecordChecked, + OnCellErrorStateChanged, + OnEntryRecordAdded, + OnEntryRecordCommitted, + OnEntryRecordPropertyChanged, + OnRowErrorStateChanged, + OnDoubleClick, + OnBeforeGridDispose, + OnSingleCellClick, + OnInitialChangesForChangeKeyComplete, + OnVacateChange, + OnGridErrorStateChanged, + OnSingleCellKeyDown, + OnRecordsReordered, + OnBeforePropertyChanged, + OnRowEscape, + OnBeginRenameColumn, + OnEndRenameColumn, + OnPasteBegin, + OnPasteEnd, + OnBeginRedoDataUpdateChange, + OnBeginUndoDataUpdateChange + } + + export enum DelegateType { + ExpandColumnMenu, + AddColumnMenuItems, + Sort, + Filter, + InsertRecord, + DeleteRecords, + IndentRecords, + OutdentRecords, + IsRecordInsertInView, + ExpandDelayLoadedHierarchyNode, + AutoFilter, + ExpandConflictResolution, + GetAutoFilterEntries, + LaunchFilterDialog, + ShowColumnConfigurationDialog, + GetRecordEditMode, + GetGridRowStyleId, + CreateEntryRecord, + TryInsertEntryRecord, + WillAddColumnMenuItems, + NextPage, + AddNewColumn, + RemoveColumnFromView, + ReorderColumnPositionInView, + TryCreateProvisionalRecord, + CanReorderRecords, + AddNewColumnMenuItems, + TryBeginPaste, + AllowSelectionChange, + GetFieldEditMode, + GetFieldReadOnlyActiveState, + OnBeforeRecordReordered + } + + export enum ClickContext { + SelectAllSquare, + RowHeader, + ColumnHeader, + Cell, + Gantt, + Other + } + + export class RowHeaderState { + constructor(id: string, img: SP.JsGrid.Image, priority: SP.JsGrid.RowHeaderStatePriorities, tooltip: string, fnOnClick: { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }); + GetId(): string; + GetImg(): SP.JsGrid.Image; + GetPriority(): SP.JsGrid.RowHeaderStatePriorities; + GetOnClick(): { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }; + GetTooltip(): string; + toString(): string; + } + + export class Image { + /** optOuterCssNames and optImgCssNames are strings that contain css class names separated by spaces. + optImgCssNames are applied to the img tag. + if bIsClustered, image is rendered inside div, and optOuterCssNames are applied to the div. */ + constructor(imgSrc: string, bIsClustered: boolean, optOuterCssNames: string, optImgCssNames: string, bIsAnimated: boolean); + imgSrc: string; + bIsClustered: boolean; + optOuterCssNames: string; + imgCssNames: string; + bIsAnimated: boolean; + /** Renders the image with specified alternative text and on-click handler. + If bHideTooltip == false, then alternative text is also shown as the tooltip (title attribute). */ + Render(altText: string, clickFn: { (eventInfo:Sys.UI.DomEvent): void }, bHideTooltip: boolean): HTMLElement; + } + + export interface IEventArgs { } + export module EventArgs { + export class OnEntryRecordAdded implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + + export class CellFocusChanged implements IEventArgs { + constructor(newRecordKey: number, newFieldKey: string, oldRecordKey: number, oldFieldKey: string); + newRecordKey: number; + newFieldKey: string; + oldRecordKey: number; + oldFieldKey: string; + } + export class RowFocusChanged implements IEventArgs { + constructor(newRecordKey: number, oldRecordKey: number); + newRecordKey: number; + oldRecordKey: number; + } + export class CellEditBegin implements IEventArgs { + constructor(recordKey: number, fieldKey: string); + recordKey: number; + fieldKey: string; + } + export class CellEditCompleted implements IEventArgs { + constructor(recordKey: number, fieldKey: string, changeKey: JsGrid.IChangeKey, bCancelled: boolean); + recordKey: number; + fieldKey: string; + changeKey: JsGrid.IChangeKey; + bCancelled: boolean; + } + export class Click implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, context: JsGrid.ClickContext, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + context: JsGrid.ClickContext; + recordKey: number; + fieldKey: string; + } + export class PropertyChanged implements IEventArgs { + constructor(recordKey: number, fieldKey: string, oldProp: SP.JsGrid.Internal.PropertyUpdate, newProp: SP.JsGrid.Internal.PropertyUpdate, propType: SP.JsGrid.IPropertyType, changeKey: SP.JsGrid.IChangeKey, validationState: SP.JsGrid.ValidationState); + recordKey: number; + fieldKey: string; + oldProp: SP.JsGrid.Internal.PropertyUpdate; + newProp: SP.JsGrid.Internal.PropertyUpdate; + propType: SP.JsGrid.IPropertyType; + changeKey: SP.JsGrid.IChangeKey; + validationState: SP.JsGrid.ValidationState; + } + export class RecordInserted implements IEventArgs { + constructor(recordKey, recordIdx, afterRecordKey, changeKey); + recordKey: number; + recordIdx: number; + afterRecordKey: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordDeleted implements IEventArgs { + constructor(recordKey, recordIdx, changeKey); + recordKey: number; + recordIdx: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordChecked implements IEventArgs { + constructor(recordKeySet: SP.Utilities.Set, bChecked: boolean); + recordKeySet: SP.Utilities.Set; + bChecked: boolean; + } + export class OnCellErrorStateChanged implements IEventArgs { + constructor(recordKey, fieldKey, bAddingError, bCellCurrentlyHasError, bCellHadError, errorId); + recordKey: number; + fieldKey: string; + bAddingError: boolean; + bCellCurrentlyHasError: boolean; + bCellHadError: boolean; + errorId: number; + } + export class OnRowErrorStateChanged implements IEventArgs { + constructor(recordKey, bAddingError, bErrorCurrentlyInRow, bRowHadError, errorId, message); + recordKey: number; + bAddingError: boolean; + bErrorCurrentlyInRow: boolean; + bRowHadError: boolean; + errorId: number; + message: string; + } + export class OnEntryRecordCommitted implements IEventArgs { + constructor(origRecKey: string, recordKey: number, changeKey: JsGrid.IChangeKey); + originalRecordKey: number; + recordKey: number; + changeKey: JsGrid.IChangeKey + } + export class SingleCellClick implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class PendingChangeKeyInitiallyComplete implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class VacateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class GridErrorStateChanged implements IEventArgs { + constructor(bAnyErrors: boolean); + bAnyErrors: boolean; + } + export class SingleCellKeyDown implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class OnRecordsReordered implements IEventArgs { + constructor(recordKeys: string[], changeKey: JsGrid.IChangeKey); + reorderedKeys: string[]; + changeKey: JsGrid.IChangeKey; + } + export class OnRowEscape implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + export class OnEndRenameColumn implements IEventArgs { + constructor(columnKey: string, originalColumnTitle: string, newColumnTitle: string); + columnKey: string; + originalColumnTitle: string; + newColumnTitle: string; + } + export class OnBeginRedoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class OnBeginUndoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + + } + + export module JsGridControl { + export class Parameters { + tableCache: SP.JsGrid.TableCache; + name: any; // TODO + bNotificationsEnabled: boolean; + styleManager: IStyleManager; + minHeaderHeight: number; + minRowHeight: number; + commandMgr: SP.JsGrid.CommandManager; + enabledRowHeaderAutoStates: SP.Utilities.Set; + } + } + + export class CommandManager { + // todo + } + + export class TableCache { + // todo + } + + export interface IStyleManager { + gridPaneStyle: IStyleType.GridPane; + columnHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + rowHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + splitterStyleCollection: { + normal: IStyleType.Splitter; + normalHandle: IStyleType.SplitterHandle; + hover: IStyleType.Splitter; + hoverHandle: IStyleType.SplitterHandle; + dra: IStyleType.Splitter; + dragHandle: IStyleType.SplitterHandle; + }; + defaultCellStyle: IStyleType.Cell; + readOnlyCellStyle: IStyleType.Cell; + readOnlyFocusedCellStyle: IStyleType.Cell; + timescaleTierStyle: IStyleType.TimescaleTier; + groupingStyles: any[]; + widgetDockStyle: IStyleType.Widget; + widgetDockHoverStyle: IStyleType.Widget; + widgetDockPressedStyle: IStyleType.Widget; + RegisterCellStyle(styleId: string, cellStyle: IStyleType.Cell): void; + GetCellStyle(styleId: string): IStyleType.Cell; + UpdateSplitterStyleFromCss(styleObject: IStyleType.Splitter, splitterStyleNameCollection): void; + UpdateHeaderStyleFromCss(styleObject: IStyleType.Header, headerStyleNameCol): void; + UpdateGridPaneStyleFromCss(styleObject: IStyleType.GridPane, gridStyleNameCollection): void; + UpdateDefaultCellStyleFromCss(styleObject: IStyleType.Cell, cssClass): void; + UpdateGroupStylesFromCss(styleObject, prefix): void; + } + + export interface IStyleType { } + export module IStyleType { + export interface Splitter extends IStyleType { + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + } + export interface SplitterHandle extends IStyleType{ + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + gripUpperColor: any; + gripLowerColor: any; + } + export interface GridPane { + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + backgroundColor: any; + columnDropIndicatorColor: any; + rowDropIndicatorColor: any; + linkColor: any; + visitedLinkColor: any; + copyRectForeBorderColor: any; + copyRectBackBorderColor: any; + focusRectBorderColor: any; + selectionRectBorderColor: any; + selectedCellBgColor: any; + readonlySelectionRectBorderColor: any; + changeHighlightCellBgColor: any; + fillRectBorderColor: any; + errorRectBorderColor: any; + } + export interface Header { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + eyeBrowBorderColor: any; + eyeBrowColor: any; + menuColor: any; + menuBorderColor: any; + resizeColor: any; + resizeBorderColor: any; + menuHoverColor: any; + menuHoverBorderColor: any; + resizeHoverColor: any; + resizeHoverBorderColor: any; + eyeBrowHoverColor: any; + eyeBrowHoverBorderColor: any; + elementClickColor: any; + elementClickBorderColor: any; + } + export interface Cell extends IStyleType { + /** -> CSS font-family */ + font: any; + /** -> CSS font-size */ + fontSize: any; + /** -> CSS font-weight */ + fontWeight: any; + /** -> CSS font-style */ + fontStyle: any; + /** -> CSS color */ + textColor: any; + /** -> CSS background-color */ + backgroundColor: any; + /** -> CSS text-align */ + textAlign: any; + } + export interface Widget { + backgroundColor: any; + borderColor: any; + } + export interface RowHeaderStyle { + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + } + export interface TimescaleTier { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + outerBorderColor: any; + todayLineColor: any; + } + } + + export class Style { + + static Type: { + Splitter: IStyleType.Splitter; + SplitterHandle: IStyleType.SplitterHandle; + GridPane: IStyleType.GridPane; + Header: IStyleType.Header; + RowHeaderStyle: IStyleType.RowHeaderStyle; + TimescaleTier: IStyleType.TimescaleTier; + Cell: IStyleType.Cell; + Widget: IStyleType.Widget; + }; + + static SetRTL: { (rtlObject): void; }; + static MakeJsGridStyleManager: { (): IStyleManager }; + static CreateStyleFromCss: { (styleType: IStyleType, cssStyleName: string, optExistingStyle, optClassId): any; }; + static CreateStyle: { (styleType: IStyleType, styleProps: any): any; }; + static MergeCellStyles: { (majorStyle, minorStyle): any; }; + static ApplyCellStyle: { (td, style): void; }; + static ApplyRowHeaderStyle: { (domObj, style, fnGetHeaderSibling): void; }; + static ApplyCornerHeaderBorderStyle: { (domObj, colStyle, rowStyle): void; }; + static ApplyHeaderInnerBorderStyle: { (domObj, bIsRowHeader, headerObject): void }; + static ApplyColumnContextMenuStyle: { (domObj, style): void }; + static ApplySplitterStyle: { (domObj, style): void }; + static MakeBorderString: { (width: number, style: string, color: string): string }; + static GetCellStyleDefaultBackgroundColor: { (): string }; + + } + + export class ColumnInfoCollection { + constructor(colInfoArray: any[]); + GetColumnByKey(key: string): any; + GetColumnArray(bVisibleOnly?: boolean): any[]; + GetColumnMap(): { [key: string]: any; }; + AppendColumn(colInfo: any): void; + InsertColumnAt(idx: number, colInfo: any): void; + RemoveColumn(key: string): void; + /** Returns null if the specified column is not found or hidden. */ + GetColumnPosition(key: string): number; + } + + export class ColumnInfo { + constructor(name: string, imgSrc: string, key: string, width: number); + /** Column title */ + name: string; + /** Column image URL. + If not null, the column header cell will show the image instead of title text. + If the title is defined at the same time as the imgSrc, the title will be shown as a tooltip. */ + imgSrc: string; + /** Custom image HTML. + If you define this in addition to the imgSrc attribute, then instead of standard img tag + the custom HTML defined by this field will be used. */ + imgRawSrc: string; + /** Column identifier */ + columnKey: string; + /** Field keys of the fields, that are displayed in this column */ + fieldKeys: string[]; + /** Width of the column */ + width: number; + bOpenMenuOnContentClick: boolean; + /** always returns 'column' */ + ColumnType(): string; + /** true by default */ + isVisible: boolean; + /** true by default */ + isHidable: boolean; + /** true by default */ + isResizable: boolean; + /** true by default */ + isSortable: boolean; + /** true by default */ + isAutoFilterable: boolean; + /** false by default */ + isFooter: boolean; + /** determine whether the cells in this column should be clickable */ + fnShouldLinkSingleValue: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): boolean }; + /** if a particular cell is determined as clickable by fnShouldLinkSingleValue, this function will be called when the cell is clicked */ + fnSingleValueClicked: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): void }; + /** this is used when you need to make some of the cells in the column readonly, but at the same time keep others editable */ + fnGetCellEditMode: { (record: IRecord, fieldKey: string): JsGrid.EditMode }; + /** this function should return name of the display control for the given cell in the column + the name should be previously associated with the display control via SP.JsGrid.PropertyType.Utils.RegisterDisplayControl method */ + fnGetDisplayControlName: { (record: IRecord, fieldKey: string): string }; + /** this function should return name of the edit control for the given cell in the column + the name should be previously associated with the edit control via SP.JsGrid.PropertyType.Utils.RegisterEditControl method */ + fnGetEditControlName: { (record: IRecord, fieldKey: string): string }; + /** set widget control names for a particular cell + widgets are basically in-cell buttons with associated popup controls, e.g. date selector or address book button + standard widget ids are defined in the SP.JsGrid.WidgetControl.Type enumeration + it is also possible to create your own widgets + usually this function is not used, and instead, widget control names are determined via PropertyType + */ + fnGetWidgetControlNames: { (record: IRecord, fieldKey: string): string[] }; + /** this function should return id of the style for the given cell in the column + styles and their ids are registered for a JsGridControl via jsGridParams.styleManager.RegisterCellStyle method */ + fnGetCellStyleId: { (record: IRecord, fieldKey: string, dataValue: any): string }; + /** set custom tooltip for the given cell in the column. by default, localized value is displayed as the tooltip */ + fnGetSingleValueTooltip: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): string }; + } + + + export interface IRecord { + /** True if this is an entry row */ + bIsNewRow: boolean; + + /** Please use SetProp and GetProp */ + properties: { [fieldKey: string]: IPropertyBase }; + + /** returns recordKey */ + key(): number; + /** returns raw data value for the specified field */ + GetDataValue(fieldKey: string): any; + /** returns localized text value for the specified field */ + GetLocalizedValue(fieldKey: string): string; + /** returns true if data value for the specified field is available */ + HasDataValue(fieldKey: string): boolean; + /** returns true if localized text value for the specified field is available */ + HasLocalizedValue(fieldKey: string): boolean; + + GetProp(fieldKey: string): IPropertyBase; + SetProp(fieldKey: string, prop: IPropertyBase): void; + + /** Update the specified field with the specified value */ + AddFieldValue(fieldKey: string, value: any): void; + /** Removes value of the specified field. + Does not refresh the view. */ + RemoveFieldValue(fieldKey: string): void; + } + + + export class RecordFactory { + constructor(gridFieldMap: any, keyColumnName: string, fnGetPropType: any); + gridFieldMap: any; + /** Create a new record */ + MakeRecord(dataPropMap, localizedPropMap, bKeepRawData): IRecord; + } + + export interface IPropertyBase { + HasLocalizedValue(): boolean; + HasDataValue(): boolean; + Clone(): IPropertyBase; + /** dataValue actually is cloned */ + Update(dataValue: any, localizedValue: string): void; + GetLocalized(): string; + GetData(): any; + } + + export class Property { + static MakeProperty(dataValue: any, localizedValue: string, bHasDataValue: boolean, bHasLocalizedValue: boolean, propType): IPropertyBase; + static MakePropertyFromGridField(gridField: any, dataValue: any, localizedVal: string, optPropType?): IPropertyBase; + } + + export class GridField { + constructor(key: string, hasDataValue: boolean, hasLocalizedValue: boolean, textDirection, defaultCellStyleId, editMode, dateOnly, csrInfo); + key: string; + hasDataValue: boolean; + hasLocalizedValue: boolean; + textDirection: any; + dateOnly: boolean; + csrInfo: any; + GetEditMode(): any; + SetEditMode(mode: any): void; + GetDefaultCellStyleId(): any; + CompareSingleDataEqual(dataValue1, dataValue2): boolean; + GetPropType(): any; + GetSingleValuePropType(): any; + GetMultiValuePropType(): any; + SetSingleValuePropType(svPropType: any): void; + SetIsMultiValue(listSeparator: any): void; + GetIsMultiValue(): boolean; + } + + export interface IEditActorGridContext { + jsGridObj: JsGridControl; + parentNode: HTMLElement; + styleManager: IStyleManager; + RTL: any; + emptyValue: any; + bLightFocus: boolean; + OnKeyDown: { (domEvent: Sys.UI.DomEvent): void; }; + } + + export interface IEditControlGridContext extends IEditActorGridContext { + OnActivateActor(): void; + OnDeactivateActor():void; + } + + export interface IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + } + + export interface ILookupPropertyType extends IPropertyType { + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + } + + export interface IMultiValuePropertyType extends IPropertyType { + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + + export class PropertyType { + /** Lookup property type factory, based on SP.JsGrid.PropertyType.LookupTable class. + displayCtrlName should be one of the following: SP.JsGrid.DisplayControl.Type.Image, SP.JsGrid.DisplayControl.Type.ImageText or SP.JsGrid.DisplayControl.Type.Text + */ + static RegisterNewLookupPropType(id: string, items: any[], displayCtrlName: string, bLimitToList: boolean): void; + + /** Register a custom property type. */ + static RegisterNewCustomPropType(propType: IPropertyType, displayCtrlName: string, editControlName: string, widgetControlNames: string[]): void; + + /** Register a custom property type, where display and edit controls, and also widgets, are derived from the specified parent property type. */ + static RegisterNewDerivedCustomPropType(propType: IPropertyType, baseTypeName: string): void; + } + + export module PropertyType { + export class String implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + toString(): string; + } + export class LookupTable implements ILookupPropertyType { + constructor(items: any[], id: string, bLimitToList: boolean); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + + } + export class CheckBoxBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class DropDownBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class MultiValuePropType implements IMultiValuePropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + export class HyperLink implements IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bHyperlink: boolean; + DataToLocalized(dataValue: any): string; + GetAddress(dataValue: any): string; + /** Returns string like this: '"http://site.com, Site title"' */ + GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; + toString(): string; + } + + + export class Utils { + static RegisterDisplayControl(name: string, singleton, requiredFunctionNames: string[]); + static RegisterEditControl(name: string, factory: (gridContext: IEditControlGridContext, gridTextInputElement:HTMLElement) => IEditControl, requiredFunctionNames: string[]); + static RegisterWidgetControl(name: string, factory: { (ddContext): IPropertyType; }, requiredFunctionNames: string[]); + + static UpdateDisplayControlForPropType(propTypeName: string, displayControlType: string); + } + } + + export module WidgetControl { + export class Type { + static Demo: string; + static Date: string; + static AddressBook: string; + static Hyperlink: string; + } + } + + export module Internal { + export class DiffTracker { + constructor(objBag, fnGetChange); + ExternalAPI: { + AnyChanges(): boolean; + ChangeKeySliceInfo(): any; + ChangeQuery(): any; + EventSliceInfo(): any; + GetChanges(optStartEvent, optEndEvent, optRecordKeys, bFirstStartEvent: boolean, bStartInclusive: boolean, bEndInclusive: boolean, bIncludeInvalidPropUpdates: boolean, bLastEndEvent: boolean): any; + GetChangesAsJson(changeQuery, optfnPreProcessUpdateForSerialize?): string; + GetUniquePropertyChanges(changeQuery, optfnFilter): any; + RegisterEvent(changeKey: IChangeKey, eventObject): void; + UnregisterEvent(changeKey: IChangeKey, eventObject): void; + }; + Clear(): void; + NotifySynchronizeToChange(changeKey: IChangeKey): void; + NotifyRollbackChange(changeKey: IChangeKey): void; + NotifyVacateChange(changeKey: IChangeKey): void; + } + + export class PropertyUpdate implements IValue { + constructor(data: any, localized: string); + data: any; + localized: string; + } + } + + export interface IEditActorCellContext { + propType:IPropertyType; + originalValue:IValue; + record:IRecord; + column:ColumnInfo; + field:GridField; + fieldKey:string; + cellExpandSpace:{ left:number; top:number; fight:number; bottom:number; }; + SetCurrentValue(value): void; + } + + export interface IEditControlCellContext extends IEditActorCellContext{ + cellWidth: number; + cellHeight: number; + cellStyle: any; //TODO: Determine correct type + cellRect:any; + NotifyExpandControl(): void; + NotifyEditComplete(): void; + Show(element: HTMLElement): void; + Hide(element: HTMLElement): void; + } + + + export module EditControl { + + } + + export interface IEditControl { + SupportedWriteMode?: SP.JsGrid.EditActorWriteType; + SupportedReadMode?: SP.JsGrid.EditActorReadType; + GetCellContext? (): IEditControlCellContext; + GetOriginalValue?():IValue; + SetValue?(value:IValue):void; + Dispose():void; + GetInputElement?():HTMLElement; + Focus?(eventInfo:Sys.UI.DomEvent):void; + BindToCell (cellContext: IEditControlCellContext):void; + OnBeginEdit (eventInfo: Sys.UI.DomEvent):void; + Unbind():void; + OnEndEdit():void; + OnCellMove?():void; + OnValueChanged?(newValue: IValue):void; + IsCurrentlyUsingGridTextInputElement?(): boolean; + SetSize?(width:number, height:number):void; + } + + } + + export module Utilities { + export class Set { + constructor(items?: { [item: string]: number }); + constructor(items?: { [item: number]: number }); + /** Returns true if the set is empty */ + IsEmpty(): boolean; + /** Returns first item in the set */ + First(): any; + /** Returns the underlying collection of items as dictionary. + Items are the keys, and values are always 1. + So the return value may be either { [item: string]: number } or { [item: number]: number } */ + GetCollection(): any; + /** Returns all items from the set as an array */ + ToArray(): any[]; + /** Adds all items from array to the set, and returns the set */ + AddArray(array: any[]): SP.Utilities.Set; + /** Adds an item to the set */ + Add(item: any): any; + /** Removes the specified item from the set and returns the removed item */ + Remove(item: any): any; + /** Clears all the items from set */ + Clear(): SP.Utilities.Set; + /** Returns true if item exists in this set */ + Contains(item: any): boolean; + /** Returns a copy of this set */ + Clone(): SP.Utilities.Set; + /** Returns a set that contains all the items that exist only in one of the sets (this and other), but not in both */ + SymmetricDifference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a set that contains all the items that are in this set but not in the otherSet */ + Difference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains items from this set and otherSet */ + Union(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Adds all items from otherSet to this set, and returns this set */ + UnionWith(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains only items that exist both in this set and the otherSet */ + Intersection(otherSet: SP.Utilities.Set): SP.Utilities.Set; + } + } +} + + + + + +declare module SP { + export class GanttControl { + static WaitForGanttCreation(callack: (control: GanttControl) => void): void; + static Instances: GanttControl[]; + static FnGanttCreationCallback: { (control: GanttControl): void }[]; + + get_Columns():SP.JsGrid.ColumnInfo[]; + } +} From c6a507446a0fc58043d1bc12a609b0ac5f9a212e Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:29:19 +0300 Subject: [PATCH 02/11] Fixed couple bugs --- sharepoint/SharePoint.d.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 026658ef8..65e1f63a4 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ // Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -159,6 +159,7 @@ declare class _spPageContextInfo { static currentUICultureName: string; //"ru-RU" static layoutsUrl: string; //"_layouts/15" static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static pageItemId: number; static pagePersonalizationScope: string; //1 static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" @@ -2440,7 +2441,7 @@ declare module SP { get_webId(): SP.Guid; getErrorDetails(): SP.ClientObjectList; uninstall(): SP.GuidResult; - upgrade(appPackageStream: any[]): void; + upgrade(appPackageStream: SP.Base64EncodedByteArray): void; cancelAllJobs(): SP.BooleanResult; install(): SP.GuidResult; getPreviousAppVersion(): SP.App; @@ -2515,8 +2516,8 @@ declare module SP { getByFileName(fileName: string): SP.Attachment; } export class AttachmentCreationInformation extends SP.ClientValueObject { - get_contentStream(): any[]; - set_contentStream(value: any[]): void; + get_contentStream(): SP.Base64EncodedByteArray; + set_contentStream(value: SP.Base64EncodedByteArray): void; get_fileName(): string; set_fileName(value: string): void; get_typeId(): string; @@ -3243,7 +3244,7 @@ declare module SP { boolean, number, currency, - uRL, + URL, computed, threading, guid, @@ -4812,9 +4813,9 @@ declare module SP { getSubwebsForCurrentUser(query: SP.SubwebQuery): SP.WebCollection; getAppInstanceById(appInstanceId: SP.Guid): SP.AppInstance; getAppInstancesByProductId(productId: SP.Guid): SP.ClientObjectList; - loadAndInstallAppInSpecifiedLocale(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadApp(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadAndInstallApp(appPackageStream: any[]): SP.AppInstance; + loadAndInstallAppInSpecifiedLocale(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadApp(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadAndInstallApp(appPackageStream: SP.Base64EncodedByteArray): SP.AppInstance; ensureUser(logonName: string): SP.User; applyTheme(colorPaletteUrl: string, fontSchemeUrl: string, backgroundImageUrl: string, shareGenerated: boolean): void; } From e53377052eb6bbb0307404938e728dd91b804103 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:48:28 +0300 Subject: [PATCH 03/11] Refactored microsoft.ajax.d.ts to compile with SharePoint.d.ts From e0ca94ea1317c51994d7dc1320601f99c127032a Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:49:32 +0300 Subject: [PATCH 04/11] Added spgantt definitions (not finished yet) to SharePoint.d.ts From 14a3909c9171566e377a8cda78ee3f54711e8a5d Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:55:16 +0300 Subject: [PATCH 05/11] Refactored SharePoint.d.ts to TypeScript 1.4 (union types) From 160132fdad7baa693eaf3af1ea31334a462278c3 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:58:09 +0300 Subject: [PATCH 06/11] Added and fixed definitions for dialogs in SharePoint.d.ts From db8c5956c24ee413134e0ffdf9b097c8f799d8b7 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 19:01:31 +0300 Subject: [PATCH 07/11] Backported SharePoint.d.ts changes fom master From 31c2a4dc3f9bbb8060ca9d846c03af0aa1a0ac06 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Tue, 14 Jul 2015 00:09:21 +0300 Subject: [PATCH 08/11] Added tests for SharePoint.d.ts --- sharepoint/SharePoint-tests.ts | 2043 +++++++++++++++++++++++++++++++- 1 file changed, 2042 insertions(+), 1 deletion(-) diff --git a/sharepoint/SharePoint-tests.ts b/sharepoint/SharePoint-tests.ts index 83934008c..0e6b53e54 100644 --- a/sharepoint/SharePoint-tests.ts +++ b/sharepoint/SharePoint-tests.ts @@ -1,5 +1,11 @@ /// +/// +/// +/// + +//code from http://sptypescript.codeplex.com/ +//BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel:HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -522,4 +528,2039 @@ function deleteListItem(resultpanel: HTMLElement) { function errorHandler() { resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); } -} \ No newline at end of file +} + + + +/** Lightweight client-side rendering template overrides.*/ +module CSR { + + export interface UpdatedValueCallback { + (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; + } + + /** Creates new overrides. Call .register() at the end.*/ + export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + return new csr(listTemplateType, baseViewId) + .onPreRender(hookFormContext) + .onPostRender(fixCsrCustomLayout); + + function hookFormContext(ctx: IFormRenderContexWithHook) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + + for (var i = 0; i < ctx.ListSchema.Field.length; i++) { + var fieldSchemaInForm = ctx.ListSchema.Field[i]; + + if (!ctx.FormContextHook) { + ctx.FormContextHook = {} + + var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; + ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { + ctx.FormContextHook[fieldName].getValue = callback; + oldRegisterGetValueCallback(fieldName, callback); + }; + + var oldUpdateControlValue = ctx.FormContext.updateControlValue; + ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { + oldUpdateControlValue(fieldName, value); + + var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); + hookedContext.lastValue = value; + + var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; + for (var i = 0; i < updatedCallbacks.length; i++) { + updatedCallbacks[i](value, hookedContext.fieldSchema); + } + + } + } + ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; + } + } + } + + function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + return; + } + + if (ctx.ListSchema.Field.length > 1) { + var wpq = ctx.FormUniqueId; + var webpart = $get('WebPart' + wpq); + var forms = webpart.getElementsByClassName('ms-formtable'); + + if (forms.length > 0) { + var placeholder = $get(wpq + 'ClientFormTopContainer'); + var fragment = document.createDocumentFragment(); + for (var i = 0; i < placeholder.children.length; i++) { + fragment.appendChild(placeholder.children.item(i)); + } + + var form = forms.item(0); + form.parentNode.replaceChild(fragment, form); + } + + var old = ctx.CurrentItem; + ctx.CurrentItem = ctx.ListData.Items[0]; + var fields = ctx.ListSchema.Field; + for (var j = 0; j < fields.length; j++) { + var field = fields[j]; + var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; + var span = $get(pHolderId); + if (span) { + span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); + } + } + ctx.CurrentItem = old; + } + + } + + + } + + +//typescripttempltes.ts + declare var Strings:any; + export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName] + && contextWithHook.FormContextHook[fieldName].getValue) { + return contextWithHook.FormContextHook[fieldName].getValue(); + } + } + return null; + } + + export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName]) { + return contextWithHook.FormContextHook[fieldName].fieldSchema; + } + } + return null; + } + + export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); + var callbacks = f.updatedValueCallbacks; + if (callbacks.indexOf(callback) == -1) { + callbacks.push(callback); + if (f.lastValue) { + callback(f.lastValue, f.fieldSchema); + } + } + } + } + + } + + export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; + var index = callbacks.indexOf(callback); + if (index != -1) { + callbacks.splice(index, 1); + } + } + } + } + + export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { + var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; + //TODO: Handle different input types + return $get(id); + } + + export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { + var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; + ctx.FieldControlModes[field.Name] = mode; + var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); + return templates.Fields[field.Name]; + } + + + class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + + public Templates: SPClientTemplates.TemplateOverrides; + public OnPreRender: SPClientTemplates.RenderCallback[]; + public OnPostRender: SPClientTemplates.RenderCallback[]; + private IsRegistered: boolean; + + + constructor(public ListTemplateType?: number, public BaseViewID?: any) { + this.Templates = { Fields: {} }; + this.OnPreRender = [] ; + this.OnPostRender = []; + this.IsRegistered = false; + } + + /* tier 1 methods */ + view(template: any): ICSR { + this.Templates.View = template; + return this; + } + + item(template: any): ICSR { + this.Templates.Item = template; + return this; + } + + header(template: any): ICSR { + this.Templates.Header = template; + return this; + } + + body(template: any): ICSR { + this.Templates.Body = template; + return this; + } + + footer(template: any): ICSR { + this.Templates.Footer = template; + return this; + } + + fieldView(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].View = template; + return this; + } + + fieldDisplay(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].DisplayForm = template; + return this; + } + + fieldNew(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].NewForm = template; + return this; + } + + fieldEdit(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].EditForm = template; + return this; + } + + /* tier 2 methods */ + template(name: string, template: any): ICSR { + this.Templates[name] = template; + return this; + } + + fieldTemplate(fieldName: string, name: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName][name] = template; + return this; + } + + /* common */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPreRender.push(callbacks[i]); + } + return this; + } + + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPostRender.push(callbacks[i]); + } + return this; + } + + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + makeReadOnly(fieldName: string): ICSR { + return this + .onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema).ReadOnlyField = true; + (schema).ReadOnly = "TRUE"; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + if (ctxInView.inGridMode) { + //TODO: Disable editing in grid mode + + } + + } else { + var ctxInForm = ctx; + if (schema.Type != 'User' && schema.Type != 'UserMulti') { + + var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); + ctxInForm.Templates.Fields[fieldName] = template; + ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); + + } + } + + }) + .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type == 'User' || schema.Type == 'UserMulti') { + SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { + var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; + var retryCount = 10; + var callback = () => { + var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; + if (!pp) { + if (retryCount--) setTimeout(callback, 1); + } else { + pp.SetEnabledState(false); + pp.DeleteProcessedUser = function () { }; + } + }; + callback(); + }); + } + } + }); + } + + makeHidden(fieldName: string): ICSR { + return this.onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; + (schema).Hidden = true; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + + if (ctxInView.inGridMode) { + //TODO: Hide item in grid mode + } else { + ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); + } + + } else { + var ctxInForm = ctx; + + var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; + var placeholder = $get(pHolderId); + var current = placeholder; + while (current.tagName.toUpperCase() !== "TR") { + current = current.parentElement; + } + var row = current; + row.style.display = 'none'; + + } + + }); + } + + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + + + return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) + .fieldNew(fieldName, SPFieldCascadedLookup_Edit); + + + function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + + var parseRegex = /\{[^\}]+\}/g; + var dependencyExpressions: string[] = []; + var result: RegExpExecArray; + while ((result = parseRegex.exec(camlFilter))) { + dependencyExpressions.push(stripBraces(result[0])); + } + var dependencyValues: { [expr: string]: string } = {}; + + var _dropdownElt: HTMLSelectElement; + var _myData: SPClientTemplates.ClientFormContext; + + + if (rCtx == null) + return ''; + _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + + var _schema = _myData.fieldSchema; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); + + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; + var _noValueSelected = _selectedValue == 0; + var _optionsLoaded = false; + var pendingLoads = 0; + + if (_noValueSelected) + _valueStr = ''; + + _myData.registerInitCallback(_myData.fieldName, InitLookupControl); + + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_dropdownElt != null) + _dropdownElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); + _myData.updateControlValue(_myData.fieldName, _valueStr); + + return BuildLookupDropdownControl(); + + function InitLookupControl() { + _dropdownElt = document.getElementById(_dropdownId); + if (_dropdownElt != null) + AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); + + SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { + bindDependentControls(dependencyExpressions); + loadOptions(true); + }); + } + + + function BuildLookupDropdownControl() { + var result = ''; + result += '
'; + return result; + } + + + function OnLookupValueChanged() { + if (_optionsLoaded) { + if (_dropdownElt != null) { + _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + _selectedValue = parseInt(_dropdownElt.value, 10); + } + } + } + + function GetCurrentLookupValue() { + if (_dropdownElt == null) + return ''; + return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; + } + + function stripBraces(input: string): string { + return input.substring(1, input.length - 1); + } + + function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { + var isLookupValue = !!listId; + if (isLookupValue) { + var lookup = SPClientTemplates.Utility.ParseLookupValue(value); + if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + value = lookup.LookupValue; + expressionParts.shift(); + } else { + value = lookup.LookupId.toString(); + } + } + + if (expressionParts.length == 0) { + dependencyValues[expr] = value; + callback(); + } else { + var ctx = SP.ClientContext.get_current(); + var web = ctx.get_web(); + //TODO: Handle lookup to another web + var list = web.get_lists().getById(listId); + var item = list.getItemById(parseInt(value, 10)); + var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); + ctx.load(item); + ctx.load(field); + + ctx.executeQueryAsync((o, e) => { + var value = item.get_item(field.get_internalName()); + + if (field.get_typeAsString() == 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup); + var lookup = (value); + value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); + listId = (field).get_lookupList(); + } + + getDependencyValue(expr, value, listId, expressionParts, callback); + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + function bindDependentControls(dependencyExpressions: string[]) { + dependencyExpressions.forEach(expr => { + var exprParts = expr.split("."); + var field = exprParts.shift(); + + CSR.addUpdatedValueCallback(rCtx, field, + (v, s) => { + getDependencyValue(expr, v, + (s).LookupListId, + exprParts.slice(0), + loadOptions); + }); + + }); + } + + + function loadOptions(isFirstLoad?: boolean) { + _optionsLoaded = false; + pendingLoads++; + + var ctx = SP.ClientContext.get_current(); + //TODO: Handle lookup to another web + var web = ctx.get_web(); + var listId = _schema.LookupListId; + var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); + var query = new SP.CamlQuery(); + + var predicate = camlFilter.replace(parseRegex, (v, a) => { + var expr = stripBraces(v); + return dependencyValues[expr] ? dependencyValues[expr] : ''; + }); + + //TODO: Handle ShowField attribure + if (predicate.substr(0, 5) == '' + + predicate + + ' ' + + ''); + } + var results = list.getItems(query); + ctx.load(results); + + + ctx.executeQueryAsync((o, e) => { + var selected = false; + + while (_dropdownElt.options.length) { + _dropdownElt.options.remove(0); + } + + if (!_schema.Required) { + var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); + _dropdownElt.options.add(defaultOpt); + selected = _selectedValue == 0; + } + var isEmptyList = true; + + var enumerator = results.getEnumerator(); + while (enumerator.moveNext()) { + var c = enumerator.get_current(); + var id: number; + var text: string; + + if (!lookupField) { + id = c.get_id(); + text = c.get_item('Title'); + } else { + var value = c.get_item(lookupField); + id = value.get_lookupId(); + text = value.get_lookupValue(); + } + var isSelected = _selectedValue == id; + if (isSelected) { + selected = true; + } + var opt = new Option(text, id.toString(), isSelected, isSelected); + _dropdownElt.options.add(opt); + isEmptyList = false; + } + pendingLoads--; + _optionsLoaded = true; + if (!pendingLoads) { + if (isFirstLoad) { + if (_selectedValue == 0 && !selected) { + _dropdownElt.selectedIndex = 0; + OnLookupValueChanged(); + } + } else { + if (_selectedValue != 0 && !selected) { + _dropdownElt.selectedIndex = 0; + } + OnLookupValueChanged(); + } + } + + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + } + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + return this.fieldEdit(fieldName, koEditField_Edit) + .fieldNew(fieldName, koEditField_Edit); + + + function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; + + vm.renderingContext = rCtx; + + + if (dependencyFields) { + dependencyFields.forEach(dependencyField => { + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); + }); + } + + + if (!vm.value) { + vm.value = ko.observable(); + } + + vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); + _myData.registerGetValueCallback(fieldName, () => vm.value()); + + + _myData.registerInitCallback(fieldName, () => { + ko.applyBindings(vm, $get(elementId)); + }); + + return '
'+template+'
'; + } + } + + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + var dependentValues: { [field: string]: string } = {}; + + return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema); + sourceField.forEach((field) => { + CSR.addUpdatedValueCallback(ctx, field, v => { + dependentValues[field] = v; + targetControl.value = transform.apply(this, + sourceField.map(n => dependentValues[n] || '')); + + }); + }); + } + }); + } + + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + if (value || !ignoreNull) { + return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + ctx.ListData.Items[0][fieldName] = value; + }); + } else { + return this; + } + } + + + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + return this + .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) + .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); + + function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + var _autoFillControl: SPClientAutoFill; + var _textInputElt: HTMLInputElement; + var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; + var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_textInputElt != null) + _textInputElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); + _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); + + return buildAutoFillControl(); + + function initAutoFillControl() { + _textInputElt = document.getElementById(_textInputId); + + SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { + _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); + var callback = init({ + renderContext: rCtx, + fieldContext: _myData, + autofill: _autoFillControl, + control: _textInputElt, + }); + + //_autoFillControl.AutoFillMinTextLength = 2; + //_autoFillControl.VisibleItemCount = 15; + //_autoFillControl.AutoFillTimeout = 500; + }); + + } + //function OnPopulate(targetElement: HTMLInputElement) { + + //} + + //function OnLookupValueChanged() { + // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + //} + //function GetCurrentLookupValue() { + // return _valueStr; + //} + function buildAutoFillControl() { + var result: string[] = []; + result.push('
'); + result.push(''); + + result.push("
"); + result.push("
"); + + return result.join(""); + } + } + + + } + + seachLookup(fieldName: string): ICSR { + return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + var _myData = ctx.fieldContext; + var _schema = _myData.fieldSchema; + if (_myData.fieldSchema.Type != 'Lookup') { + return null; + } + + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); + var _noValueSelected = _selectedValue.LookupId == 0; + ctx.control.value = _selectedValue.LookupValue; + $addHandler(ctx.control, "blur", _ => { + if (ctx.control.value == '') { + _myData.fieldValue = ''; + _myData.updateControlValue(fieldName, _myData.fieldValue); + } + }); + + if (_noValueSelected) + _myData.fieldValue = ''; + + var _autoFillControl = ctx.autofill; + _autoFillControl.AutoFillMinTextLength = 2; + _autoFillControl.VisibleItemCount = 15; + _autoFillControl.AutoFillTimeout = 500; + + return () => { + var value = ctx.control.value; + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); + + SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { + var Search = Microsoft.SharePoint.Client.Search.Query; + var ctx = SP.ClientContext.get_current(); + var query = new Search.KeywordQuery(ctx); + query.set_rowLimit(_autoFillControl.VisibleItemCount); + query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); + var selectProps = query.get_selectProperties(); + selectProps.clear(); + //TODO: Handle ShowField attribute + selectProps.add('Title'); + selectProps.add('ListItemId'); + var executor = new Search.SearchExecutor(ctx); + var result = executor.executeQuery(query); + ctx.executeQueryAsync( + () => { + //TODO: Discover proper way to load collection + var tableCollection = new Search.ResultTableCollection(); + tableCollection.initPropertiesFromJson(result.get_value()); + + var relevantResults = tableCollection.get_item(0); + var rows = relevantResults.get_resultRows(); + + var items = []; + for (var i = 0; i < rows.length; i++) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + } + + items.push(AutoFillOptionBuilder.buildSeparatorItem()); + + if (relevantResults.get_totalRows() == 0) + items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); + else + items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); + + _autoFillControl.PopulateAutoFill(items, onSelectItem); + + }, + (sender, args) => { + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); + console.log(args.get_message()); + }); + }); + } + + function onSelectItem(targetInputId, item: ISPClientAutoFillData) { + var targetElement = ctx.control; + targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; + _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; + _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; + _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; + _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); + } + + }); + } + + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + return this.onPostRenderField(fieldName, + (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + + var control = CSR.getControl(schema); + if (control) { + var weburl = _spPageContextInfo.webServerRelativeUrl; + if (weburl[weburl.length - 1] == '/') { + weburl = weburl.substring(0, weburl.length - 1); + } + var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' + + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); + if (contentTypeId) { + newFormUrl += '&ContentTypeId=' + contentTypeId; + } + + var link = document.createElement('a'); + link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; + link.textContent = prompt; + if (control.nextElementSibling) { + control.parentElement.insertBefore(link, control.nextElementSibling); + } else { + control.parentElement.appendChild(link); + } + + if (showDialog) { + $addHandler(link, "click", (e: Sys.UI.DomEvent) => { + SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { + SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); + }); + e.stopPropagation(); + e.preventDefault(); + }); + } + } + }); + } + + register() { + if (!this.IsRegistered) { + SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); + this.IsRegistered = true; + } + } + } + + export class AutoFillOptionBuilder { + + static buildFooterItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.DisplayTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; + + return item; + } + + static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { + + var item = {}; + + item[SPClientAutoFill.KeyProperty] = id; + item[SPClientAutoFill.DisplayTextProperty] = displayText || title; + item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; + item[SPClientAutoFill.TitleTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; + + return item; + } + + static buildSeparatorItem(): ISPClientAutoFillData { + var item = {}; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; + return item; + } + + static buildLoadingItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; + item[SPClientAutoFill.DisplayTextProperty] = title; + return item; + } + + } + + /** Lightweight client-side rendering template overrides.*/ + export interface ICSR { + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: string): ICSR; + + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Sets pre-render callbacks. Callback called before rendering starts. + @param callbacks pre-render callbacks. + */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. + @param callbacks post-render callbacks. + */ + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks pre-render callbacks. + */ + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks post-render callbacks. + */ + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Registers overrides in client-side templating engine.*/ + register(): void; + + /** Override View rendering template. + @param template New view template. + */ + view(template: string): ICSR; + + /** Override View rendering template. + @param template New view template. + */ + view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; + view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; + item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + + /** Override DisplyForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: string): ICSR; + + /** Override DisplyForm rendering template. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override EditForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: string): ICSR; + + /** Override EditForm rendering template. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override NewForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: string): ICSR; + + /** Override NewForm rendering template. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + + /** Set initial value for field. + @param fieldName Internal name of the field. + @param value Initial value for field. + */ + setInitialValue(fieldName: string, value: any): ICSR; + + /** Make field hidden in list view and standard forms. + @param fieldName Internal name of the field. + */ + makeHidden(fieldName: string): ICSR + + + /** Replace New and Edit templates for field to Display template. + @param fieldName Internal name of the field. + */ + makeReadOnly(fieldName: string): ICSR + + /** Create cascaded Lookup Field. + @param fieldName Internal name of the field. + @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. + */ + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + + /** Auto computes text-based field value based on another fields. + @param targetField Internal name of the field. + @param transform Function combines source field values. + @param sourceField Internal names of source fields. + */ + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + + /** Field text value with autocomplete based on autofill.js + @param fieldName Internal name of the field. + @param ctx AutoFill context. + */ + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + + /** Replace defult dropdown to search-based autocomplete for Lookup field. + @param fieldName Internal name of the field. + */ + seachLookup(fieldName: string): ICSR; + + /** Adds link to add new value to lookup list. + @param fieldName Internal name of the field. + @param prompt Text to display as a link to add new value. + @param contentTypeID Default content type for new item. + */ + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + + + } + + export interface IAutoFillFieldContext { + renderContext: SPClientTemplates.RenderContext_FieldInForm; + fieldContext: SPClientTemplates.ClientFormContext; + autofill: SPClientAutoFill; + control: HTMLInputElement; + } + + export interface IKoFieldInForm { + renderingContext?:SPClientTemplates.RenderContext_FieldInForm; + value?:KnockoutObservable; + } + + + interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: IFormContextHook; + } + + interface IFormContextHook { + [fieldName: string]: IFormContextHookField; + } + + interface IFormContextHookField { + fieldSchema?: SPClientTemplates.FieldSchema_InForm; + lastValue?: any; + getValue?: () => any; + updatedValueCallbacks: UpdatedValueCallback[]; + } + + + function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + return hook[fieldName] = hook[fieldName] || { + updatedValueCallbacks: [] + }; + + } + + class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { + constructor(public valueGetter: () => boolean, public validationMessage: string) { } + + Validate(value: any): SPClientForms.ClientValidation.ValidationResult { + return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); + } + } + +} + +if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); +} + + +//mquery.ts + + + + +module spdevlab { + export module mQuery { + export class DynamicTable { + + // private fields + _domContainer:HTMLElement; + _tableContainer:MQueryResultSetElements; + + _rowTemplateId:string = null; + _rowTemplateContent:string = null; + + _options = { + tableCnt: '.spdev-rep-tb', + addCnt: '.spdev-rep-tb-add', + removeCnt: '.spdev-rep-tb-del' + }; + + // public methods + init(domContainer: HTMLElement, options) { + + if (m$.isDefinedAndNotNull(options)) { + m$.extend(this._options, options); + } + + this._initContainers(domContainer); + + this._initRowTemplate(); + this._initEvents(); + this._showUI(); + } + + // private methods + _initContainers(domContainer) { + + this._domContainer = domContainer; + this._tableContainer = m$(this._options.tableCnt, this._domContainer); + } + + _showUI() { + m$(this._domContainer).css("display", ""); + } + + _initEvents() { + + m$(this._options.addCnt, this._domContainer).click(() => { + + if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { + + m$(this._tableContainer).append(this._rowTemplateContent); + + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + + var targetElement = e.currentTarget; + var parentRow = m$(targetElement).parents("tr").first(); + + m$(parentRow).remove(); + }); + } + + return false; + }); + } + + _initRowTemplate() { + var templateId = m$(this._tableContainer).attr("template-id"); + + if (m$.isDefinedAndNotNull(templateId)) { + this._rowTemplateId = templateId; + this._rowTemplateContent = DynamicTable._templates[templateId]; + } + } + + static _templates:string[] = []; + static initTables() { + // init templates + m$('script').forEach((template:HTMLElement) => { + + var id = m$(template).attr("dynamic-table-template-id"); + + if (m$.isDefinedAndNotNull(id)) { + DynamicTable._templates[id] = template.innerHTML; + } + }); + + // init tables + m$(".spdev-rep-tb-cnt").forEach( divContainer => { + + var dynamicTable = new DynamicTable(); + + dynamicTable.init(divContainer, { + removeCnt: '.spdev-rep-tb-del-override' + }); + }); + } + + }; + + + } +} + +m$.ready(() => { + spdevlab.mQuery.DynamicTable.initTables(); +}); + + +//whoisapppart.ts + + +module _ { + var queryString = parseQueryString(); + var isIframe = queryString['DisplayMode'] == 'iframe' + var spHostUrl = queryString['SPHostUrl']; + var editmode = Number(queryString['editmode']); + var includeDetails = queryString['boolProp'] == 'true'; + + prepareVisual(); + m$.ready(() => { + loadPeoplePicker('peoplePicker'); + partProperties(); + + if (isIframe) { + partResize(); + } + }); + + //Load the people picker + function loadPeoplePicker(peoplePickerElementId: string) { + var schema: ISPClientPeoplePickerSchema = { + PrincipalAccountType: "User", + AllowMultipleValues: false, + Width: 300, + OnUserResolvedClientScript: onUserResolvedClientScript + } + + SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); + } + + function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { + if (users.length > 0) { + var person = users[0]; + var accountName = person.Key; + + var context = SP.ClientContext.get_current(); + + var peopleManager = new SP.UserProfiles.PeopleManager(context); + var personProperties = peopleManager.getPropertiesFor(accountName); + + context.load(personProperties); + context.executeQueryAsync((sender, args) => { + + $get("basicInfo").style.display = 'block'; + + var userPic = personProperties.get_userProfileProperties()["PictureURL"]; + $get("pic").innerHTML = ' + personProperties.get_displayName() + '; + + $get("name").innerHTML = '' + personProperties.get_displayName() + ''; + $get("email").innerHTML = '' + personProperties.get_email() + ''; + $get("title").innerHTML = personProperties.get_title(); + $get("department").innerHTML = person.EntityData.Department; + $get("phone").innerHTML = person.EntityData.MobilePhone; + + var properties = personProperties.get_userProfileProperties(); + var messageText = ""; + for (var key in properties) { + messageText += "
[" + key + "]: \"" + properties[key] + "\""; + } + $get("detailInfo").innerHTML = messageText; + + if (isIframe) { + partResize(); + } + + }, (sender, args) => { alert('Error: ' + args.get_message()); }); + + } + } + + function partProperties() { + + if (editmode == 1) { + $get("editmodehdr").style.display = "inline"; + $get("content").style.display = "none"; + } + else if (includeDetails) { + $get('detailInfo').style.display = 'block'; + + $get("editmodehdr").style.display = "none"; + $get("content").style.display = "inline"; + } + } + + function partResize() { + var bounds = Sys.UI.DomElement.getBounds(document.body); + parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); + } + + function prepareVisual() { + if (isIframe) { + //Create a Link element for the defaultcss.ashx resource + var linkElement = document.createElement('link'); + linkElement.setAttribute('rel', 'stylesheet'); + linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); + + //Add the linkElement as a child to the head section of the html + document.head.appendChild(linkElement); + } else { + + m$.ready(() => { + var nav = new SP.UI.Controls.Navigation('navigation', { + appIconUrl: queryString['SPHostLogo'], + appTitle: document.title + }); + nav.setVisible(true); + $get('apppart-notification').style.display = 'block'; + document.body.style.overflow = 'visible'; + }); + } + } + + function parseQueryString() { + var result = {}; + var qs = document.location.search.split('?')[1]; + if (qs) { + var parts = qs.split('&'); + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var pair = parts[i].split('='); + result[pair[0]] = decodeURIComponent(pair[1]); + } + } + } + return result; + } +} + +//taxonomy +module SP { + + // Class + export class ClientContextPromise extends SP.ClientContext { + /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ + executeQueryPromise(): JQueryPromise { + var deferred = jQuery.Deferred(); + this.executeQueryAsync(function (sender, args) { + deferred.resolve(sender, args); + }, + function (sender, args) { + deferred.reject(sender, args); + }) + return deferred.promise(); + } + + constructor(serverRelativeUrlOrFullUrl: string) { + super(serverRelativeUrlOrFullUrl); + } + + static get_current(): ClientContextPromise { + return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); + } + + } + +} + +SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); + +module _ { + var context: SP.ClientContextPromise; + var web: SP.Web; + var site: SP.Site; + var session: SP.Taxonomy.TaxonomySession; + var termStore: SP.Taxonomy.TermStore; + var groups: SP.Taxonomy.TermGroupCollection; + + // This code runs when the DOM is ready and creates a context object + // which is needed to use the SharePoint object model. + // It also wires up the click handlers for the two HTML buttons in Default.aspx. + $(document).ready(function () { + context = SP.ClientContextPromise.get_current(); + site = context.get_site(); + web = context.get_web(); + $('#listExisting').click(function () { listGroups(); }); + $('#createTerms').click(function () { createTerms(); }); + }); + + // When the listExisting button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function listGroups() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); + } + + // Runs when the executeQueryAsync method in the listGroups function has succeeded. + // In this case, get and load the groups associated with the term store that we + // know we now have a reference to. + function onListTaxonomySession() { + groups = termStore.get_groups(); + context.load(groups); + context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. + // In this case, loop through all the groups and add a clickable div element to the report area + // for each group. + // NOTE: We clear the report area first to ensure we have a clean place to write to. + // Also note how we create a click event handler for each div on-the-fly, and that we pass in the + // current group ID to that function. So when the user clicks one of these divs, we will know which + // one was clicked. + function onRetrieveGroups() { + $('#report').children().remove(); + + var groupEnum = groups.getEnumerator(); + + // For each group, we'll build a clickable div. + while (groupEnum.moveNext()) { + (() => { + var currentGroup = groupEnum.get_current(); + var groupName = document.createElement("div"); + groupName.setAttribute("style", "float:none;cursor:pointer"); + var groupID = currentGroup.get_id(); + groupName.setAttribute("id", groupID.toString()); + $(groupName).click(() => showTermSets(groupID)); + groupName.appendChild(document.createTextNode(currentGroup.get_name())); + $('#report').append(groupName); + })(); + } + } + + // This is the function that runs when the user clicks one of the divs + // that we created in the onRetrieveGroups function. We can know which + // div was clicked by interrogating the groupID parameter. So what we'll + // do is retrieve a reference to the group with the same ID as the div, and + // then add the term sets that belong to that group under the div that was clicked. + function showTermSets(groupID: SP.Guid) { + + // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. + // The reason we don't clear them all is becuase we want to retain the text node of the + // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop + // controller. + var parentDiv = document.getElementById(groupID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // For each term set, we'll build a clickable div + var currentGroup = groups.getById(groupID); + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + context.load(currentGroup); + var termSets: SP.Taxonomy.TermSetCollection; + context.executeQueryPromise() + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise() + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } + + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + } + + + // This is the function that runs when the user clicks one of the divs + // that we created in the showTermSets function. We can know which + // div was clicked by interrogating the termSetID parameter. So what we'll + // do is retrieve a reference to the term set with the same ID as the div, and + // then add the term that belong to that term set under the div that was clicked. + + function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { + + // First, cancel the bubble so that the group div click handler does not also fire + // because that removes all term set divs and we don't want that here. + event.cancelBubble = true; + + // Get a reference to the term set div that was click and + // remove its children (apart from the TextNode that is currently + // showing the term set name. + var parentDiv = document.getElementById(termSetID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + var currentGroup = groups.getById(groupID); + var termSets:SP.Taxonomy.TermSetCollection; + var currentTermSet:SP.Taxonomy.TermSet; + var terms:SP.Taxonomy.TermCollection; + + context.load(currentGroup); + context + .executeQueryPromise() + .then(() => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) + .then(() => { + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) + .then(() => { + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); + + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailRetrieveGroups(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); + } + + // Runs when the executeQueryAsync method in the listGroups function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailListTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + + + // When the createTerms button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function createTerms() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); + } + + + // This function is the success callback for loading the session and store from the createTerms function + function onGetTaxonomySession() { + // Create six GUIDs that we will need when we create a new group, term set, and associated terms + var guidGroupValue = SP.Guid.newGuid(); + var guidTermSetValue = SP.Guid.newGuid(); + var guidTerm1 = SP.Guid.newGuid(); + var guidTerm2 = SP.Guid.newGuid(); + var guidTerm3 = SP.Guid.newGuid(); + var guidTerm4 = SP.Guid.newGuid(); + + // Create a new group + var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); + + // Create a new term set in the newly-created group + var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); + + // Create four new terms in the newly-created term set + myTermSet.createTerm("Top Secret", 1033, guidTerm1); + myTermSet.createTerm("Company Confidential", 1033, guidTerm2); + myTermSet.createTerm("Partners Only", 1033, guidTerm3); + myTermSet.createTerm("Public", 1033, guidTerm4); + + // Ensure the groups variable has been set, because when this all succeeds we will + // effectively run the same code as if the user had clicked the listGroups button + groups = termStore.get_groups(); + context.load(groups); + + // Execute all the preceeding statements in this function + context.executeQueryAsync(onAddTerms, onFailAddTerms); + + } + + // If all is well with creating the terms, then this function will run. + // Effectively this runs the same code as if the user had clicked the listGroups button + // so the user will see their newly-created group + function onAddTerms() { + listGroups(); + } + + // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailAddTerms(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to add terms. Error: " + args.get_message()); + } + + // Runs when the executeQueryAsync method in the createTerms function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + +}; + +//publishing.ts +// Variables used in various callbacks +JSRequest.EnsureSetup(); + +SP.SOD.execute('mquery.js', 'm$.ready', () => { + var context = SP.ClientContext.get_current(); + var web = context.get_web(); + m$('#CreatePage').click(createPage); +}); + +function createPage(evt) { + SP.SOD.execute('sp.js', 'SP.ClientConext', () => { + SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { + var context = SP.ClientContext.get_current(); + + + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function () { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function () { + + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( + + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function () { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, + + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function (sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to add a new Publishing Page. + function (sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function (sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); + }); +} + +//likes +module SampleReputation { + + interface MyList extends SPClientTemplates.RenderContext_InView { + listId: string; + } + + class MyItem { + + id: number; + title: string; + likesCount: number; + isLikedByCurrentUser: boolean; + + constructor(public row: SPClientTemplates.Item) { + this.id = parseInt(row['ID']); + this.title = row['Title']; + this.likesCount = parseInt(row['LikesCount']) || 0; + this.isLikedByCurrentUser = this.getLike(row['LikedBy']); + } + + private getLike(likedBy): boolean { + if (likedBy && likedBy.length > 0) { + for (var i = 0; i < likedBy.length; i++) { + if (likedBy[i].id == _spPageContextInfo.userId) { + return true; + } + } + } + return false; + } + } + + function init() { + SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); + SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); + SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { + CSR.override(10004, 1) + .onPreRender((ctx: MyList) => { + ctx.listId = ctx.listName.substring(1, 37); + }) + .header('
    ') + .body(renderTemplate) + .footer('
') + .register(); + }); + + SP.SOD.execute('mQuery.js', 'm$.ready', () => { + RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); + }); + + + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); + } + + function renderTemplate(ctx: MyList) { + var rows = ctx.ListData.Row; + var result = ''; + for (var i = 0; i < rows.length; i++) { + var item = new MyItem(rows[i]); + result += '\ +
  • ' + item.title +'\ + \ + ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ + \ +
  • '; + } + return result; + } + + function getLikeText(isLikedByCurrentUser: boolean) { + return isLikedByCurrentUser ? '\u2665' : '\u2661'; + } + + export function setLike(itemId: number, listId: string): void { + var context = SP.ClientContext.get_current(); + var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); + context.executeQueryAsync( + () => { + m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); + }, + (sender, args) => { + alert(args.get_message()); + }); + }); + } + + init(); +} + + + +//code from https://github.com/gandjustas/SharePointAngularTS +module App { + "use strict"; +var app = angular.module("app", []); +} + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + interface Iappcontroller { + title: string; + activate: () => void; + } + + class appcontroller implements Iappcontroller { + title: string = "appcontroller"; + lists: SP.List[]; + + static $inject: string[] = ["$SharePoint", "$spnotify"]; + + constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + this.activate(); + } + + activate() { + var loading = this.$n.showLoading(true) + this.$SharePoint + .getLists() + .then(l => this.lists = l ) + .catch((e: string) => this.$n.show(e, true)) + .finally(() => this.$n.remove(loading) ); + ; + + } + } + + angular.module("app").controller("appcontroller", appcontroller); +} + + + +module App { + "use strict"; + + export interface ISharePoint { + getLists: () => ng.IPromise; + } + + class SharePointServcie implements ISharePoint { + static $inject: string[] = ["$q"]; + + constructor(public $q: ng.IQService) { + } + + getLists() { + var promise = this.$q.defer(); + SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { + var ctx = SP.ClientContext.get_current(); + var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); + var appCtx = new SP.AppContextSite(ctx, hostUrl); + var hostWeb = appCtx.get_web(); + var lists = hostWeb.get_lists(); + ctx.load(lists); + + ctx.executeQueryAsync(() => { + var result: SP.List[] = []; + for (var e = lists.getEnumerator(); e.moveNext();) { + result.push(e.get_current()); + } + promise.resolve(result); + }, + (o, args) => { promise.reject(args.get_message()); }); + }); + return promise.promise; + } + } + + angular.module("app").service("$SharePoint", SharePointServcie); +} + + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + export interface ISpNotify { + showLoading(sticky?: boolean) : string; + show(msg: string, sticky?: boolean): string; + remove(id: string):void; + } + + class SpNotify implements ISpNotify { + static $inject: string[] = []; + + + showLoading(sticky: boolean = false) { + return SP.UI.Notify.showLoadingNotification(sticky); + } + + show(msg: string, sticky: boolean = false) { + return SP.UI.Notify.addNotification(msg, sticky); + } + + remove(id: string) { + SP.UI.Notify.removeNotification(id); + } + } + + angular.module("app").service("$spnotify", SpNotify); +} + From 1e5725eeeea816a0411b9f7015bca78b4f1d1252 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 00:57:57 +0300 Subject: [PATCH 09/11] Reverted file modes --- README.md | 0 angularjs/angular.d.ts | 0 chrome/chrome.d.ts | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 README.md mode change 100644 => 100755 angularjs/angular.d.ts mode change 100644 => 100755 chrome/chrome.d.ts diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100644 new mode 100755 diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts old mode 100644 new mode 100755 From 3cc4192c1a5e00a417541f4beaae854fbb4d319d Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 01:36:19 +0300 Subject: [PATCH 10/11] Fixed tests for microsoft-ajax.d.ts --- microsoft-ajax/microsoft.ajax-tests.ts | 84 +++++++++++++------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/microsoft-ajax/microsoft.ajax-tests.ts b/microsoft-ajax/microsoft.ajax-tests.ts index 763c1e7fb..0f776da09 100644 --- a/microsoft-ajax/microsoft.ajax-tests.ts +++ b/microsoft-ajax/microsoft.ajax-tests.ts @@ -37,33 +37,33 @@ function BaseClassExtensions_Error_Tests() { // Verify the required parameters were defined. if (input === undefined) { // Throw a standard exception type. - var err = (Error).argumentNull("input", "A parameter was undefined."); + var err = Error.argumentNull("input", "A parameter was undefined."); throw err; } else if (min === undefined) { - var err = (Error).argumentNull("min", "A parameter was undefined."); + var err = Error.argumentNull("min", "A parameter was undefined."); throw err; } else if (max === undefined) { - var err = (Error).argumentNull("max", "A parameter was undefined."); + var err = Error.argumentNull("max", "A parameter was undefined."); throw err; } else if (min >= max) { - var err = (Error).invalidOperation("The min parameter must be smaller than max parameter."); + var err = Error.invalidOperation("The min parameter must be smaller than max parameter."); throw err; } else if (isNaN(input)) { var msg = "A number was not entered. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += String.format("Please enter a number between {0} and {1}.", min, max); - var err = (Error).create(msg); + var err = Error.create(msg); throw err; } else if (input < min || input > max) { msg = "The number entered was outside the acceptable range. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += String.format("Please enter a number between {0} and {1}.", min, max); - var err = (Error).create(msg); + var err = Error.create(msg); throw err; } @@ -82,12 +82,12 @@ function BaseClassExtensions_Error_Tests() { function BaseClassExtensions_String_Tests() { - (String).format("Please enter a number between {0} and {1}.", 1, 2); - (String).endsWith("test"); - (String).localeFormat("Please enter a number between {0} and {1}", 1, 2); - (String).trim(); - (String).trimEnd(); - (String).trimStart(); + String.format("Please enter a number between {0} and {1}.", 1, 2); + "test".endsWith("test"); + String.localeFormat("Please enter a number between {0} and {1}", 1, 2); + "test".trim(); + "test".trimEnd(); + "test".trimStart(); } function BaseClassExtensions_Function_Tests() { @@ -95,22 +95,22 @@ function BaseClassExtensions_Function_Tests() { /** Sample code from http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx */ var createDelegateTest = function () { var context = ""; - var method: MicrosoftAjaxBaseTypeExtensions.Function; - var a = (Function).createCallback(method, context); + var method: Function; + var a = Function.createCallback(method, context); } /** Sample code from http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx */ var createDelegateTest = function () { var instance = this; - var method: MicrosoftAjaxBaseTypeExtensions.Function; - var a = (Function).createDelegate(instance, method); + var method: Function; + var a = Function.createDelegate(instance, method); } /** Sample code from http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx */ var validateParametersTest = function () { var arguments = ['test1', 'test2']; var insert = function Array$insert(array: any[], index: number, item: any) { - var e = (Function).validateParameters(arguments, [ + var e = Function.validateParameters(arguments, [ { name: "array", type: Array, elementMayBeNull: true }, { name: "index", mayBeNull: true }, { name: "item", mayBeNull: true } @@ -122,20 +122,20 @@ function BaseClassExtensions_Function_Tests() { function BaseClassExtensions_Array_Tests() { - var arrayVar = Array("one", "two", "three"); + var arrayVar =["one", "two", "three"]; - arrayVar.add(["one"], {}); - arrayVar.addRange({}, ["one", "two", "three"]); - arrayVar.clear(); - arrayVar.clone(); - arrayVar.contains({}); - arrayVar.dequeue(); - arrayVar.enqueue({}); - arrayVar.insert([1, 2, 3], 1, {}); - arrayVar.isArray({}); - arrayVar.parse("1, 2, 3, 4, 5"); - arrayVar.remove([1, 2, 3], 2); - arrayVar.removeAt([1, 2, 3], 1); + Array.add(arrayVar, "four"); + Array.addRange(arrayVar, ["one", "two", "three"]); + Array.clear(arrayVar); + Array.clone(arrayVar); + Array.contains(arrayVar, "zero"); + Array.dequeue(arrayVar); + Array.enqueue(arrayVar, "zero"); + Array.insert([1, 2, 3], 1, {}); + Array.isArray({}); + Array.parse("1, 2, 3, 4, 5"); + Array.remove([1, 2, 3], 2); + Array.removeAt([1, 2, 3], 1); } @@ -144,13 +144,13 @@ function BaseClassExtensions_Date_Tests() { var date = new Date(2014, 5, 25); date.format("g"); date.localeFormat("g"); - date.parseLocale("2014/05/25"); - date.parseInvariant("2014/05/25"); + Date.parseLocale("2014/05/25"); + Date.parseInvariant("2014/05/25"); } function BaseClassExtensions_Boolean_Tests() { - (Boolean).parse("false"); + Boolean.parse("false"); } function BaseClassExtensions_Number_Tests() { @@ -159,8 +159,8 @@ function BaseClassExtensions_Number_Tests() { x.format("d"); x.localeFormat("c"); - x.parseInvariant("1"); - x.parseLocale("1"); + Number.parseInvariant("1"); + Number.parseLocale("1"); } function Sys_Application_Tests() { @@ -374,7 +374,7 @@ function Sys_UI_Control_Tests() { function Sy_UI_Point_Tests() { - var elementRef: Sys.UI.DomElement; + var elementRef: HTMLElement; var result: string; // Get the location of the element var elementLoc = Sys.UI.DomElement.getLocation(elementRef); @@ -417,7 +417,7 @@ function Sys_UI_DomElement_Tests() { // Add CSS class Sys.UI.DomElement.addCssClass($get("Button1"), "redBackgroundColor"); - var elementRef: Sys.UI.DomElement = $get("Label1"); + var elementRef = $get("Label1"); var elementBounds = Sys.UI.DomElement.getBounds(elementRef); var toggleCssClassMethod = () => {}; var removeCssClassMethod = () => {}; @@ -611,7 +611,7 @@ function Sys_Services_Profile_Service_Group_Tests() { function Sys_Net_NetworkRequestEventArgs_Tests() { var value = new Sys.Net.WebRequest(); - var netWorkEventArgs = new Sys.Net.NetWorkRequestEventArgs(value); + var netWorkEventArgs = new Sys.Net.NetworkRequestEventArgs(value); var webRequest = netWorkEventArgs.get_webRequest(); } @@ -660,7 +660,7 @@ function Sys_WebForms_PageRequestManager_Tests() { } var pageLoadingRequestHandler = (sender: any, args: Sys.WebForms.PageLoadingEventArgs) => { var dataItems: any = args.get_dataItems(); - var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleted(); + var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleting(); var panelsUpdating = args.get_panelsUpdating(); var empty: Sys.EventArgs = args.Empty; } @@ -832,7 +832,7 @@ function CreatingCustomNonVisualClientComponentsTests() { _startTimer: function () { // save timer cookie for removal later - this._timer = window.setInterval((Function).createDelegate(this, this._timerCallback), this._interval); + this._timer = window.setInterval(Function.createDelegate(this, this._timerCallback), this._interval); }, _stopTimer: function () { From ae2581f4ce9d1b468089ea3d0652200d17e52af4 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 19:37:28 +0300 Subject: [PATCH 11/11] Fixed Travis-CI build --- microsoft-ajax/microsoft.ajax.d.ts | 2 +- sharepoint/SharePoint.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 19c9f9605..793fdf486 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -3039,7 +3039,7 @@ declare module Sys { * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ - static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean); + static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean): void; /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index c50100a78..fef652dd3 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ -// Type definitions for sptypescript +// Type definitions for SharePoint 2010 and 2013 // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan , Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped ///