From 59d84928170d304337e56ef69040e649e02b1f18 Mon Sep 17 00:00:00 2001 From: Mehmet Bektas Date: Tue, 7 Jan 2020 18:16:04 +0100 Subject: [PATCH] fix eslint warnings reported --- .eslintrc.json | 3 + examples/web3/src/index.ts | 2 +- examples/web3/src/manager.ts | 2 +- packages/base/src/backbone-patch.ts | 2 +- packages/base/src/manager-base.ts | 8 +- packages/base/src/nativeview.ts | 16 ++-- packages/base/src/services-shim.ts | 20 ++-- packages/base/src/utils.ts | 10 +- packages/base/src/viewlist.ts | 4 +- packages/base/src/widget.ts | 72 +++++++------- packages/base/src/widget_layout.ts | 12 +-- packages/base/src/widget_style.ts | 12 +-- packages/base/test/src/dummy-manager.ts | 34 +++---- packages/base/test/src/manager_test.ts | 2 +- packages/base/test/src/widget_test.ts | 6 +- packages/controls/src/phosphor/accordion.ts | 20 ++-- .../controls/src/phosphor/currentselection.ts | 2 +- packages/controls/src/utils.ts | 4 +- packages/controls/src/widget_audio.ts | 12 +-- packages/controls/src/widget_bool.ts | 36 +++---- packages/controls/src/widget_box.ts | 32 +++---- packages/controls/src/widget_button.ts | 16 ++-- packages/controls/src/widget_color.ts | 20 ++-- packages/controls/src/widget_controller.ts | 42 ++++---- packages/controls/src/widget_core.ts | 6 +- packages/controls/src/widget_date.ts | 40 ++++---- packages/controls/src/widget_description.ts | 10 +- packages/controls/src/widget_float.ts | 40 ++++---- packages/controls/src/widget_image.ts | 12 +-- packages/controls/src/widget_int.ts | 96 +++++++++---------- packages/controls/src/widget_link.ts | 16 ++-- packages/controls/src/widget_selection.ts | 94 +++++++++--------- .../controls/src/widget_selectioncontainer.ts | 54 +++++------ packages/controls/src/widget_string.ts | 70 +++++++------- packages/controls/src/widget_upload.ts | 18 ++-- packages/controls/src/widget_video.ts | 12 +-- packages/controls/test/src/dummy-manager.ts | 29 +++--- .../src/phosphor/currentselection_test.ts | 2 +- packages/html-manager/src/htmlmanager.ts | 7 +- packages/html-manager/src/index.ts | 2 +- packages/html-manager/src/libembed-amd.ts | 8 +- packages/html-manager/src/libembed.ts | 4 +- packages/html-manager/src/output.ts | 12 +-- packages/html-manager/src/output_renderers.ts | 2 +- packages/jupyterlab-manager/src/manager.ts | 36 +++---- packages/jupyterlab-manager/src/output.ts | 30 +++--- packages/jupyterlab-manager/src/plugin.ts | 14 +-- packages/jupyterlab-manager/src/renderer.ts | 4 +- .../jupyterlab-manager/src/semvercache.ts | 2 +- packages/output/src/output.ts | 2 +- 50 files changed, 509 insertions(+), 502 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 21b7915d8a..9226b03c38 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -9,6 +9,9 @@ "@typescript-eslint/interface-name-prefix": [ "error", { "prefixWithI": "always" } ], + "@typescript-eslint/no-unused-vars": [ + "warn", { "args": "none" } + ], "@typescript-eslint/no-use-before-define": "off", "@typescript-eslint/camelcase": "off", "@typescript-eslint/no-explicit-any": "off", diff --git a/examples/web3/src/index.ts b/examples/web3/src/index.ts index e4e2a7a08a..39ede219da 100644 --- a/examples/web3/src/index.ts +++ b/examples/web3/src/index.ts @@ -42,7 +42,7 @@ document.addEventListener('DOMContentLoaded', async function(event) { // Run backend code to create the widgets. You could also create the // widgets in the frontend, like the other widget examples demonstrate. const execution = kernel.requestExecute({ code: code }); - execution.onIOPub = (msg) => { + execution.onIOPub = (msg): void => { // If we have a display message, display the widget. if (KernelMessage.isDisplayDataMsg(msg)) { const widgetData: any = msg.content.data['application/vnd.jupyter.widget-view+json']; diff --git a/examples/web3/src/manager.ts b/examples/web3/src/manager.ts index df3b26b12f..acff872cd0 100644 --- a/examples/web3/src/manager.ts +++ b/examples/web3/src/manager.ts @@ -25,7 +25,7 @@ class WidgetManager extends HTMLManager { }); } - display_view(msg: any, view: DOMWidgetView, options: any) { + display_view(msg: any, view: DOMWidgetView, options: any): Promise { return Promise.resolve(view).then((view) => { pWidget.Widget.attach(view.pWidget, this.el); view.on('remove', function() { diff --git a/packages/base/src/backbone-patch.ts b/packages/base/src/backbone-patch.ts index 519c6dcae4..4d7c57e619 100644 --- a/packages/base/src/backbone-patch.ts +++ b/packages/base/src/backbone-patch.ts @@ -43,7 +43,7 @@ import * as utils from './utils'; // anyone who needs to know about the change in state. The heart of the beast. // This *MUST* be called with the model as the `this` context. export -function set(key: string|{}, val: any, options: any) { +function set(key: string|{}, val: any, options: any): any { /* tslint:disable:no-invalid-this */ if (key == null) { return this; diff --git a/packages/base/src/manager-base.ts b/packages/base/src/manager-base.ts index 87da036d56..7e9294ed87 100644 --- a/packages/base/src/manager-base.ts +++ b/packages/base/src/manager-base.ts @@ -16,6 +16,8 @@ import { PROTOCOL_VERSION } from './version'; +import { ReadonlyPartialJSONValue } from '@lumino/coreutils'; + const PROTOCOL_MAJOR_VERSION = PROTOCOL_VERSION.split('.', 1)[0]; /** @@ -467,7 +469,7 @@ abstract class ManagerBase { * Disconnect the widget manager from the kernel, setting each model's comm * as dead. */ - disconnect() { + disconnect(): void { Object.keys(this._models).forEach((i) => { this._models[i].then(model => { model.comm_live = false; }); }); @@ -521,7 +523,7 @@ abstract class ManagerBase { * * @returns {*} A copy of the state, with its 'state' attribute filtered */ - protected filterExistingModelState(serialized_state: any) { + protected filterExistingModelState(serialized_state: any): any { let models = serialized_state.state as {[key: string]: any}; models = Object.keys(models) .filter((model_id) => { @@ -559,7 +561,7 @@ interface IStateOptions { * @jupyter-widgets/schema package. */ export -function serialize_state(models: WidgetModel[], options: IStateOptions = {}) { +function serialize_state(models: WidgetModel[], options: IStateOptions = {}): ReadonlyPartialJSONValue { const state: {[key: string]: any} = {}; models.forEach(model => { const model_id = model.model_id; diff --git a/packages/base/src/nativeview.ts b/packages/base/src/nativeview.ts index 73fab0f46a..a31ecacc4b 100644 --- a/packages/base/src/nativeview.ts +++ b/packages/base/src/nativeview.ts @@ -43,7 +43,7 @@ const matchesSelector = ElementProto.matches || ElementProto['mozMatchesSelector'] || ElementProto['msMatchesSelector'] || ElementProto['oMatchesSelector'] || - function matches(selector: string) { + function matches(selector: string): boolean { /* tslint:disable:no-invalid-this */ const matches = (this.document || this.ownerDocument).querySelectorAll(selector); let i = matches.length; @@ -63,7 +63,7 @@ interface IDOMEvent { export class NativeView extends Backbone.View { - _removeElement() { + _removeElement(): void { this.undelegateEvents(); if (this.el.parentNode) { this.el.parentNode.removeChild(this.el); @@ -71,13 +71,13 @@ class NativeView extends Backbone.View { } // Apply the `element` to the view. - _setElement(element: HTMLElement) { + _setElement(element: HTMLElement): void { this.el = element; } // Set a hash of attributes to the view's `el`. We use the "prop" version // if available, falling back to `setAttribute` for the catch-all. - _setAttributes(attrs: {[key: string]: string}) { + _setAttributes(attrs: {[key: string]: string}): void { for (const attr in attrs) { attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]); } @@ -97,7 +97,7 @@ class NativeView extends Backbone.View { * https://github.com/jquery/jquery/blob/7d21f02b9ec9f655583e898350badf89165ed4d5/src/event.js#L442 * for some similar exceptional cases). */ - delegate(eventName: string, selector: any, listener: any) { + delegate(eventName: string, selector: any, listener: any): any { if (typeof selector !== 'string') { listener = selector; selector = null; @@ -111,7 +111,7 @@ class NativeView extends Backbone.View { } const root = this.el; - const handler = selector ? function (e: Event) { + const handler = selector ? function (e: Event): any { let node = (e.target as HTMLElement) || (e.srcElement as HTMLElement); for (; node && node !== root; node = node.parentNode as HTMLElement) { if (matchesSelector.call(node, selector)) { @@ -132,7 +132,7 @@ class NativeView extends Backbone.View { // Remove a single delegated event. Either `eventName` or `selector` must // be included, `selector` and `listener` are optional. - undelegate(eventName: string, selector?: any, listener?: any) { + undelegate(eventName: string, selector?: any, listener?: any): NativeView { if (typeof selector === 'function') { listener = selector; selector = null; @@ -160,7 +160,7 @@ class NativeView extends Backbone.View { } // Remove all events created with `delegate` from `el` - undelegateEvents() { + undelegateEvents(): NativeView { if (this.el && this._domEvents) { const len = this._domEvents.length; for (let i = 0; i < len; i++) { diff --git a/packages/base/src/services-shim.ts b/packages/base/src/services-shim.ts index 97a88b74bf..c74f2eb057 100644 --- a/packages/base/src/services-shim.ts +++ b/packages/base/src/services-shim.ts @@ -98,7 +98,7 @@ namespace shims { * Hookup kernel events. * @param {Kernel.IKernel} jsServicesKernel - @jupyterlab/services Kernel.IKernel instance */ - init_kernel(jsServicesKernel: Kernel.IKernelConnection) { + init_kernel(jsServicesKernel: Kernel.IKernelConnection): void { this.kernel = jsServicesKernel; // These aren't really the same. this.jsServicesKernel = jsServicesKernel; } @@ -120,7 +120,7 @@ namespace shims { * @param {(Comm, object) => void} f - callback that is called when the * comm is made. Signature of f(comm, msg). */ - register_target(target_name: string, f: (comm: Comm, data: {}) => void) { + register_target(target_name: string, f: (comm: Comm, data: {}) => void): void { const handle = this.jsServicesKernel.registerCommTarget(target_name, (jsServicesComm, msg) => { // Create the comm. @@ -143,7 +143,7 @@ namespace shims { * Unregisters a comm target * @param {string} target_name */ - unregister_target(target_name: string, f: (comm: Comm, data: {}) => void) { + unregister_target(target_name: string, f: (comm: Comm, data: {}) => void): void { const handle = this.targets[target_name]; handle.dispose(); delete this.targets[target_name]; @@ -152,7 +152,7 @@ namespace shims { /** * Register a comm in the mapping */ - register_comm(comm: Comm) { + register_comm(comm: Comm): string { this.comms[comm.comm_id] = Promise.resolve(comm); comm.kernel = this.kernel; return comm.comm_id; @@ -178,7 +178,7 @@ namespace shims { * Comm id * @return {string} */ - get comm_id() { + get comm_id(): string { return this.jsServicesComm.commId; } @@ -186,7 +186,7 @@ namespace shims { * Target name * @return {string} */ - get target_name() { + get target_name(): string { return this.jsServicesComm.targetName; } @@ -251,22 +251,22 @@ namespace shims { * @param @jupyterlab/services IKernelFuture instance * @param callbacks */ - _hookupCallbacks(future: Kernel.IShellFuture, callbacks: ICallbacks) { + _hookupCallbacks(future: Kernel.IShellFuture, callbacks: ICallbacks): void { if (callbacks) { - future.onReply = function(msg) { + future.onReply = function(msg): void { if (callbacks.shell && callbacks.shell.reply) { callbacks.shell.reply(msg); } // TODO: Handle payloads. See https://github.com/jupyter/notebook/blob/master/notebook/static/services/kernels/kernel.js#L923-L947 }; - future.onStdin = function(msg) { + future.onStdin = function(msg): void { if (callbacks.input) { callbacks.input(msg); } }; - future.onIOPub = function(msg) { + future.onIOPub = function(msg): void { if (callbacks.iopub) { if (callbacks.iopub.status && msg.header.msg_type === 'status') { callbacks.iopub.status(msg); diff --git a/packages/base/src/utils.ts b/packages/base/src/utils.ts index ceaaffc8ed..0ea61966ea 100644 --- a/packages/base/src/utils.ts +++ b/packages/base/src/utils.ts @@ -24,7 +24,7 @@ function difference(a: string[], b: string[]): string[] { * Compare two objects deeply to see if they are equal. */ export -function isEqual(a: any, b: any) { +function isEqual(a: any, b: any): boolean { return _isEqual(a, b); } @@ -34,7 +34,7 @@ function isEqual(a: any, b: any) { * This is from code that Typescript 2.4 generates for a polyfill. */ export -const assign = (Object as any).assign || function(t: any, ...args: any[]) { +const assign = (Object as any).assign || function(t: any, ...args: any[]): any { for (let i = 1; i < args.length; i++) { const s = args[i]; for (const p in s) { @@ -113,7 +113,7 @@ function resolvePromisesDict(d: Dict>): Promise> { */ export function reject(message: string, log: boolean) { - return function promiseRejection(error: any) { + return function promiseRejection(error: any): never { if (log) { console.error(new Error(message)); } @@ -131,7 +131,7 @@ function reject(message: string, log: boolean) { * Will lead to {a: 1, b: {data: array1}, c: [0, array2]} */ export -function put_buffers(state: any, buffer_paths: (string | number)[][], buffers: DataView[]) { +function put_buffers(state: any, buffer_paths: (string | number)[][], buffers: DataView[]): void { for (let i=0; i < buffer_paths.length; i++) { const buffer_path = buffer_paths[i]; // say we want to set state[x][y][z] = buffers[i] @@ -162,7 +162,7 @@ function remove_buffers(state: any): {state: any; buffers: ArrayBuffer[]; buffer // if we need to remove an object from a list, we need to clone that list, otherwise we may modify // the internal state of the widget model // however, we do not want to clone everything, for performance - function remove(obj: any, path: (string | number)[]) { + function remove(obj: any, path: (string | number)[]): any { if (obj.toJSON) { // We need to get the JSON form of the object before recursing. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior diff --git a/packages/base/src/viewlist.ts b/packages/base/src/viewlist.ts index 7de6e74e24..4e9af90ec6 100644 --- a/packages/base/src/viewlist.ts +++ b/packages/base/src/viewlist.ts @@ -19,12 +19,12 @@ class ViewList { this.initialize(create_view, remove_view, context); } - initialize(create_view: (model: any, index: any) => T | Promise, remove_view: (view: T) => void, context: any) { + initialize(create_view: (model: any, index: any) => T | Promise, remove_view: (view: T) => void, context: any): void { this._handler_context = context || this; this._models = []; this.views = []; // list of promises for views this._create_view = create_view; - this._remove_view = remove_view || function(view) { (view as any).remove(); }; + this._remove_view = remove_view || function(view): void { (view as any).remove(); }; } /** diff --git a/packages/base/src/widget.ts b/packages/base/src/widget.ts index b0b036e24b..cf693edac7 100644 --- a/packages/base/src/widget.ts +++ b/packages/base/src/widget.ts @@ -76,7 +76,7 @@ class WidgetModel extends Backbone.Model { /** * The default attributes. */ - defaults() { + defaults(): Backbone.ObjectHash { return { _model_module: '@jupyter-widgets/base', _model_name: 'WidgetModel', @@ -95,7 +95,7 @@ class WidgetModel extends Backbone.Model { * As of backbone 1.1, backbone ignores `patch` if it thinks the * model has never been pushed. */ - isNew() { + isNew(): boolean { return false; } @@ -111,7 +111,7 @@ class WidgetModel extends Backbone.Model { * An ID unique to this model. * comm : Comm instance (optional) */ - initialize(attributes: any, options: {model_id: string; comm?: any; widget_manager: any}) { + initialize(attributes: any, options: {model_id: string; comm?: any; widget_manager: any}): void { super.initialize(attributes, options); // Attributes should be initialized here, since user initialization may depend on it @@ -158,7 +158,7 @@ class WidgetModel extends Backbone.Model { /** * Send a custom msg over the comm. */ - send(content: {}, callbacks: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]) { + send(content: {}, callbacks: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]): void { if (this.comm !== undefined) { const data = {method: 'custom', content: content}; this.comm.send(data, callbacks, {}, buffers); @@ -197,7 +197,7 @@ class WidgetModel extends Backbone.Model { /** * Handle when a widget comm is closed. */ - _handle_comm_closed(msg: KernelMessage.ICommCloseMsg) { + _handle_comm_closed(msg: KernelMessage.ICommCloseMsg): void { this.trigger('comm:close'); this.close(true); } @@ -240,7 +240,7 @@ class WidgetModel extends Backbone.Model { * * This function is meant for internal use only. Values set here will not be propagated on a sync. */ - set_state(state: any) { + set_state(state: any): void { this._state_lock = state; try { this.set(state); @@ -257,7 +257,7 @@ class WidgetModel extends Backbone.Model { * If drop_default is truthy, attributes that are equal to their default * values are dropped. */ - get_state(drop_defaults: boolean) { + get_state(drop_defaults: boolean): any { const fullState = this.attributes; if (drop_defaults) { // if defaults is a function, call it @@ -280,7 +280,7 @@ class WidgetModel extends Backbone.Model { * * execution_state : ('busy', 'idle', 'starting') */ - _handle_status(msg: KernelMessage.IStatusMsg) { + _handle_status(msg: KernelMessage.IStatusMsg): void { if (this.comm !== void 0) { if (msg.content.execution_state === 'idle') { this._pending_msgs--; @@ -308,7 +308,7 @@ class WidgetModel extends Backbone.Model { * We just call the super method, in which val and options are optional. * Handles both "key", value and {key: value} -style arguments. */ - set(key: any, val?: any, options?: any) { + set(key: any, val?: any, options?: any): any { // Call our patched backbone set. See #1642 and #1643. const return_value = backbonePatch.set.call(this, key, val, options); @@ -431,7 +431,7 @@ class WidgetModel extends Backbone.Model { * primitive object that is a snapshot of the widget state that may have * binary array buffers. */ - serialize(state: {[key: string]: any}) { + serialize(state: {[key: string]: any}): {[key: string]: any} { const serializers = (this.constructor as typeof WidgetModel).serializers || {}; for (const k of Object.keys(state)) { try { @@ -455,11 +455,11 @@ class WidgetModel extends Backbone.Model { /** * Send a sync message to the kernel. */ - send_sync_message(state: {}, callbacks: any = {}) { + send_sync_message(state: {}, callbacks: any = {}): void { try { callbacks.iopub = callbacks.iopub || {}; const statuscb = callbacks.iopub.status; - callbacks.iopub.status = (msg: KernelMessage.IStatusMsg) => { + callbacks.iopub.status = (msg: KernelMessage.IStatusMsg): void => { this._handle_status(msg); if (statuscb) { statuscb(msg); @@ -484,7 +484,7 @@ class WidgetModel extends Backbone.Model { * * This invokes a Backbone.Sync. */ - save_changes(callbacks?: {}) { + save_changes(callbacks?: {}): void { if (this.comm_live) { const options: any = {patch: true}; if (callbacks) { @@ -502,7 +502,7 @@ class WidgetModel extends Backbone.Model { * the second form will result in foo being called twice * while the first will call foo only once. */ - on_some_change(keys: string[], callback: (...args: any[]) => void, context: any) { + on_some_change(keys: string[], callback: (...args: any[]) => void, context: any): void { this.on('change', (...args) => { if (keys.some(this.hasChanged, this)) { callback.apply(context, args); @@ -514,7 +514,7 @@ class WidgetModel extends Backbone.Model { * Serialize the model. See the deserialization function at the top of this file * and the kernel-side serializer/deserializer. */ - toJSON(options: any) { + toJSON(options: any): string { return `IPY_MODEL_${this.model_id}`; } @@ -523,7 +523,7 @@ class WidgetModel extends Backbone.Model { * is an instance of widget manager, which is required for the * deserialization of widget models. */ - static _deserialize_state(state: {[key: string]: any}, manager: managerBase.ManagerBase) { + static _deserialize_state(state: {[key: string]: any}, manager: managerBase.ManagerBase): Promise> { const serializers = this.serializers; let deserialized: {[key: string]: any}; if (serializers) { @@ -573,7 +573,7 @@ class DOMWidgetModel extends WidgetModel { style: {deserialize: unpack_models}, }; - defaults() { + defaults(): Backbone.ObjectHash { return utils.assign(super.defaults(), { _dom_classes: [] // We do not declare defaults for the layout and style attributes. @@ -599,7 +599,7 @@ class WidgetView extends NativeView { /** * Initializer, called at the end of the constructor. */ - initialize(parameters: WidgetView.IInitializeParameters) { + initialize(parameters: WidgetView.IInitializeParameters): void { this.listenTo(this.model, 'change', () => { const changed = Object.keys(this.model.changedAttributes() || {}); if (changed[0] === '_view_count' && changed.length === 1) { @@ -635,7 +635,7 @@ class WidgetView extends NativeView { * * Update view to be consistent with this.model */ - update(options?: any) { + update(options?: any): void { return; } @@ -651,7 +651,7 @@ class WidgetView extends NativeView { /** * Create and promise that resolves to a child view of a given model */ - create_child_view(child_model: WidgetModel, options = {}) { + create_child_view(child_model: WidgetModel, options = {}): Promise { options = { parent: this, ...options}; return this.model.widget_manager.create_view(child_model, options) .catch(utils.reject('Could not create child view', true)); @@ -667,11 +667,11 @@ class WidgetView extends NativeView { /** * Send a custom msg associated with this view. */ - send(content: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]) { + send(content: {}, buffers?: ArrayBuffer[] | ArrayBufferView[]): void { this.model.send(content, this.callbacks(), buffers); } - touch() { + touch(): void { this.model.save_changes(this.callbacks()); } @@ -718,7 +718,7 @@ class JupyterPhosphorWidget extends Widget { * * This causes the view to be destroyed as well with 'remove' */ - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -735,7 +735,7 @@ class JupyterPhosphorWidget extends Widget { * Any custom phosphor widget used inside a Jupyter widget should override * the processMessage function like this. */ - processMessage(msg: Message) { + processMessage(msg: Message): void { super.processMessage(msg); this._view.processPhosphorMessage(msg); } @@ -758,7 +758,7 @@ class JupyterPhosphorPanelWidget extends Panel { * Any custom phosphor widget used inside a Jupyter widget should override * the processMessage function like this. */ - processMessage(msg: Message) { + processMessage(msg: Message): void { super.processMessage(msg); this._view.processPhosphorMessage(msg); } @@ -768,7 +768,7 @@ class JupyterPhosphorPanelWidget extends Panel { * * This causes the view to be destroyed as well with 'remove' */ - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -787,7 +787,7 @@ class DOMWidgetView extends WidgetView { /** * Public constructor */ - initialize(parameters: WidgetView.IInitializeParameters) { + initialize(parameters: WidgetView.IInitializeParameters): void { super.initialize(parameters); this.listenTo(this.model, 'change:_dom_classes', (model: WidgetModel, new_classes: string[]) => { @@ -817,7 +817,7 @@ class DOMWidgetView extends WidgetView { }); } - setLayout(layout: WidgetModel, oldLayout?: WidgetModel) { + setLayout(layout: WidgetModel, oldLayout?: WidgetModel): void { if (layout) { this.layoutPromise = this.layoutPromise.then((oldLayoutView) => { if (oldLayoutView) { @@ -843,7 +843,7 @@ class DOMWidgetView extends WidgetView { } } - setStyle(style: WidgetModel, oldStyle?: WidgetModel) { + setStyle(style: WidgetModel, oldStyle?: WidgetModel): void { if (style) { this.stylePromise = this.stylePromise.then((oldStyleView) => { if (oldStyleView) { @@ -868,7 +868,7 @@ class DOMWidgetView extends WidgetView { /** * Update the DOM classes applied to an element, default to this.el. */ - update_classes(old_classes: string[], new_classes: string[], el?: HTMLElement) { + update_classes(old_classes: string[], new_classes: string[], el?: HTMLElement): void { if (el === undefined) { el = this.el; } @@ -912,7 +912,7 @@ class DOMWidgetView extends WidgetView { * el: optional DOM element handle, defaults to this.el * Element that the classes are applied to. */ - update_mapped_classes(class_map: {[key: string]: string[]}, trait_name: string, el?: HTMLElement) { + update_mapped_classes(class_map: {[key: string]: string[]}, trait_name: string, el?: HTMLElement): void { let key = this.model.previous(trait_name); const old_classes = class_map[key] ? class_map[key] : []; key = this.model.get(trait_name); @@ -921,13 +921,13 @@ class DOMWidgetView extends WidgetView { this.update_classes(old_classes, new_classes, el || this.el); } - set_mapped_classes(class_map: {[key: string]: string[]}, trait_name: string, el?: HTMLElement) { + set_mapped_classes(class_map: {[key: string]: string[]}, trait_name: string, el?: HTMLElement): void { const key = this.model.get(trait_name); const new_classes = class_map[key] ? class_map[key] : []; this.update_classes([], new_classes, el || this.el); } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.pWidget) { this.pWidget.dispose(); } @@ -940,14 +940,14 @@ class DOMWidgetView extends WidgetView { }); } - remove() { + remove(): any { if (this.pWidget) { this.pWidget.dispose(); } return super.remove(); } - processPhosphorMessage(msg: Message) { + processPhosphorMessage(msg: Message): void { switch (msg.type) { case 'after-attach': this.trigger('displayed'); @@ -955,7 +955,7 @@ class DOMWidgetView extends WidgetView { } } - private _comm_live_update() { + private _comm_live_update(): void { if (this.model.comm_live) { this.pWidget.removeClass('jupyter-widgets-disconnected'); } else { diff --git a/packages/base/src/widget_layout.ts b/packages/base/src/widget_layout.ts index e56de3c444..e6f076aa80 100644 --- a/packages/base/src/widget_layout.ts +++ b/packages/base/src/widget_layout.ts @@ -62,7 +62,7 @@ const css_properties: {[key: string]: string} = { export class LayoutModel extends WidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return assign(super.defaults(), { _model_name: 'LayoutModel', _view_name: 'LayoutView' @@ -75,7 +75,7 @@ class LayoutView extends WidgetView { /** * Public constructor */ - initialize(parameters: WidgetView.IInitializeParameters) { + initialize(parameters: WidgetView.IInitializeParameters): void { this._traitNames = []; super.initialize(parameters); // Register the traits that live on the Python side @@ -88,7 +88,7 @@ class LayoutView extends WidgetView { * Register a CSS trait that is known by the model * @param trait */ - registerTrait(trait: string) { + registerTrait(trait: string): void { this._traitNames.push(trait); // Treat overflow_x and overflow_y as a special case since they are deprecated @@ -125,7 +125,7 @@ class LayoutView extends WidgetView { /** * Handles when a trait value changes */ - handleChange(trait: string, value: any) { + handleChange(trait: string, value: any): void { // should be synchronous so that we can measure later. const parent = this.options.parent as DOMWidgetView; if (parent) { @@ -142,7 +142,7 @@ class LayoutView extends WidgetView { /** * Handles when the value of overflow_x or overflow_y changes */ - handleOverflowChange(trait: string, value: any) { + handleOverflowChange(trait: string, value: any): void { // This differs from the default handleChange method // in that setting `overflow_x` or `overflow_y` to null // when `overflow` is null removes the attribute. @@ -163,7 +163,7 @@ class LayoutView extends WidgetView { /** * Remove the styling from the parent view. */ - unlayout() { + unlayout(): void { const parent = this.options.parent as DOMWidgetView; this._traitNames.forEach((trait) => { if (parent) { diff --git a/packages/base/src/widget_style.ts b/packages/base/src/widget_style.ts index ec8ac6113d..00780b24d6 100644 --- a/packages/base/src/widget_style.ts +++ b/packages/base/src/widget_style.ts @@ -12,7 +12,7 @@ import { export class StyleModel extends WidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { const Derived = this.constructor as typeof StyleModel; return assign(super.defaults(), { _model_name: 'StyleModel', @@ -38,7 +38,7 @@ class StyleView extends WidgetView { /** * Public constructor */ - initialize(parameters: WidgetView.IInitializeParameters) { + initialize(parameters: WidgetView.IInitializeParameters): void { this._traitNames = []; super.initialize(parameters); // Register the traits that live on the Python side @@ -55,7 +55,7 @@ class StyleView extends WidgetView { * Register a CSS trait that is known by the model * @param trait */ - registerTrait(trait: string) { + registerTrait(trait: string): void { this._traitNames.push(trait); // Listen to changes, and set the value on change. @@ -67,7 +67,7 @@ class StyleView extends WidgetView { /** * Handles when a trait value changes */ - handleChange(trait: string, value: any) { + handleChange(trait: string, value: any): void { // should be synchronous so that we can measure later. const parent = this.options.parent as DOMWidgetView; if (parent) { @@ -93,7 +93,7 @@ class StyleView extends WidgetView { /** * Apply styles for all registered traits */ - style() { + style(): void { for (const trait of this._traitNames) { this.handleChange(trait, this.model.get(trait)); } @@ -102,7 +102,7 @@ class StyleView extends WidgetView { /** * Remove the styling from the parent view. */ - unstyle() { + unstyle(): void { const parent = this.options.parent as DOMWidgetView; const ModelType = this.model.constructor as typeof StyleModel; const styleProperties = ModelType.styleProperties; diff --git a/packages/base/test/src/dummy-manager.ts b/packages/base/test/src/dummy-manager.ts index a7dcc351d7..f643f2a7f7 100644 --- a/packages/base/test/src/dummy-manager.ts +++ b/packages/base/test/src/dummy-manager.ts @@ -16,35 +16,35 @@ class MockComm implements widgets.IClassicComm { this.comm_id = `mock-comm-id-${numComms}`; numComms += 1; } - on_open(fn: Function) { + on_open(fn: Function): void { this._on_open = fn; } - on_close(fn: Function) { + on_close(fn: Function): void { this._on_close = fn; } - on_msg(fn: Function) { + on_msg(fn: Function): void { this._on_msg = fn; } - _process_msg(msg: any) { + _process_msg(msg: any): any { if (this._on_msg) { return this._on_msg(msg); } else { return Promise.resolve(); } } - open() { + open(): string { if (this._on_open) { this._on_open(); } return ''; } - close() { + close(): string { if (this._on_close) { this._on_close(); } return ''; } - send() { + send(): string { return ''; } comm_id: string; @@ -66,11 +66,11 @@ const typesToArray: {[key: string]: any} = { }; -const JSONToArray = function(obj: any) { +const JSONToArray = function(obj: any): any { return new typesToArray[obj.dtype](obj.buffer.buffer); }; -const arrayToJSON = function(obj: any) { +const arrayToJSON = function(obj: any): any { const dtype = Object.keys(typesToArray).filter( i => typesToArray[i] === obj.constructor)[0]; return {dtype, buffer: obj}; @@ -83,7 +83,7 @@ const array_serialization = { class TestWidget extends widgets.WidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_module: 'test-widgets', _model_name: 'TestWidget', @@ -97,11 +97,11 @@ class TestWidget extends widgets.WidgetModel { } class TestWidgetView extends widgets.WidgetView { - render() { + render(): void { this._rendered += 1; super.render(); } - remove() { + remove(): void { this._removed += 1; super.remove(); } @@ -114,7 +114,7 @@ class BinaryWidget extends TestWidget { ...widgets.WidgetModel.serializers, array: array_serialization }; - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'BinaryWidget', _view_name: 'BinaryWidgetView', @@ -123,7 +123,7 @@ class BinaryWidget extends TestWidget { } class BinaryWidgetView extends TestWidgetView { - render() { + render(): void { this._rendered += 1; } _rendered = 0; @@ -138,7 +138,7 @@ class DummyManager extends widgets.ManagerBase { this.el = window.document.createElement('div'); } - display_view(msg: services.KernelMessage.IMessage, view: Backbone.View, options: any) { + display_view(msg: services.KernelMessage.IMessage, view: Backbone.View, options: any): Promise { // TODO: make this a spy // TODO: return an html element return Promise.resolve(view).then(view => { @@ -166,11 +166,11 @@ class DummyManager extends widgets.ManagerBase { } } - _get_comm_info() { + _get_comm_info(): Promise<{}> { return Promise.resolve({}); } - _create_comm() { + _create_comm(): Promise { return Promise.resolve(new MockComm()); } diff --git a/packages/base/test/src/manager_test.ts b/packages/base/test/src/manager_test.ts index a0677bd26d..84b81198a5 100644 --- a/packages/base/test/src/manager_test.ts +++ b/packages/base/test/src/manager_test.ts @@ -285,7 +285,7 @@ describe('ManagerBase', function() { view_module_version: '1.0.0', }; class NewWidgetManager extends DummyManager { - _create_comm() { + _create_comm(): Promise { return Promise.reject('failed creation'); } } diff --git a/packages/base/test/src/widget_test.ts b/packages/base/test/src/widget_test.ts index eda74d973b..6717020adc 100644 --- a/packages/base/test/src/widget_test.ts +++ b/packages/base/test/src/widget_test.ts @@ -64,7 +64,7 @@ describe('unpack_models', function() { describe('WidgetModel', function() { before(async function() { - this.setup = async function() { + this.setup = async function(): Promise { this.manager = new DummyManager(); this.comm = new MockComm(); sinon.spy(this.comm, 'send'); @@ -80,12 +80,12 @@ describe('WidgetModel', function() { }); this.widget.constructor.serializers = { times3: { - deserialize: (value: number, manager: any) => { + deserialize: (value: number, manager: any): number => { return value * 3.0; } }, halve: { - deserialize: (value: number, manager: any) => { + deserialize: (value: number, manager: any): Promise => { return Promise.resolve(value / 2.0); } }, diff --git a/packages/controls/src/phosphor/accordion.ts b/packages/controls/src/phosphor/accordion.ts index 766e877edd..f812afe4e2 100644 --- a/packages/controls/src/phosphor/accordion.ts +++ b/packages/controls/src/phosphor/accordion.ts @@ -63,7 +63,7 @@ class Collapse extends Widget { this.collapsed = false; } - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -73,7 +73,7 @@ class Collapse extends Widget { this._content = null; } - get widget() { + get widget(): Widget { return this._widget; } @@ -91,7 +91,7 @@ class Collapse extends Widget { this._content.addWidget(widget); } - get collapsed() { + get collapsed(): boolean { return this._collapsed; } @@ -107,7 +107,7 @@ class Collapse extends Widget { } } - toggle() { + toggle(): void { this.collapsed = !this.collapsed; } @@ -115,7 +115,7 @@ class Collapse extends Widget { return this._collapseChanged; } - private _collapse() { + private _collapse(): void { this._collapsed = true; if (this._content) { this._content.hide(); @@ -123,7 +123,7 @@ class Collapse extends Widget { this.removeClass(COLLAPSE_CLASS_OPEN); this._collapseChanged.emit(void 0); } - private _uncollapse() { + private _uncollapse(): void { this._collapsed = false; if (this._content) { this._content.show(); @@ -152,7 +152,7 @@ class Collapse extends Widget { } } - private _evtClick(event: MouseEvent) { + private _evtClick(event: MouseEvent): void { this.toggle(); } @@ -277,14 +277,14 @@ class Accordion extends Panel { } } - private _wrapWidget(widget: Widget) { + private _wrapWidget(widget: Widget): Collapse { const collapse = new Collapse({ widget }); collapse.addClass(ACCORDION_CHILD_CLASS); collapse.collapseChanged.connect(this._onCollapseChange, this); return collapse; } - private _onCollapseChange(sender: Collapse) { + private _onCollapseChange(sender: Collapse): void { if (!sender.collapsed) { this._selection.value = sender; } else if (this._selection.value === sender && sender.collapsed) { @@ -292,7 +292,7 @@ class Accordion extends Panel { } } - private _onSelectionChanged(sender: Selection, change: Selection.ISelectionChangedArgs) { + private _onSelectionChanged(sender: Selection, change: Selection.ISelectionChangedArgs): void { // Collapse previous widget, open current widget const pv = change.previousValue; const cv = change.currentValue; diff --git a/packages/controls/src/phosphor/currentselection.ts b/packages/controls/src/phosphor/currentselection.ts index e4e09d9b68..81e93794be 100644 --- a/packages/controls/src/phosphor/currentselection.ts +++ b/packages/controls/src/phosphor/currentselection.ts @@ -351,7 +351,7 @@ class Selection { /** * Set the current value based on the current index. */ - private _updateSelectedValue() { + private _updateSelectedValue(): void { const i = this._index; this._value = i !== null ? this._array[i] : null; } diff --git a/packages/controls/src/utils.ts b/packages/controls/src/utils.ts index 2c5efc3756..31df6002fe 100644 --- a/packages/controls/src/utils.ts +++ b/packages/controls/src/utils.ts @@ -9,8 +9,6 @@ import { WrappedError } from '@jupyter-widgets/base'; -import * as _ from 'underscore'; - /** * Creates a wrappable Promise rejection function. * @@ -20,7 +18,7 @@ import * as _ from 'underscore'; */ export function reject(message: any, log: any) { - return function promiseRejection(error: any) { + return function promiseRejection(error: any): Promise { const wrapped_error = new WrappedError(message, error); if (log) { console.error(wrapped_error); diff --git a/packages/controls/src/widget_audio.ts b/packages/controls/src/widget_audio.ts index 735c77e961..1c0bdd90af 100644 --- a/packages/controls/src/widget_audio.ts +++ b/packages/controls/src/widget_audio.ts @@ -13,7 +13,7 @@ import * as _ from 'underscore'; export class AudioModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'AudioModel', _view_name: 'AudioView', @@ -27,7 +27,7 @@ class AudioModel extends CoreDOMWidgetModel { static serializers = { ...CoreDOMWidgetModel.serializers, - value: {serialize: (value: any) => { + value: {serialize: (value: any): DataView => { return new DataView(value.buffer.slice(0)); }} }; @@ -35,7 +35,7 @@ class AudioModel extends CoreDOMWidgetModel { export class AudioView extends DOMWidgetView { - render() { + render(): void { /** * Called when view is rendered. */ @@ -44,7 +44,7 @@ class AudioView extends DOMWidgetView { this.update(); // Set defaults. } - update() { + update(): void { /** * Update the contents of this view * @@ -77,7 +77,7 @@ class AudioView extends DOMWidgetView { return super.update(); } - remove() { + remove(): void { if (this.el.src) { URL.revokeObjectURL(this.el.src); } @@ -90,7 +90,7 @@ class AudioView extends DOMWidgetView { * #### Notes * This is a read-only attribute. */ - get tagName() { + get tagName(): string { // We can't make this an attribute with a default value // since it would be set after it is needed in the // constructor. diff --git a/packages/controls/src/widget_bool.ts b/packages/controls/src/widget_bool.ts index fe4c68eb2c..d1108432d2 100644 --- a/packages/controls/src/widget_bool.ts +++ b/packages/controls/src/widget_bool.ts @@ -16,9 +16,11 @@ import { import * as _ from 'underscore'; + + export class BoolModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { value: false, disabled: false, @@ -29,7 +31,7 @@ class BoolModel extends CoreDescriptionModel { export class CheckboxModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { indent: true, _view_name: 'CheckboxView', @@ -43,7 +45,7 @@ class CheckboxView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -80,7 +82,7 @@ class CheckboxView extends DescriptionView { * Update the description span (rather than the label) since * we want the description to the right of the checkbox. */ - updateDescription() { + updateDescription(): void { // can be called before the view is fully initialized if (this.checkboxLabel == null) { return; @@ -96,7 +98,7 @@ class CheckboxView extends DescriptionView { * Update the visibility of the label in the super class * to provide the optional indent. */ - updateIndent() { + updateIndent(): void { const indent = this.model.get('indent'); this.label.style.display = indent ? '' : 'none'; } @@ -113,7 +115,7 @@ class CheckboxView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - _handle_click() { + _handle_click(): void { const value = this.model.get('value'); this.model.set('value', !value, {updated_view: this}); this.touch(); @@ -125,7 +127,7 @@ class CheckboxView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { this.checkbox.checked = this.model.get('value'); if (options === undefined || options.updated_view != this) { @@ -142,7 +144,7 @@ class CheckboxView extends DescriptionView { export class ToggleButtonModel extends BoolModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'ToggleButtonView', _model_name: 'ToggleButtonModel', @@ -158,7 +160,7 @@ class ToggleButtonView extends DOMWidgetView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('jupyter-button'); @@ -168,11 +170,11 @@ class ToggleButtonView extends DOMWidgetView { this.update(); // Set defaults. } - update_button_style() { + update_button_style(): void { this.update_mapped_classes(ToggleButtonView.class_map, 'button_style'); } - set_button_style() { + set_button_style(): void { this.set_mapped_classes(ToggleButtonView.class_map, 'button_style'); } @@ -182,7 +184,7 @@ class ToggleButtonView extends DOMWidgetView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any){ + update(options?: any): void { if (this.model.get('value')) { this.el.classList.add('mod-active'); } else { @@ -224,7 +226,7 @@ class ToggleButtonView extends DOMWidgetView { * Calling model.set will trigger all of the other views of the * model to update. */ - _handle_click(event: MouseEvent) { + _handle_click(event: MouseEvent): void { event.preventDefault(); const value = this.model.get('value'); this.model.set('value', !value, {updated_view: this}); @@ -237,7 +239,7 @@ class ToggleButtonView extends DOMWidgetView { * #### Notes * This is a read-only attribute. */ - get tagName() { + get tagName(): string { // We can't make this an attribute with a default value // since it would be set after it is needed in the // constructor. @@ -257,7 +259,7 @@ class ToggleButtonView extends DOMWidgetView { export class ValidModel extends BoolModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { readout: 'Invalid', _view_name: 'ValidView', @@ -271,7 +273,7 @@ class ValidView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-valid'); @@ -291,7 +293,7 @@ class ValidView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { this.el.classList.remove('mod-valid'); this.el.classList.remove('mod-invalid'); this.readout.textContent = this.model.get('readout'); diff --git a/packages/controls/src/widget_box.ts b/packages/controls/src/widget_box.ts index 13ce8cce37..13032d33ba 100644 --- a/packages/controls/src/widget_box.ts +++ b/packages/controls/src/widget_box.ts @@ -30,7 +30,7 @@ import $ from 'jquery'; export class BoxModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'BoxView', _model_name: 'BoxModel', @@ -47,7 +47,7 @@ class BoxModel extends CoreDOMWidgetModel { export class HBoxModel extends BoxModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'HBoxView', _model_name: 'HBoxModel', @@ -57,7 +57,7 @@ class HBoxModel extends BoxModel { export class VBoxModel extends BoxModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'VBoxView', _model_name: 'VBoxModel', @@ -68,12 +68,12 @@ class VBoxModel extends BoxModel { export class BoxView extends DOMWidgetView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new JupyterPhosphorPanelWidget({ view: this }); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // Boxes don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -83,7 +83,7 @@ class BoxView extends DOMWidgetView { this.$el = $(this.pWidget.node); } - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.children_views = new ViewList(this.add_child_model, null, this); this.listenTo(this.model, 'change:children', this.update_children); @@ -94,13 +94,13 @@ class BoxView extends DOMWidgetView { this.pWidget.addClass('widget-box'); } - render() { + render(): void { super.render(); this.update_children(); this.set_box_style(); } - update_children() { + update_children(): void { this.children_views.update(this.model.get('children')).then((views: DOMWidgetView[]) => { // Notify all children that their sizes may have changed. views.forEach( (view) => { @@ -109,15 +109,15 @@ class BoxView extends DOMWidgetView { }); } - update_box_style() { + update_box_style(): void { this.update_mapped_classes(BoxView.class_map, 'box_style'); } - set_box_style() { + set_box_style(): void { this.set_mapped_classes(BoxView.class_map, 'box_style'); } - add_child_model(model: WidgetModel) { + add_child_model(model: WidgetModel): Promise { // we insert a dummy element so the order is preserved when we add // the rendered content later. const dummy = new Widget(); @@ -132,7 +132,7 @@ class BoxView extends DOMWidgetView { }).catch(reject('Could not add child view to box', true)); } - remove() { + remove(): void { this.children_views = null; super.remove(); } @@ -153,7 +153,7 @@ class HBoxView extends BoxView { /** * Public constructor */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.pWidget.addClass('widget-hbox'); } @@ -164,7 +164,7 @@ class VBoxView extends BoxView { /** * Public constructor */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.pWidget.addClass('widget-vbox'); } @@ -175,7 +175,7 @@ class GridBoxView extends BoxView { /** * Public constructor */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.pWidget.addClass('widget-gridbox'); // display needn't be set to flex and grid @@ -185,7 +185,7 @@ class GridBoxView extends BoxView { export class GridBoxModel extends BoxModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'GridBoxView', _model_name: 'GridBoxModel', diff --git a/packages/controls/src/widget_button.ts b/packages/controls/src/widget_button.ts index c4311b0d5e..58cbac2c04 100644 --- a/packages/controls/src/widget_button.ts +++ b/packages/controls/src/widget_button.ts @@ -17,7 +17,7 @@ import * as _ from 'underscore'; export class ButtonStyleModel extends StyleModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ButtonStyleModel', _model_module: '@jupyter-widgets/controls', @@ -42,7 +42,7 @@ class ButtonStyleModel extends StyleModel { export class ButtonModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { description: '', tooltip: '', @@ -61,7 +61,7 @@ class ButtonView extends DOMWidgetView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('jupyter-button'); @@ -77,7 +77,7 @@ class ButtonView extends DOMWidgetView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { this.el.disabled = this.model.get('disabled'); this.el.setAttribute('title', this.model.get('tooltip')); @@ -99,11 +99,11 @@ class ButtonView extends DOMWidgetView { return super.update(); } - update_button_style() { + update_button_style(): void { this.update_mapped_classes(ButtonView.class_map, 'button_style'); } - set_button_style() { + set_button_style(): void { this.set_mapped_classes(ButtonView.class_map, 'button_style'); } @@ -119,7 +119,7 @@ class ButtonView extends DOMWidgetView { /** * Handles when the button is clicked. */ - _handle_click(event: MouseEvent) { + _handle_click(event: MouseEvent): void { event.preventDefault(); this.send({event: 'click'}); } @@ -130,7 +130,7 @@ class ButtonView extends DOMWidgetView { * #### Notes * This is a read-only attribute. */ - get tagName() { + get tagName(): string { // We can't make this an attribute with a default value // since it would be set after it is needed in the // constructor. diff --git a/packages/controls/src/widget_color.ts b/packages/controls/src/widget_color.ts index 2cdbe22490..b7e8280185 100644 --- a/packages/controls/src/widget_color.ts +++ b/packages/controls/src/widget_color.ts @@ -19,7 +19,7 @@ const named_colors: {[key: string]: string} = { aliceblue: '#f0f8ff', antiquewhi export class ColorPickerModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { value: 'black', concise: false, @@ -31,7 +31,7 @@ class ColorPickerModel extends CoreDescriptionModel { export class ColorPickerView extends DescriptionView { - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -66,7 +66,7 @@ class ColorPickerView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { if (options === undefined || options.updated_view != this) { const disabled = this.model.get('disabled'); this._textbox.disabled = disabled; @@ -86,13 +86,13 @@ class ColorPickerView extends DescriptionView { }; } - private _update_value() { + private _update_value(): void { const value = this.model.get('value'); this._colorpicker.value = color2hex(value); this._textbox.value = value; } - private _update_concise() { + private _update_concise(): void { const concise = this.model.get('concise'); if (concise) { this.el.classList.add('concise'); @@ -103,12 +103,12 @@ class ColorPickerView extends DescriptionView { } } - private _picker_change() { + private _picker_change(): void { this.model.set('value', this._colorpicker.value); this.touch(); } - private _text_change() { + private _text_change(): void { const value = this._validate_color( this._textbox.value, this.model.get('value') @@ -117,7 +117,7 @@ class ColorPickerView extends DescriptionView { this.touch(); } - private _validate_color(color: string, fallback: any) { + private _validate_color(color: string, fallback: any): any { return color.match(/#[a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?$/) || named_colors[color.toLowerCase()] ? color: fallback; } @@ -131,11 +131,11 @@ class ColorPickerView extends DescriptionView { * From a valid html color (named color, 6-digits or 3-digits hex format) * return a 6-digits hexadecimal color #rrggbb. */ -function color2hex(color: string) { +function color2hex(color: string): string { return named_colors[color.toLowerCase()] || rgb3_to_rgb6(color); } -function rgb3_to_rgb6(rgb: string) { +function rgb3_to_rgb6(rgb: string): string { if (rgb.length === 7) { return rgb; } else { diff --git a/packages/controls/src/widget_controller.ts b/packages/controls/src/widget_controller.ts index 48d8afc2e1..7b4251344c 100644 --- a/packages/controls/src/widget_controller.ts +++ b/packages/controls/src/widget_controller.ts @@ -6,7 +6,7 @@ import { } from './widget_core'; import { - DOMWidgetView, unpack_models, ViewList, JupyterPhosphorPanelWidget + DOMWidgetView, unpack_models, ViewList, JupyterPhosphorPanelWidget, Dict } from '@jupyter-widgets/base'; import { @@ -24,7 +24,7 @@ import $ from 'jquery'; export class ControllerButtonModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ControllerButtonModel', _view_name: 'ControllerButtonView', @@ -39,7 +39,7 @@ class ControllerButtonModel extends CoreDOMWidgetModel { */ export class ControllerButtonView extends DOMWidgetView { - render() { + render(): void { this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-controller-button'); this.el.style.width = 'fit-content'; @@ -67,7 +67,7 @@ class ControllerButtonView extends DOMWidgetView { this.el.appendChild(this.label); } - update() { + update(): void { this.bar.style.height = (100 * this.model.get('value')) + '%'; } @@ -79,7 +79,7 @@ class ControllerButtonView extends DOMWidgetView { export class ControllerAxisModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ControllerAxisModel', _view_name: 'ControllerAxisView', @@ -93,7 +93,7 @@ class ControllerAxisModel extends CoreDOMWidgetModel { */ export class ControllerAxisView extends DOMWidgetView { - render() { + render(): void { this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-controller-axis'); this.el.style.width = '16px'; @@ -126,7 +126,7 @@ class ControllerAxisView extends DOMWidgetView { this.update(); } - update() { + update(): void { this.bullet.style.top = (50 * (this.model.get('value') + 1)) + '%'; } @@ -144,7 +144,7 @@ class ControllerModel extends CoreDOMWidgetModel { axes: {deserialize: unpack_models} }; - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ControllerModel', _view_name: 'ControllerView', @@ -158,7 +158,7 @@ class ControllerModel extends CoreDOMWidgetModel { }); } - initialize(attributes: any, options: any) { + initialize(attributes: any, options: any): void { super.initialize(attributes, options); if (navigator.getGamepads === void 0) { // Checks if the browser supports the gamepad API @@ -185,7 +185,7 @@ class ControllerModel extends CoreDOMWidgetModel { * Once one is connected, it will start the update loop, which * populates the update of axes and button values. */ - wait_loop() { + wait_loop(): void { const index = this.get('index'); const pad = navigator.getGamepads()[index]; if (pad) { @@ -207,7 +207,7 @@ class ControllerModel extends CoreDOMWidgetModel { * axes: list of Axis models, * } */ - setup(pad: Gamepad) { + setup(pad: Gamepad): Promise> { // Set up the main gamepad attributes this.set({ name: pad.id, @@ -230,7 +230,7 @@ class ControllerModel extends CoreDOMWidgetModel { * Update axes and buttons values, until the gamepad is disconnected. * When the gamepad is disconnected, this.reset_gamepad is called. */ - update_loop() { + update_loop(): void { const index = this.get('index'); const id = this.get('name'); const pad = navigator.getGamepads()[index]; @@ -260,7 +260,7 @@ class ControllerModel extends CoreDOMWidgetModel { /** * Resets the gamepad attributes, and start the wait_loop. */ - reset_gamepad() { + reset_gamepad(): void { this.get('buttons').forEach(function(button: ControllerButtonModel) { button.close(); }); @@ -322,12 +322,12 @@ class ControllerModel extends CoreDOMWidgetModel { export class ControllerView extends DOMWidgetView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new JupyterPhosphorPanelWidget({ view: this }); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // Boxes don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -337,7 +337,7 @@ class ControllerView extends DOMWidgetView { this.$el = $(this.pWidget.node); } - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.button_views = new ViewList(this.add_button, null, this); @@ -353,7 +353,7 @@ class ControllerView extends DOMWidgetView { this.listenTo(this.model, 'change:name', this.update_label); } - render() { + render(): void { this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-controller'); this.label = document.createElement('div'); @@ -373,11 +373,11 @@ class ControllerView extends DOMWidgetView { this.update_label(); } - update_label() { + update_label(): void { this.label.textContent = this.model.get('name') || this.model.readout; } - add_button(model: ControllerButtonModel) { + add_button(model: ControllerButtonModel): Promise { // we insert a dummy element so the order is preserved when we add // the rendered content later. const dummy = new Widget(); @@ -392,7 +392,7 @@ class ControllerView extends DOMWidgetView { }).catch(utils.reject('Could not add child button view to controller', true)); } - add_axis(model: ControllerAxisModel) { + add_axis(model: ControllerAxisModel): Promise { // we insert a dummy element so the order is preserved when we add // the rendered content later. const dummy = new Widget(); @@ -407,7 +407,7 @@ class ControllerView extends DOMWidgetView { }).catch(utils.reject('Could not add child axis view to controller', true)); } - remove() { + remove(): void { super.remove(); this.button_views.remove(); this.axis_views.remove(); diff --git a/packages/controls/src/widget_core.ts b/packages/controls/src/widget_core.ts index 88b44e65a8..78a8d1bc26 100644 --- a/packages/controls/src/widget_core.ts +++ b/packages/controls/src/widget_core.ts @@ -20,7 +20,7 @@ import * as _ from 'underscore'; export class CoreWidgetModel extends WidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'CoreWidgetModel', _view_module: '@jupyter-widgets/controls', @@ -33,7 +33,7 @@ class CoreWidgetModel extends WidgetModel { export class CoreDOMWidgetModel extends DOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'CoreDOMWidgetModel', _view_module: '@jupyter-widgets/controls', @@ -46,7 +46,7 @@ class CoreDOMWidgetModel extends DOMWidgetModel { export class CoreDescriptionModel extends DescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'CoreDescriptionModel', _view_module: '@jupyter-widgets/controls', diff --git a/packages/controls/src/widget_date.ts b/packages/controls/src/widget_date.ts index ef31202f62..24114a994d 100644 --- a/packages/controls/src/widget_date.ts +++ b/packages/controls/src/widget_date.ts @@ -15,19 +15,6 @@ import { import * as _ from 'underscore'; -export -function serialize_date(value: Date) { - if (value === null) { - return null; - } else { - return { - year: value.getUTCFullYear(), - month: value.getUTCMonth(), - date: value.getUTCDate() - }; - } -} - export interface ISerializedDate { /** * Full year @@ -46,7 +33,20 @@ export interface ISerializedDate { } export -function deserialize_date(value: ISerializedDate) { +function serialize_date(value: Date): ISerializedDate | null { + if (value === null) { + return null; + } else { + return { + year: value.getUTCFullYear(), + month: value.getUTCMonth(), + date: value.getUTCDate() + }; + } +} + +export +function deserialize_date(value: ISerializedDate): Date | null { if (value === null) { return null; } else { @@ -67,7 +67,7 @@ class DatePickerModel extends CoreDescriptionModel { } }; - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { value: null, _model_name: 'DatePickerModel', @@ -78,7 +78,7 @@ class DatePickerModel extends CoreDescriptionModel { export class DatePickerView extends DescriptionView { - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -101,7 +101,7 @@ class DatePickerView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { if (options === undefined || options.updated_view !== this) { this._datepicker.disabled = this.model.get('disabled'); } @@ -119,19 +119,19 @@ class DatePickerView extends DescriptionView { }; } - private _update_value() { + private _update_value(): void { const value = this.model.get('value'); this._datepicker.valueAsDate = value; } - private _picker_change() { + private _picker_change(): void { if (!this._datepicker.validity.badInput) { this.model.set('value', this._datepicker.valueAsDate); this.touch(); } } - private _picker_focusout() { + private _picker_focusout(): void { if (this._datepicker.validity.badInput) { this.model.set('value', null); this.touch(); diff --git a/packages/controls/src/widget_description.ts b/packages/controls/src/widget_description.ts index b7fa55a6d5..05a9db416b 100644 --- a/packages/controls/src/widget_description.ts +++ b/packages/controls/src/widget_description.ts @@ -15,7 +15,7 @@ import { export class DescriptionStyleModel extends StyleModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'DescriptionStyleModel', _model_module: '@jupyter-widgets/controls', @@ -34,7 +34,7 @@ class DescriptionStyleModel extends StyleModel { export class DescriptionModel extends DOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'DescriptionModel', _view_name: 'DescriptionView', @@ -50,7 +50,7 @@ class DescriptionModel extends DOMWidgetModel { export class DescriptionView extends DOMWidgetView { - render() { + render(): void { this.label = document.createElement('label'); this.el.appendChild(this.label); this.label.className = 'widget-label'; @@ -61,11 +61,11 @@ class DescriptionView extends DOMWidgetView { this.updateDescription(); } - typeset(element: HTMLElement, text?: string){ + typeset(element: HTMLElement, text?: string): void { this.displayed.then(() => typeset(element, text)); } - updateDescription() { + updateDescription(): void { const description = this.model.get('description'); let description_tooltip = this.model.get('description_tooltip'); if (description_tooltip === null) { diff --git a/packages/controls/src/widget_float.ts b/packages/controls/src/widget_float.ts index 5a847b07df..a0650dbd35 100644 --- a/packages/controls/src/widget_float.ts +++ b/packages/controls/src/widget_float.ts @@ -18,7 +18,7 @@ import { export class FloatModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FloatModel', value: 0, @@ -28,7 +28,7 @@ class FloatModel extends CoreDescriptionModel { export class BoundedFloatModel extends FloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'BoundedFloatModel', max: 100.0, @@ -39,7 +39,7 @@ class BoundedFloatModel extends FloatModel { export class FloatSliderModel extends BoundedFloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FloatSliderModel', _view_name: 'FloatSliderView', @@ -53,13 +53,13 @@ class FloatSliderModel extends BoundedFloatModel { disabled: false, }); } - initialize(attributes: any, options: { model_id: string; comm?: any; widget_manager: any }) { + initialize(attributes: any, options: { model_id: string; comm?: any; widget_manager: any }): void { super.initialize(attributes, options); this.on('change:readout_format', this.update_readout_format, this); this.update_readout_format(); } - update_readout_format() { + update_readout_format(): void { this.readout_formatter = format(this.get('readout_format')); } @@ -68,7 +68,7 @@ class FloatSliderModel extends BoundedFloatModel { export class FloatLogSliderModel extends BoundedFloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FloatLogSliderModel', _view_name: 'FloatLogSliderView', @@ -86,13 +86,13 @@ class FloatLogSliderModel extends BoundedFloatModel { max: 4 }); } - initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }) { + initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }): void { super.initialize(attributes, options); this.on('change:readout_format', this.update_readout_format, this); this.update_readout_format(); } - update_readout_format() { + update_readout_format(): void { this.readout_formatter = format(this.get('readout_format')); } @@ -108,7 +108,7 @@ class FloatSliderView extends IntSliderView { * Validate the value of the slider before sending it to the back-end * and applying it to the other views on the page. */ - _validate_slide_value(x: any) { + _validate_slide_value(x: any): any { return x; } @@ -119,7 +119,7 @@ class FloatSliderView extends IntSliderView { export class FloatLogSliderView extends BaseIntSliderView { - update(options?: any) { + update(options?: any): void { super.update(options); const min = this.model.get('min'); const max = this.model.get('max'); @@ -164,7 +164,7 @@ class FloatLogSliderView extends BaseIntSliderView { * * if any of these conditions are not met, the text is reset */ - handleTextChange() { + handleTextChange(): void { let value = this.stringToValue(this.readout.textContent); const vmin = this.model.get('min'); const vmax = this.model.get('max'); @@ -187,7 +187,7 @@ class FloatLogSliderView extends BaseIntSliderView { /** * Called when the slider value is changing. */ - handleSliderChange(e: Event, ui: { value: any }) { + handleSliderChange(e: Event, ui: { value: any }): void { const base = this.model.get('base'); const actual_value = Math.pow(base, this._validate_slide_value(ui.value)); this.readout.textContent = this.valueToString(actual_value); @@ -205,14 +205,14 @@ class FloatLogSliderView extends BaseIntSliderView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleSliderChanged(e: Event, ui: { value: any }) { + handleSliderChanged(e: Event, ui: { value: any }): void { const base = this.model.get('base'); const actual_value = Math.pow(base,this._validate_slide_value(ui.value)); this.model.set('value', actual_value, {updated_view: this}); this.touch(); } - _validate_slide_value(x: any) { + _validate_slide_value(x: any): any { return x; } @@ -227,7 +227,7 @@ class FloatRangeSliderView extends IntRangeSliderView { * Validate the value of the slider before sending it to the back-end * and applying it to the other views on the page. */ - _validate_slide_value(x: any) { + _validate_slide_value(x: any): any { return x; } @@ -239,7 +239,7 @@ class FloatRangeSliderView extends IntRangeSliderView { export class FloatTextModel extends FloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FloatTextModel', _view_name: 'FloatTextView', @@ -251,7 +251,7 @@ class FloatTextModel extends FloatModel { export class BoundedFloatTextModel extends BoundedFloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'BoundedFloatTextModel', _view_name: 'FloatTextView', @@ -270,7 +270,7 @@ class FloatTextView extends IntTextView { /** * Handle key press */ - handleKeypress(e: KeyboardEvent) { + handleKeypress(e: KeyboardEvent): void { // Overwrite IntTextView's handleKeypress // which prevents decimal points. e.stopPropagation(); @@ -279,7 +279,7 @@ class FloatTextView extends IntTextView { /** * Handle key up */ - handleKeyUp(e: KeyboardEvent) { + handleKeyUp(e: KeyboardEvent): void { // Overwrite IntTextView's handleKeyUp // which prevents decimal points. } @@ -287,7 +287,7 @@ class FloatTextView extends IntTextView { export class FloatProgressModel extends BoundedFloatModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FloatProgressModel', _view_name: 'ProgressView', diff --git a/packages/controls/src/widget_image.ts b/packages/controls/src/widget_image.ts index 53d1144f5e..72e467af2e 100644 --- a/packages/controls/src/widget_image.ts +++ b/packages/controls/src/widget_image.ts @@ -13,7 +13,7 @@ import * as _ from 'underscore'; export class ImageModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ImageModel', _view_name: 'ImageView', @@ -26,7 +26,7 @@ class ImageModel extends CoreDOMWidgetModel { static serializers = { ...CoreDOMWidgetModel.serializers, - value: {serialize: (value: any) => { + value: {serialize: (value: any): DataView => { return new DataView(value.buffer.slice(0)); }} }; @@ -34,7 +34,7 @@ class ImageModel extends CoreDOMWidgetModel { export class ImageView extends DOMWidgetView { - render() { + render(): void { /** * Called when view is rendered. */ @@ -44,7 +44,7 @@ class ImageView extends DOMWidgetView { this.update(); // Set defaults. } - update() { + update(): void { /** * Update the contents of this view * @@ -84,7 +84,7 @@ class ImageView extends DOMWidgetView { return super.update(); } - remove() { + remove(): void { if (this.el.src) { URL.revokeObjectURL(this.el.src); } @@ -97,7 +97,7 @@ class ImageView extends DOMWidgetView { * #### Notes * This is a read-only attribute. */ - get tagName() { + get tagName(): string { // We can't make this an attribute with a default value // since it would be set after it is needed in the // constructor. diff --git a/packages/controls/src/widget_int.ts b/packages/controls/src/widget_int.ts index 824672855c..7f7e31ad1f 100644 --- a/packages/controls/src/widget_int.ts +++ b/packages/controls/src/widget_int.ts @@ -28,7 +28,7 @@ import 'jquery-ui/ui/widgets/slider'; export class IntModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'IntModel', value: 0, @@ -38,7 +38,7 @@ class IntModel extends CoreDescriptionModel { export class BoundedIntModel extends IntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'BoundedIntModel', max: 100, @@ -49,7 +49,7 @@ class BoundedIntModel extends IntModel { export class SliderStyleModel extends DescriptionStyleModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SliderStyleModel', }; @@ -67,7 +67,7 @@ class SliderStyleModel extends DescriptionStyleModel { export class IntSliderModel extends BoundedIntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'IntSliderModel', _view_name: 'IntSliderView', @@ -80,12 +80,12 @@ class IntSliderModel extends BoundedIntModel { disabled: false, }); } - initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }) { + initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }): void { super.initialize(attributes, options); this.on('change:readout_format', this.update_readout_format, this); this.update_readout_format(); } - update_readout_format() { + update_readout_format(): void { this.readout_formatter = format(this.get('readout_format')); } readout_formatter: any; @@ -96,7 +96,7 @@ class IntRangeSliderModel extends IntSliderModel {} export abstract class BaseIntSliderView extends DescriptionView { - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -124,7 +124,7 @@ abstract class BaseIntSliderView extends DescriptionView { this.update(); } - update(options?: any) { + update(options?: any): void { /** * Update the contents of this view * @@ -206,7 +206,7 @@ abstract class BaseIntSliderView extends DescriptionView { /** * Returns true if the readout box content overflows. */ - readout_overflow() { + readout_overflow(): boolean { return this.readout.scrollWidth > this.readout.clientWidth; } @@ -230,7 +230,7 @@ abstract class BaseIntSliderView extends DescriptionView { }; } - handleKeyDown(e: KeyboardEvent) { + handleKeyDown(e: KeyboardEvent): void { if (e.keyCode === 13) { /* keyboard keycodes `enter` */ e.preventDefault(); this.handleTextChange(); @@ -264,7 +264,7 @@ abstract class BaseIntSliderView extends DescriptionView { * Validate the value of the slider before sending it to the back-end * and applying it to the other views on the page. */ - _validate_slide_value(x: number) { + _validate_slide_value(x: number): number { return Math.floor(x); } @@ -278,7 +278,7 @@ abstract class BaseIntSliderView extends DescriptionView { export class IntRangeSliderView extends BaseIntSliderView { - update(options?: any) { + update(options?: any): void { super.update(options); this.$slider.slider('option', 'range', true); // values for the range case are validated python-side in @@ -323,7 +323,7 @@ class IntRangeSliderView extends BaseIntSliderView { * * if any of these conditions are not met, the text is reset */ - handleTextChange() { + handleTextChange(): void { let value = this.stringToValue(this.readout.textContent); const vmin = this.model.get('min'); const vmax = this.model.get('max'); @@ -351,7 +351,7 @@ class IntRangeSliderView extends BaseIntSliderView { /** * Called when the slider value is changing. */ - handleSliderChange(e: any, ui: { values: number[]}) { + handleSliderChange(e: any, ui: { values: number[]}): void { const actual_value = ui.values.map(this._validate_slide_value); this.readout.textContent = this.valueToString(actual_value); @@ -368,7 +368,7 @@ class IntRangeSliderView extends BaseIntSliderView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleSliderChanged(e: Event, ui: { values: number[]}) { + handleSliderChanged(e: Event, ui: { values: number[]}): void { const actual_value = ui.values.map(this._validate_slide_value); this.model.set('value', actual_value, {updated_view: this}); this.touch(); @@ -382,7 +382,7 @@ class IntRangeSliderView extends BaseIntSliderView { export class IntSliderView extends BaseIntSliderView { - update(options?: any) { + update(options?: any): void { super.update(options); const min = this.model.get('min'); const max = this.model.get('max'); @@ -424,7 +424,7 @@ class IntSliderView extends BaseIntSliderView { * * if any of these conditions are not met, the text is reset */ - handleTextChange() { + handleTextChange(): void{ let value = this.stringToValue(this.readout.textContent); const vmin = this.model.get('min'); const vmax = this.model.get('max'); @@ -446,7 +446,7 @@ class IntSliderView extends BaseIntSliderView { /** * Called when the slider value is changing. */ - handleSliderChange(e: any, ui: { value: number }) { + handleSliderChange(e: any, ui: { value: number }): void { const actual_value = this._validate_slide_value(ui.value); this.readout.textContent = this.valueToString(actual_value); @@ -463,7 +463,7 @@ class IntSliderView extends BaseIntSliderView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleSliderChanged(e: Event, ui: { value?: any }) { + handleSliderChanged(e: Event, ui: { value?: any }): void { const actual_value = this._validate_slide_value(ui.value); this.model.set('value', actual_value, {updated_view: this}); this.touch(); @@ -473,7 +473,7 @@ class IntSliderView extends BaseIntSliderView { export class IntTextModel extends IntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'IntTextModel', _view_name: 'IntTextView', @@ -485,7 +485,7 @@ class IntTextModel extends IntModel { export class BoundedIntTextModel extends BoundedIntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'BoundedIntTextModel', _view_name: 'IntTextView', @@ -498,7 +498,7 @@ class BoundedIntTextModel extends BoundedIntModel { export class IntTextView extends DescriptionView { - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -519,7 +519,7 @@ class IntTextView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { if (options === undefined || options.updated_view !== this) { const value: number = this.model.get('value'); @@ -543,7 +543,7 @@ class IntTextView extends DescriptionView { return super.update(); } - events() { + events(): {[e: string]: string} { return { 'keydown input' : 'handleKeyDown', 'keypress input' : 'handleKeypress', @@ -558,14 +558,14 @@ class IntTextView extends DescriptionView { * * Stop propagation so the event isn't sent to the application. */ - handleKeyDown(e: KeyboardEvent) { + handleKeyDown(e: KeyboardEvent): void { e.stopPropagation(); } /** * Handles key press */ - handleKeypress(e: KeyboardEvent) { + handleKeypress(e: KeyboardEvent): void { if (/[e,.\s]/.test(String.fromCharCode(e.keyCode))) { e.preventDefault(); } @@ -574,7 +574,7 @@ class IntTextView extends DescriptionView { /** * Handle key up */ - handleKeyUp(e: KeyboardEvent) { + handleKeyUp(e: KeyboardEvent): void { if (e.altKey || e.ctrlKey) { return; } @@ -599,7 +599,7 @@ class IntTextView extends DescriptionView { * Call the submit handler if continuous update is true and we are not * obviously incomplete. */ - handleChanging(e: Event) { + handleChanging(e: Event): void { const target = e.target as HTMLInputElement; const trimmed = target.value.trim(); @@ -616,7 +616,7 @@ class IntTextView extends DescriptionView { /** * Applies validated input. */ - handleChanged(e: Event) { + handleChanged(e: Event): void { const target = e.target as HTMLInputElement; let numericalValue = this._parse_value(target.value); @@ -654,7 +654,7 @@ class IntTextView extends DescriptionView { export class ProgressStyleModel extends DescriptionStyleModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'ProgressStyleModel', }; @@ -673,7 +673,7 @@ class ProgressStyleModel extends DescriptionStyleModel { export class IntProgressModel extends BoundedIntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'IntProgressModel', _view_name: 'ProgressView', @@ -687,13 +687,13 @@ class IntProgressModel extends BoundedIntModel { export class ProgressView extends DescriptionView { - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.listenTo(this.model, 'change:bar_style', this.update_bar_style); this.pWidget.addClass('jupyter-widgets'); } - render() { + render(): void{ super.render(); const orientation = this.model.get('orientation'); const className = orientation === 'horizontal' ? @@ -723,7 +723,7 @@ class ProgressView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { const value = this.model.get('value'); const max = this.model.get('max'); const min = this.model.get('min'); @@ -751,11 +751,11 @@ class ProgressView extends DescriptionView { return super.update(); } - update_bar_style() { + update_bar_style(): void { this.update_mapped_classes(ProgressView.class_map, 'bar_style', this.bar); } - set_bar_style() { + set_bar_style(): void { this.set_mapped_classes(ProgressView.class_map, 'bar_style', this.bar); } @@ -772,7 +772,7 @@ class ProgressView extends DescriptionView { export class PlayModel extends BoundedIntModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'PlayModel', _view_name: 'PlayView', @@ -784,11 +784,11 @@ class PlayModel extends BoundedIntModel { disabled: false, }); } - initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }) { + initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }): void { super.initialize(attributes, options); } - loop() { + loop(): void { if (this.get('_playing')) { const next_value = this.get('value') + this.get('step'); if (next_value <= this.get('max')) { @@ -806,22 +806,22 @@ class PlayModel extends BoundedIntModel { } } - schedule_next() { + schedule_next(): void { window.setTimeout(this.loop.bind(this), this.get('interval')); } - stop() { + stop(): void { this.set('_playing', false); this.set('value', this.get('min')); this.save_changes(); } - pause() { + pause(): void { this.set('_playing', false); this.save_changes(); } - play() { + play(): void { this.set('_playing', true); if (this.get('value') == this.get('max')) { // if the value is at the end, reset if first, and then schedule the next @@ -835,7 +835,7 @@ class PlayModel extends BoundedIntModel { } } - repeat() { + repeat(): void { this.set('_repeat', !this.get('_repeat')); this.save_changes(); } @@ -843,7 +843,7 @@ class PlayModel extends BoundedIntModel { export class PlayView extends DOMWidgetView { - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -890,7 +890,7 @@ class PlayView extends DOMWidgetView { this.update(); } - update() { + update(): void { const disabled = this.model.get('disabled'); this.playButton.disabled = disabled; this.pauseButton.disabled = disabled; @@ -899,7 +899,7 @@ class PlayView extends DOMWidgetView { this.update_playing(); } - update_playing() { + update_playing(): void { const playing = this.model.get('_playing'); const disabled = this.model.get('disabled'); if (playing) { @@ -915,7 +915,7 @@ class PlayView extends DOMWidgetView { } } - update_repeat() { + update_repeat(): void { const repeat = this.model.get('_repeat'); this.repeatButton.style.display = this.model.get('show_repeat') ? this.playButton.style.display : 'none'; if (repeat) { diff --git a/packages/controls/src/widget_link.ts b/packages/controls/src/widget_link.ts index 6a454a32dd..75dbef2dcd 100644 --- a/packages/controls/src/widget_link.ts +++ b/packages/controls/src/widget_link.ts @@ -20,7 +20,7 @@ class DirectionalLinkModel extends CoreWidgetModel { source: {deserialize: unpack_models} }; - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { target: undefined, source: undefined, @@ -28,13 +28,13 @@ class DirectionalLinkModel extends CoreWidgetModel { }); } - initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }) { + initialize(attributes: any, options: { model_id: string; comm: any; widget_manager: any }): void { super.initialize(attributes, options); this.on('change', this.updateBindings, this); this.updateBindings(); } - updateValue(sourceModel: WidgetModel, sourceAttr: string, targetModel: WidgetModel, targetAttr: string) { + updateValue(sourceModel: WidgetModel, sourceAttr: string, targetModel: WidgetModel, targetAttr: string): void { if (this._updating) { return; } @@ -49,7 +49,7 @@ class DirectionalLinkModel extends CoreWidgetModel { } } - updateBindings() { + updateBindings(): void { this.cleanup(); [this.sourceModel, this.sourceAttr] = this.get('source') || [null, null]; [this.targetModel, this.targetAttr] = this.get('target') || [null, null]; @@ -65,7 +65,7 @@ class DirectionalLinkModel extends CoreWidgetModel { } } - cleanup() { + cleanup(): void { // Stop listening to 'change' and 'destroy' events of the source and target if (this.sourceModel) { this.stopListening(this.sourceModel, 'change:' + this.sourceAttr, null); @@ -86,13 +86,13 @@ class DirectionalLinkModel extends CoreWidgetModel { export class LinkModel extends DirectionalLinkModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'LinkModel' }); } - updateBindings() { + updateBindings(): void { super.updateBindings(); if (this.targetModel) { this.listenTo(this.targetModel, 'change:' + this.targetAttr, () => { @@ -101,7 +101,7 @@ class LinkModel extends DirectionalLinkModel { } } - cleanup() { + cleanup(): void { super.cleanup(); if (this.targetModel) { this.stopListening(this.targetModel, 'change:' + this.targetAttr, null); diff --git a/packages/controls/src/widget_selection.ts b/packages/controls/src/widget_selection.ts index 65daaf29c4..e88b18ab94 100644 --- a/packages/controls/src/widget_selection.ts +++ b/packages/controls/src/widget_selection.ts @@ -19,7 +19,7 @@ import $ from 'jquery'; export class SelectionModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SelectionModel', index: '', @@ -31,7 +31,7 @@ class SelectionModel extends CoreDescriptionModel { export class DropdownModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'DropdownModel', _view_name: 'DropdownView', @@ -52,7 +52,7 @@ class DropdownView extends DescriptionView { /** * Public constructor. */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.listenTo(this.model, 'change:_options_labels', () => this._updateOptions()); } @@ -60,7 +60,7 @@ class DropdownView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -77,7 +77,7 @@ class DropdownView extends DescriptionView { /** * Update the contents of this view */ - update() { + update(): void { // Disable listbox if needed this.listbox.disabled = this.model.get('disabled'); @@ -87,7 +87,7 @@ class DropdownView extends DescriptionView { return super.update(); } - _updateOptions() { + _updateOptions(): void { this.listbox.textContent = ''; const items = this.model.get('_options_labels'); for (let i = 0; i < items.length; i++) { @@ -109,7 +109,7 @@ class DropdownView extends DescriptionView { /** * Handle when a new value is selected. */ - _handle_change() { + _handle_change(): void { this.model.set('index', this.listbox.selectedIndex === -1 ? null : this.listbox.selectedIndex); this.touch(); } @@ -121,7 +121,7 @@ class DropdownView extends DescriptionView { export class SelectModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SelectModel', _view_name: 'SelectView', @@ -135,7 +135,7 @@ class SelectView extends DescriptionView { /** * Public constructor. */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.listenTo(this.model, 'change:_options_labels', () => this._updateOptions()); this.listenTo(this.model, 'change:index', (model, value, options) => this.updateSelection(options)); @@ -146,7 +146,7 @@ class SelectView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -163,7 +163,7 @@ class SelectView extends DescriptionView { /** * Update the contents of this view */ - update() { + update(): void { super.update(); this.listbox.disabled = this.model.get('disabled'); let rows = this.model.get('rows'); @@ -173,7 +173,7 @@ class SelectView extends DescriptionView { this.listbox.setAttribute('size', rows); } - updateSelection(options: any = {}) { + updateSelection(options: any = {}): void { if (options.updated_view === this) { return; } @@ -181,7 +181,7 @@ class SelectView extends DescriptionView { this.listbox.selectedIndex = index === null ? -1 : index; } - _updateOptions() { + _updateOptions(): void { this.listbox.textContent = ''; const items = this.model.get('_options_labels'); for (let i = 0; i < items.length; i++) { @@ -203,7 +203,7 @@ class SelectView extends DescriptionView { /** * Handle when a new value is selected. */ - _handle_change() { + _handle_change(): void { this.model.set('index', this.listbox.selectedIndex, {updated_view: this}); this.touch(); } @@ -213,7 +213,7 @@ class SelectView extends DescriptionView { export class RadioButtonsModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'RadioButtonsModel', _view_name: 'RadioButtonsView', @@ -230,7 +230,7 @@ class RadioButtonsView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -250,7 +250,7 @@ class RadioButtonsView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { const items: string[] = this.model.get('_options_labels'); const radios = _.pluck( this.container.querySelectorAll('input[type="radio"]'), @@ -311,7 +311,7 @@ class RadioButtonsView extends DescriptionView { * yet we would like the full widget line up properly * when displayed side-by-side with other widgets. */ - adjustPadding(e: this) { + adjustPadding(e: this): void { // Vertical margins on a widget const elStyles = window.getComputedStyle(e.el); const margins = parseInt(elStyles.marginTop, 10) + parseInt(elStyles.marginBottom, 10); @@ -343,7 +343,7 @@ class RadioButtonsView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - _handle_click (event: Event) { + _handle_click (event: Event): void { const target = event.target as HTMLInputElement; this.model.set('index', parseInt(target.value), {updated_view: this}); this.touch(); @@ -354,7 +354,7 @@ class RadioButtonsView extends DescriptionView { export class ToggleButtonsStyleModel extends DescriptionStyleModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'ToggleButtonsStyleModel', }); @@ -377,7 +377,7 @@ class ToggleButtonsStyleModel extends DescriptionStyleModel { export class ToggleButtonsModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'ToggleButtonsModel', _view_name: 'ToggleButtonsView' @@ -388,7 +388,7 @@ export export class ToggleButtonsView extends DescriptionView { - initialize(options: any) { + initialize(options: any): void { this._css_state = {}; super.initialize(options); this.listenTo(this.model, 'change:button_style', this.update_button_style); @@ -397,7 +397,7 @@ class ToggleButtonsView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -417,7 +417,7 @@ class ToggleButtonsView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { const items: string[] = this.model.get('_options_labels'); const icons = this.model.get('icons') || []; const previous_icons = this.model.previous('icons') || []; @@ -490,7 +490,7 @@ class ToggleButtonsView extends DescriptionView { return super.update(options); } - update_style_traits(button?: HTMLButtonElement) { + update_style_traits(button?: HTMLButtonElement): void { for (const name in this._css_state as string[]) { if (Object.prototype.hasOwnProperty.call(this._css_state, 'name')) { if (name === 'margin') { @@ -510,14 +510,14 @@ class ToggleButtonsView extends DescriptionView { } } - update_button_style() { + update_button_style(): void { const buttons = this.buttongroup.querySelectorAll('button'); for (let i = 0; i < buttons.length; i++) { this.update_mapped_classes(ToggleButtonsView.classMap, 'button_style', buttons[i]); } } - set_button_style() { + set_button_style(): void { const buttons = this.buttongroup.querySelectorAll('button'); for (let i = 0; i < buttons.length; i++) { this.set_mapped_classes(ToggleButtonsView.classMap, 'button_style', buttons[i]); @@ -536,7 +536,7 @@ class ToggleButtonsView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - _handle_click (event: Event) { + _handle_click(event: Event): void { const target = event.target as HTMLButtonElement; this.model.set('index', parseInt(target.value, 10), {updated_view: this}); this.touch(); @@ -564,7 +564,7 @@ namespace ToggleButtonsView { export class SelectionSliderModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SelectionSliderModel', _view_name: 'SelectionSliderView', @@ -581,7 +581,7 @@ class SelectionSliderView extends DescriptionView { /** * Called when view is rendered. */ - render () { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -623,7 +623,7 @@ class SelectionSliderView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { if (options === undefined || options.updated_view !== this) { const labels = this.model.get('_options_labels'); const max = labels.length - 1; @@ -686,13 +686,13 @@ class SelectionSliderView extends DescriptionView { }; } - updateSelection() { + updateSelection(): void { const index = this.model.get('index'); this.$slider.slider('option', 'value', index); this.updateReadout(index); } - updateReadout(index: any) { + updateReadout(index: any): void { const value = this.model.get('_options_labels')[index]; this.readout.textContent = value; } @@ -700,7 +700,7 @@ class SelectionSliderView extends DescriptionView { /** * Called when the slider value is changing. */ - handleSliderChange(e: Event, ui: { value?: number; values?: number[] }) { + handleSliderChange(e: Event, ui: { value?: number; values?: number[] }): void { this.updateReadout(ui.value); // Only persist the value while sliding if the continuous_update @@ -716,7 +716,7 @@ class SelectionSliderView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleSliderChanged(e: Event, ui: { value?: number; values?: number[] }) { + handleSliderChanged(e: Event, ui: { value?: number; values?: number[] }): void { this.updateReadout(ui.value); this.model.set('index', ui.value, {updated_view: this}); this.touch(); @@ -729,7 +729,7 @@ class SelectionSliderView extends DescriptionView { export class MultipleSelectionModel extends SelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return { ...super.defaults(), _model_name: 'MultipleSelectionModel', }; @@ -739,7 +739,7 @@ class MultipleSelectionModel extends SelectionModel { export class SelectMultipleModel extends MultipleSelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SelectMultipleModel', _view_name: 'SelectMultipleView', @@ -753,7 +753,7 @@ class SelectMultipleView extends SelectView { /** * Public constructor. */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.listbox.multiple = true; } @@ -761,12 +761,12 @@ class SelectMultipleView extends SelectView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('widget-select-multiple'); } - updateSelection(options: any = {}) { + updateSelection(options: any = {}): void { if (options.updated_view === this) { return; } @@ -783,7 +783,7 @@ class SelectMultipleView extends SelectView { /** * Handle when a new value is selected. */ - _handle_change() { + _handle_change(): void { const index = Array.prototype.map .call(this.listbox.selectedOptions || [], function(option: HTMLOptionElement) { return option.index; @@ -795,7 +795,7 @@ class SelectMultipleView extends SelectView { export class SelectionRangeSliderModel extends MultipleSelectionModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'SelectionSliderModel', _view_name: 'SelectionSliderView', @@ -812,18 +812,18 @@ class SelectionRangeSliderView extends SelectionSliderView { /** * Called when view is rendered. */ - render () { + render(): void { super.render(); this.$slider.slider('option', 'range', true); } - updateSelection() { + updateSelection(): void { const index = this.model.get('index'); this.$slider.slider('option', 'values', index.slice()); this.updateReadout(index); } - updateReadout(index: number[]) { + updateReadout(index: number[]): void { const labels = this.model.get('_options_labels'); const minValue = labels[index[0]]; const maxValue = labels[index[1]]; @@ -833,7 +833,7 @@ class SelectionRangeSliderView extends SelectionSliderView { /** * Called when the slider value is changing. */ - handleSliderChange(e: Event, ui: { values: number[] }) { + handleSliderChange(e: Event, ui: { values: number[] }): void { this.updateReadout(ui.values); // Only persist the value while sliding if the continuous_update @@ -849,7 +849,7 @@ class SelectionRangeSliderView extends SelectionSliderView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleSliderChanged(e: Event, ui: { values: number[] }) { + handleSliderChanged(e: Event, ui: { values: number[] }): void { // The jqueryui documentation indicates ui.values doesn't exist on the slidestop event, // but it appears that it actually does: https://github.com/jquery/jquery-ui/blob/ae31f2b3b478975f70526bdf3299464b9afa8bb1/ui/widgets/slider.js#L313 this.updateReadout(ui.values); diff --git a/packages/controls/src/widget_selectioncontainer.ts b/packages/controls/src/widget_selectioncontainer.ts index f32bd7d32d..93966feff2 100644 --- a/packages/controls/src/widget_selectioncontainer.ts +++ b/packages/controls/src/widget_selectioncontainer.ts @@ -39,7 +39,7 @@ import $ from 'jquery'; export class SelectionContainerModel extends BoxModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'SelectionContainerModel', selected_index: 0, @@ -50,7 +50,7 @@ class SelectionContainerModel extends BoxModel { export class AccordionModel extends SelectionContainerModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'AccordionModel', _view_name: 'AccordionView' @@ -76,7 +76,7 @@ class JupyterPhosphorAccordionWidget extends Accordion { * Any custom phosphor widget used inside a Jupyter widget should override * the processMessage function like this. */ - processMessage(msg: Message) { + processMessage(msg: Message): void { super.processMessage(msg); this._view.processPhosphorMessage(msg); } @@ -86,7 +86,7 @@ class JupyterPhosphorAccordionWidget extends Accordion { * * This causes the view to be destroyed as well with 'remove' */ - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -104,12 +104,12 @@ class JupyterPhosphorAccordionWidget extends Accordion { export class AccordionView extends DOMWidgetView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new JupyterPhosphorAccordionWidget({ view: this }); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // Accordions don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -119,7 +119,7 @@ class AccordionView extends DOMWidgetView { this.$el = $(this.pWidget.node); } - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.children_views = new ViewList(this.add_child_view, this.remove_child_view, this); this.listenTo(this.model, 'change:children', () => this.updateChildren()); @@ -130,7 +130,7 @@ class AccordionView extends DOMWidgetView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); const accordion = this.pWidget; accordion.addClass('jupyter-widgets'); @@ -151,7 +151,7 @@ class AccordionView extends DOMWidgetView { /** * Update children */ - updateChildren() { + updateChildren(): void { // While we are updating, the index may not be valid, so deselect the // tabs before updating so we don't get spurious changes in the index, // which would then set off another sync cycle. @@ -165,7 +165,7 @@ class AccordionView extends DOMWidgetView { /** * Set header titles */ - update_titles() { + update_titles(): void { const collapsed = this.pWidget.collapseWidgets; const titles = this.model.get('_titles'); for (let i = 0; i < collapsed.length; i++) { @@ -178,14 +178,14 @@ class AccordionView extends DOMWidgetView { /** * Make the rendering and selected index consistent. */ - update_selected_index() { + update_selected_index(): void { this.pWidget.selection.index = this.model.get('selected_index'); } /** * Called when a child is removed from children list. */ - remove_child_view(view: DOMWidgetView) { + remove_child_view(view: DOMWidgetView): void { this.pWidget.removeWidget(view.pWidget); view.remove(); } @@ -193,7 +193,7 @@ class AccordionView extends DOMWidgetView { /** * Called when a child is added to children list. */ - add_child_view(model: WidgetModel, index: number) { + add_child_view(model: WidgetModel, index: number): Promise { // Placeholder widget to keep our position in the tab panel while we create the view. const accordion = this.pWidget; const placeholder = new Widget(); @@ -209,7 +209,7 @@ class AccordionView extends DOMWidgetView { }).catch(utils.reject('Could not add child view to box', true)); } - remove() { + remove(): void { this.children_views = null; super.remove(); } @@ -221,7 +221,7 @@ class AccordionView extends DOMWidgetView { export class TabModel extends SelectionContainerModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'TabModel', _view_name: 'TabView' @@ -255,7 +255,7 @@ class JupyterPhosphorTabPanelWidget extends TabPanel { * * This causes the view to be destroyed as well with 'remove' */ - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -275,14 +275,14 @@ class JupyterPhosphorTabPanelWidget extends TabPanel { export class TabView extends DOMWidgetView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new JupyterPhosphorTabPanelWidget({ view: this, }); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // TabViews don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -295,7 +295,7 @@ class TabView extends DOMWidgetView { /** * Public constructor. */ - initialize(parameters: any) { + initialize(parameters: any): void { super.initialize(parameters); this.childrenViews = new ViewList( this.addChildView, @@ -309,7 +309,7 @@ class TabView extends DOMWidgetView { /** * Called when view is rendered. */ - render() { + render(): void{ super.render(); const tabs = this.pWidget; tabs.addClass('jupyter-widgets'); @@ -334,7 +334,7 @@ class TabView extends DOMWidgetView { /** * Render tab views based on the current model's children. */ - updateTabs() { + updateTabs(): void { // While we are updating, the index may not be valid, so deselect the // tabs before updating so we don't get spurious changes in the index, // which would then set off another sync cycle. @@ -348,7 +348,7 @@ class TabView extends DOMWidgetView { /** * Called when a child is added to children list. */ - addChildView(model: WidgetModel, index: number) { + addChildView(model: WidgetModel, index: number): Promise { // Placeholder widget to keep our position in the tab panel while we create the view. const label = this.model.get('_titles')[index] || ''; const tabs = this.pWidget; @@ -376,7 +376,7 @@ class TabView extends DOMWidgetView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { // Update the selected index in the overall update method because it // should be run after the tabs have been updated. Otherwise the // selected index may not be a valid tab in the tab bar. @@ -387,7 +387,7 @@ class TabView extends DOMWidgetView { /** * Updates the tab page titles. */ - updateTitles() { + updateTitles(): void { const titles = this.model.get('_titles') || {}; each(this.pWidget.widgets, (widget, i) => { widget.title.label = titles[i] || ''; @@ -397,16 +397,16 @@ class TabView extends DOMWidgetView { /** * Updates the selected index. */ - updateSelectedIndex() { + updateSelectedIndex(): void { this.pWidget.currentIndex = this.model.get('selected_index'); } - remove() { + remove(): void { this.childrenViews = null; super.remove(); } - _onTabChanged(sender: TabBar, args: TabBar.ICurrentChangedArgs) { + _onTabChanged(sender: TabBar, args: TabBar.ICurrentChangedArgs): void { if (!this.updatingTabs) { const i = args.currentIndex; this.model.set('selected_index', i === -1 ? null : i); diff --git a/packages/controls/src/widget_string.ts b/packages/controls/src/widget_string.ts index 05bc980756..7d2201270b 100644 --- a/packages/controls/src/widget_string.ts +++ b/packages/controls/src/widget_string.ts @@ -24,7 +24,7 @@ const INVALID_VALUE_CLASS = 'jpwidgets-invalidComboValue'; export class StringModel extends CoreDescriptionModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { value: '', disabled: false, @@ -36,7 +36,7 @@ class StringModel extends CoreDescriptionModel { export class HTMLModel extends StringModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'HTMLView', _model_name: 'HTMLModel' @@ -49,7 +49,7 @@ class HTMLView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -66,7 +66,7 @@ class HTMLView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { this.content.innerHTML = this.model.get('value'); return super.update(); } @@ -77,7 +77,7 @@ class HTMLView extends DescriptionView { export class HTMLMathModel extends StringModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'HTMLMathView', _model_name: 'HTMLMathModel' @@ -90,7 +90,7 @@ class HTMLMathView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -104,7 +104,7 @@ class HTMLMathView extends DescriptionView { /** * Update the contents of this view */ - update() { + update(): void { this.content.innerHTML = this.model.get('value'); this.typeset(this.content); return super.update(); @@ -115,7 +115,7 @@ class HTMLMathView extends DescriptionView { export class LabelModel extends StringModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'LabelView', _model_name: 'LabelModel' @@ -128,7 +128,7 @@ class LabelView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-label'); @@ -141,7 +141,7 @@ class LabelView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update() { + update(): void { this.typeset(this.el, this.model.get('value')); return super.update(); } @@ -149,7 +149,7 @@ class LabelView extends DescriptionView { export class TextareaModel extends StringModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'TextareaView', _model_name: 'TextareaModel', @@ -164,7 +164,7 @@ class TextareaView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -185,7 +185,7 @@ class TextareaView extends DescriptionView { this.update_placeholder(); } - update_placeholder(value?: string) { + update_placeholder(value?: string): void { value = value || this.model.get('placeholder'); this.textbox.setAttribute('placeholder', value.toString()); } @@ -196,7 +196,7 @@ class TextareaView extends DescriptionView { * Called when the model is changed. The model may have been * changed by another view or by a state update from the back-end. */ - update(options?: any) { + update(options?: any): void { if (options === undefined || options.updated_view != this) { this.textbox.value = this.model.get('value'); let rows = this.model.get('rows'); @@ -209,7 +209,7 @@ class TextareaView extends DescriptionView { return super.update(); } - events() { + events(): {[e: string]: string} { return { 'keydown input': 'handleKeyDown', 'keypress input': 'handleKeypress', @@ -223,7 +223,7 @@ class TextareaView extends DescriptionView { * * Stop propagation so the event isn't sent to the application. */ - handleKeyDown(e: Event) { + handleKeyDown(e: Event): void { e.stopPropagation(); } @@ -232,14 +232,14 @@ class TextareaView extends DescriptionView { * * Stop propagation so the keypress isn't sent to the application. */ - handleKeypress(e: Event) { + handleKeypress(e: Event): void { e.stopPropagation(); } /** * Triggered on input change */ - handleChanging(e: Event) { + handleChanging(e: Event): void { if (this.model.get('continuous_update')) { this.handleChanged(e); } @@ -250,7 +250,7 @@ class TextareaView extends DescriptionView { * * @param e Event */ - handleChanged(e: Event) { + handleChanged(e: Event): void { const target = e.target as HTMLTextAreaElement; this.model.set('value', target.value, {updated_view: this}); this.touch(); @@ -260,7 +260,7 @@ class TextareaView extends DescriptionView { export class TextModel extends StringModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'TextView', _model_name: 'TextModel', @@ -274,7 +274,7 @@ class TextView extends DescriptionView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); this.el.classList.add('widget-inline-hbox'); @@ -296,11 +296,11 @@ class TextView extends DescriptionView { this.update_title(); } - update_placeholder(value?: string) { + update_placeholder(value?: string): void { this.textbox.setAttribute('placeholder', value || this.model.get('placeholder')); } - update_title() { + update_title(): void { const title = this.model.get('description_tooltip'); if (!title) { this.textbox.removeAttribute('title'); @@ -309,7 +309,7 @@ class TextView extends DescriptionView { } } - update(options?: any) { + update(options?: any): void { /** * Update the contents of this view * @@ -326,7 +326,7 @@ class TextView extends DescriptionView { return super.update(); } - events() { + events(): {[e: string]: string} { return { 'keydown input': 'handleKeyDown', 'keypress input': 'handleKeypress', @@ -340,14 +340,14 @@ class TextView extends DescriptionView { * * Stop propagation so the keypress isn't sent to the application. */ - handleKeyDown(e: Event) { + handleKeyDown(e: Event): void { e.stopPropagation(); } /** * Handles text submission */ - handleKeypress(e: KeyboardEvent) { + handleKeypress(e: KeyboardEvent): void { e.stopPropagation(); // The submit message is deprecated in widgets 7 if (e.keyCode === 13) { // Return key @@ -361,7 +361,7 @@ class TextView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleChanging(e: Event) { + handleChanging(e: Event): void { if (this.model.get('continuous_update')) { this.handleChanged(e); } @@ -373,7 +373,7 @@ class TextView extends DescriptionView { * Calling model.set will trigger all of the other views of the * model to update. */ - handleChanged(e: Event) { + handleChanged(e: Event): void { const target = e.target as HTMLInputElement; this.model.set('value', target.value, {updated_view: this}); this.touch(); @@ -386,7 +386,7 @@ class TextView extends DescriptionView { export class PasswordModel extends TextModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _view_name: 'PasswordView', _model_name: 'PasswordModel' @@ -405,7 +405,7 @@ class PasswordView extends TextView { */ export class ComboboxModel extends TextModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_name: 'ComboboxModel', _view_name: 'ComboboxView', @@ -421,7 +421,7 @@ class ComboboxModel extends TextModel { */ export class ComboboxView extends TextView { - render() { + render(): void { this.datalist = document.createElement('datalist'); this.datalist.id = uuid(); @@ -431,7 +431,7 @@ class ComboboxView extends TextView { this.el.appendChild(this.datalist); } - update(options?: any) { + update(options?: any): void { super.update(options); if (!this.datalist) { return; @@ -468,7 +468,7 @@ class ComboboxView extends TextView { return true; } - handleChanging(e: KeyboardEvent) { + handleChanging(e: KeyboardEvent): void { // Override to validate value const target = e.target as HTMLInputElement; const valid = this.isValid(target.value); @@ -478,7 +478,7 @@ class ComboboxView extends TextView { } } - handleChanged(e: KeyboardEvent) { + handleChanged(e: KeyboardEvent): void { // Override to validate value const target = e.target as HTMLInputElement; const valid = this.isValid(target.value); diff --git a/packages/controls/src/widget_upload.ts b/packages/controls/src/widget_upload.ts index 54f19212ff..fbcefd23cd 100644 --- a/packages/controls/src/widget_upload.ts +++ b/packages/controls/src/widget_upload.ts @@ -7,7 +7,7 @@ import { DOMWidgetView } from '@jupyter-widgets/base'; import * as _ from 'underscore'; export class FileUploadModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'FileUploadModel', _view_name: 'FileUploadView', @@ -29,7 +29,7 @@ export class FileUploadModel extends CoreDOMWidgetModel { static serializers = { ...CoreDOMWidgetModel.serializers, - data: { serialize: (buffers: any) => { return [...buffers]; } }, + data: { serialize: (buffers: any): any[] => { return [...buffers]; } }, }; } @@ -39,11 +39,11 @@ export class FileUploadView extends DOMWidgetView { fileInput: HTMLInputElement; fileReader: FileReader; - get tagName() { + get tagName(): string { return 'button'; } - render() { + render(): void { super.render(); this.el.classList.add('jupyter-widgets'); @@ -77,7 +77,7 @@ export class FileUploadView extends DOMWidgetView { lastModified: file.lastModified, }; this.fileReader = new FileReader(); - this.fileReader.onload = event => { + this.fileReader.onload = (event): any => { const buffer = (event as any).target.result; resolve({ buffer, @@ -85,7 +85,7 @@ export class FileUploadView extends DOMWidgetView { error: '', }); }; - this.fileReader.onerror = () => { + this.fileReader.onerror = (): any => { reject(); }; this.fileReader.onabort = this.fileReader.onerror; @@ -125,7 +125,7 @@ export class FileUploadView extends DOMWidgetView { this.update(); // Set defaults. } - update() { + update(): void { this.el.disabled = this.model.get('disabled'); this.el.setAttribute('title', this.model.get('tooltip')); @@ -151,11 +151,11 @@ export class FileUploadView extends DOMWidgetView { return super.update(); } - update_button_style() { + update_button_style(): void { this.update_mapped_classes(FileUploadView.class_map, 'button_style', this.el); } - set_button_style() { + set_button_style(): void { this.set_mapped_classes(FileUploadView.class_map, 'button_style', this.el); } diff --git a/packages/controls/src/widget_video.ts b/packages/controls/src/widget_video.ts index 403ce6121b..31da1d8d95 100644 --- a/packages/controls/src/widget_video.ts +++ b/packages/controls/src/widget_video.ts @@ -13,7 +13,7 @@ import * as _ from 'underscore'; export class VideoModel extends CoreDOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return _.extend(super.defaults(), { _model_name: 'VideoModel', _view_name: 'VideoView', @@ -29,7 +29,7 @@ class VideoModel extends CoreDOMWidgetModel { static serializers = { ...CoreDOMWidgetModel.serializers, - value: {serialize: (value: any) => { + value: {serialize: (value: any): DataView => { return new DataView(value.buffer.slice(0)); }} }; @@ -37,7 +37,7 @@ class VideoModel extends CoreDOMWidgetModel { export class VideoView extends DOMWidgetView { - render() { + render(): void { /** * Called when view is rendered. */ @@ -47,7 +47,7 @@ class VideoView extends DOMWidgetView { this.update(); // Set defaults. } - update() { + update(): void { /** * Update the contents of this view * @@ -95,7 +95,7 @@ class VideoView extends DOMWidgetView { return super.update(); } - remove() { + remove(): void { if (this.el.src) { URL.revokeObjectURL(this.el.src); } @@ -108,7 +108,7 @@ class VideoView extends DOMWidgetView { * #### Notes * This is a read-only attribute. */ - get tagName() { + get tagName(): string { // We can't make this an attribute with a default value // since it would be set after it is needed in the // constructor. diff --git a/packages/controls/test/src/dummy-manager.ts b/packages/controls/test/src/dummy-manager.ts index baa7cf9e57..897325a628 100644 --- a/packages/controls/test/src/dummy-manager.ts +++ b/packages/controls/test/src/dummy-manager.ts @@ -5,6 +5,7 @@ import * as widgets from '../../lib'; import * as services from '@jupyterlab/services'; import * as Backbone from 'backbone'; import * as base from '@jupyter-widgets/base'; +import { WidgetModel, WidgetView } from '@jupyter-widgets/base'; let numComms = 0; @@ -14,35 +15,35 @@ class MockComm { this.comm_id = `mock-comm-id-${numComms}`; numComms += 1; } - on_open(fn: Function) { + on_open(fn: Function): void { this._on_open = fn; } - on_close(fn: Function) { + on_close(fn: Function): void { this._on_close = fn; } - on_msg(fn: Function) { + on_msg(fn: Function): void { this._on_msg = fn; } - _process_msg(msg: any) { + _process_msg(msg: any): any { if (this._on_msg) { return this._on_msg(msg); } else { return Promise.resolve(); } } - open() { + open(): string { if (this._on_open) { this._on_open(); } return ''; } - close() { + close(): string { if (this._on_close) { this._on_close(); } return ''; } - send() { + send(): string { return ''; } comm_id: string; @@ -53,7 +54,7 @@ class MockComm { } class TestWidget extends base.WidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), _model_module: 'test-widgets', _model_name: 'TestWidget', @@ -67,11 +68,11 @@ class TestWidget extends base.WidgetModel { } class TestWidgetView extends base.WidgetView { - render() { + render(): void { this._rendered += 1; super.render(); } - remove() { + remove(): void { this._removed +=1; super.remove(); } @@ -88,7 +89,7 @@ class DummyManager extends base.ManagerBase { this.el = window.document.createElement('div'); } - display_view(msg: services.KernelMessage.IMessage, view: Backbone.View, options: any) { + display_view(msg: services.KernelMessage.IMessage, view: Backbone.View, options: any): Promise { // TODO: make this a spy // TODO: return an html element return Promise.resolve(view).then(view => { @@ -98,7 +99,7 @@ class DummyManager extends base.ManagerBase { }); } - protected loadClass(className: string, moduleName: string, moduleVersion: string): Promise { + protected loadClass(className: string, moduleName: string, moduleVersion: string): Promise { if (moduleName === '@jupyter-widgets/controls') { if ((widgets as any)[className]) { return Promise.resolve((widgets as any)[className]); @@ -116,11 +117,11 @@ class DummyManager extends base.ManagerBase { } } - _get_comm_info() { + _get_comm_info(): Promise<{}> { return Promise.resolve({}); } - _create_comm() { + _create_comm(): Promise { return Promise.resolve(new MockComm()); } diff --git a/packages/controls/test/src/phosphor/currentselection_test.ts b/packages/controls/test/src/phosphor/currentselection_test.ts index 0018a73815..cfe5a2b832 100644 --- a/packages/controls/test/src/phosphor/currentselection_test.ts +++ b/packages/controls/test/src/phosphor/currentselection_test.ts @@ -8,7 +8,7 @@ import { ArrayExt } from '@lumino/algorithm'; import { Selection } from '../../../lib/phosphor/currentselection'; -function getLastMessage(subscriber: { getCall: (arg0: number) => { args: [any, any] } }) { +function getLastMessage(subscriber: { getCall: (arg0: number) => { args: [any, any] } }): any { const [, message] = subscriber.getCall(0).args; return message; } diff --git a/packages/html-manager/src/htmlmanager.ts b/packages/html-manager/src/htmlmanager.ts index 02a163969d..0ba46b5d1d 100644 --- a/packages/html-manager/src/htmlmanager.ts +++ b/packages/html-manager/src/htmlmanager.ts @@ -9,6 +9,7 @@ import * as PhosphorWidget from '@lumino/widgets'; import { RenderMimeRegistry, standardRendererFactories } from '@jupyterlab/rendermime'; import { WidgetRenderer, WIDGET_MIMETYPE } from './output_renderers'; +import { WidgetModel, WidgetView } from '@jupyter-widgets/base'; export class HTMLManager extends base.ManagerBase { @@ -29,7 +30,7 @@ class HTMLManager extends base.ManagerBase { * Display the specified view. Element where the view is displayed * is specified in the `options.el` argument. */ - display_view(msg: any, view: any, options: { el: HTMLElement }) { + display_view(msg: any, view: any, options: { el: HTMLElement }): Promise { return Promise.resolve(view).then((view) => { PhosphorWidget.Widget.attach(view.pWidget, options.el); view.on('remove', () => { @@ -42,7 +43,7 @@ class HTMLManager extends base.ManagerBase { /** * Placeholder implementation for _get_comm_info. */ - _get_comm_info() { + _get_comm_info(): Promise<{}> { return Promise.resolve({}); } @@ -60,7 +61,7 @@ class HTMLManager extends base.ManagerBase { /** * Load a class and return a promise to the loaded object. */ - protected loadClass(className: string, moduleName: string, moduleVersion: string) { + protected loadClass(className: string, moduleName: string, moduleVersion: string): Promise { return new Promise((resolve, reject) => { if (moduleName === '@jupyter-widgets/base') { resolve(base); diff --git a/packages/html-manager/src/index.ts b/packages/html-manager/src/index.ts index f3c77a2d11..fb1978b2a8 100644 --- a/packages/html-manager/src/index.ts +++ b/packages/html-manager/src/index.ts @@ -8,7 +8,7 @@ export const version = (require('../package.json') as any).version; export -function generateEmbedScript(widgetState: any, imageDataUrl: string) { +function generateEmbedScript(widgetState: any, imageDataUrl: string): string { return ` `; } diff --git a/packages/html-manager/src/libembed-amd.ts b/packages/html-manager/src/libembed-amd.ts index f823e1d013..625aad107d 100644 --- a/packages/html-manager/src/libembed-amd.ts +++ b/packages/html-manager/src/libembed-amd.ts @@ -27,7 +27,7 @@ const requirePromise = function(pkg: string | string[]): Promise { }); } -function moduleNameToCDNUrl(moduleName: string, moduleVersion: string) { +function moduleNameToCDNUrl(moduleName: string, moduleVersion: string): string { let packageName = moduleName; let fileName = 'index'; // default filename // if a '/' is present, like 'foo/bar', packageName is changed to 'foo', and path to 'bar' @@ -59,7 +59,7 @@ function moduleNameToCDNUrl(moduleName: string, moduleVersion: string) { * The semver range is only used with the CDN. */ export -function requireLoader(moduleName: string, moduleVersion: string) { +function requireLoader(moduleName: string, moduleVersion: string): Promise { return requirePromise([`${moduleName}`]).catch((err) => { const failedId = err.requireModules && err.requireModules[0]; if (failedId) { @@ -86,9 +86,9 @@ function requireLoader(moduleName: string, moduleVersion: string) { * the widgets' models and views classes. (The default loader looks them up on unpkg.com) */ export -function renderWidgets(element = document.documentElement, loader: (moduleName: string, moduleVersion: string) => Promise = requireLoader) { +function renderWidgets(element = document.documentElement, loader: (moduleName: string, moduleVersion: string) => Promise = requireLoader): void { requirePromise(['@jupyter-widgets/html-manager']).then((htmlmanager) => { - const managerFactory = () => { + const managerFactory = (): any => { return new htmlmanager.HTMLManager({loader: loader}); } libembed.renderWidgets(managerFactory, element); diff --git a/packages/html-manager/src/libembed.ts b/packages/html-manager/src/libembed.ts index 39d7e8933f..3727d8515d 100644 --- a/packages/html-manager/src/libembed.ts +++ b/packages/html-manager/src/libembed.ts @@ -31,7 +31,7 @@ const view_validate = ajv.compile(widget_view_schema); * @param element (default document.documentElement) The document element in which to process for widget state. */ export -function renderWidgets(managerFactory: () => HTMLManager, element: HTMLElement = document.documentElement) { +function renderWidgets(managerFactory: () => HTMLManager, element: HTMLElement = document.documentElement): void { const tags = element.querySelectorAll('script[type="application/vnd.jupyter.widget-state+json"]'); for (let i=0; i!=tags.length; ++i) { renderManager(element, JSON.parse(tags[i].innerHTML), managerFactory); @@ -52,7 +52,7 @@ function renderWidgets(managerFactory: () => HTMLManager, element: HTMLElement = * Additionally, if the script tag has a prior img sibling with class * 'jupyter-widget', then that img tag is deleted. */ -function renderManager(element: HTMLElement, widgetState: any, managerFactory: () => HTMLManager) { +function renderManager(element: HTMLElement, widgetState: any, managerFactory: () => HTMLManager): void { const valid = model_validate(widgetState); if (!valid) { console.error('Model state has errors.', model_validate.errors); diff --git a/packages/html-manager/src/output.ts b/packages/html-manager/src/output.ts index f6c89faf7a..af0bd0c1be 100644 --- a/packages/html-manager/src/output.ts +++ b/packages/html-manager/src/output.ts @@ -14,14 +14,14 @@ import $ from 'jquery'; import '../css/output.css'; export class OutputModel extends outputBase.OutputModel { - defaults() { + defaults(): Backbone.ObjectHash { return { ...super.defaults(), msg_id: '' }; } - initialize(attributes: any, options: any) { + initialize(attributes: any, options: any): void { super.initialize(attributes, options); this._outputs = new OutputAreaModel({ values: attributes.outputs, @@ -31,7 +31,7 @@ export class OutputModel extends outputBase.OutputModel { }); } - get outputs() { + get outputs(): OutputAreaModel { return this._outputs; } @@ -40,12 +40,12 @@ export class OutputModel extends outputBase.OutputModel { } export class OutputView extends outputBase.OutputView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new Panel(); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // Boxes don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -54,7 +54,7 @@ export class OutputView extends outputBase.OutputView { this.$el = $(this.pWidget.node) } - render() { + render(): void { const manager = this.model.widget_manager; const rendermime = manager.renderMime; this._outputView = new OutputArea({ diff --git a/packages/html-manager/src/output_renderers.ts b/packages/html-manager/src/output_renderers.ts index fa9e41dd68..30e8d86ce7 100644 --- a/packages/html-manager/src/output_renderers.ts +++ b/packages/html-manager/src/output_renderers.ts @@ -17,7 +17,7 @@ export class WidgetRenderer extends Widget implements IRenderMime.IRenderer { this._manager = manager; } - async renderModel(model: IRenderMime.IMimeModel) { + async renderModel(model: IRenderMime.IMimeModel): Promise { const source: any = model.data[this.mimeType]; const modelPromise = this._manager.get_model(source.model_id); if (modelPromise) { diff --git a/packages/jupyterlab-manager/src/manager.ts b/packages/jupyterlab-manager/src/manager.ts index c3f5fbcb5c..d5bbf9c33c 100644 --- a/packages/jupyterlab-manager/src/manager.ts +++ b/packages/jupyterlab-manager/src/manager.ts @@ -6,7 +6,7 @@ import * as Backbone from 'backbone'; import { ManagerBase, shims, IClassicComm, IWidgetRegistryData, ExportMap, - ExportData, WidgetModel, WidgetView, put_buffers, serialize_state, IStateOptions + ExportData, WidgetModel, WidgetView, put_buffers, serialize_state, IStateOptions, ICallbacks } from '@jupyter-widgets/base'; import { @@ -14,7 +14,7 @@ import { } from '@lumino/disposable'; import { - PromiseDelegate + PromiseDelegate, ReadonlyPartialJSONValue } from '@lumino/coreutils'; import { @@ -84,11 +84,11 @@ class BackboneViewWrapper extends Widget { this.node.appendChild(view.el); } - onAfterAttach(msg: any) { + onAfterAttach(msg: any): void { this._view.trigger('displayed'); } - dispose() { + dispose(): void { this._view = null; super.dispose(); } @@ -108,7 +108,7 @@ class WidgetManager extends ManagerBase implements IDisposable { this._rendermime = rendermime; // Set _handleCommOpen so `this` is captured. - this._handleCommOpen = async (comm, msg) => { + this._handleCommOpen = async (comm, msg): Promise => { const oldComm = new shims.services.Comm(comm); await this.handle_comm_open(oldComm, msg); }; @@ -141,7 +141,7 @@ class WidgetManager extends ManagerBase implements IDisposable { /** * Save the widget state to the context model. */ - private _saveState() { + private _saveState(): void { const state = this.get_state_sync({ drop_defaults: true }); this._context.model.metadata.set('widgets', { 'application/vnd.jupyter.widget-state+json' : state @@ -151,10 +151,10 @@ class WidgetManager extends ManagerBase implements IDisposable { /** * Default callback handler to emit unhandled kernel messages. */ - callbacks(view?: WidgetView) { + callbacks(view?: WidgetView): ICallbacks { return { iopub: { - output: (msg: KernelMessage.IIOPubMessage) => { + output: (msg: KernelMessage.IIOPubMessage): void => { this._onUnhandledIOPubMessage.emit(msg); } } @@ -164,7 +164,7 @@ class WidgetManager extends ManagerBase implements IDisposable { /** * Register a new kernel */ - _handleKernelChanged({oldValue, newValue}: Session.ISessionConnection.IKernelChangedArgs) { + _handleKernelChanged({oldValue, newValue}: Session.ISessionConnection.IKernelChangedArgs): void { if (oldValue) { oldValue.removeCommTarget(this.comm_target_name, this._handleCommOpen); } @@ -174,7 +174,7 @@ class WidgetManager extends ManagerBase implements IDisposable { } } - _handleKernelConnectionStatusChange(status: Kernel.ConnectionStatus) { + _handleKernelConnectionStatusChange(status: Kernel.ConnectionStatus): void { if (status === 'connected') { // Only restore if our initial restore at construction is finished if (this._initialRestoredStatus) { @@ -185,7 +185,7 @@ class WidgetManager extends ManagerBase implements IDisposable { } } - _handleKernelStatusChange(status: Kernel.Status) { + _handleKernelStatusChange(status: Kernel.Status): void { if (status === 'restarting') { this.disconnect(); } @@ -210,7 +210,7 @@ class WidgetManager extends ManagerBase implements IDisposable { * Disconnect the widget manager from the kernel, setting each model's comm * as dead. */ - disconnect() { + disconnect(): void { super.disconnect(); this._restoredStatus = false; } @@ -406,11 +406,11 @@ class WidgetManager extends ManagerBase implements IDisposable { return cls; } - get context() { + get context(): DocumentRegistry.IContext { return this._context; } - get rendermime() { + get rendermime(): IRenderMimeRegistry { return this._rendermime; } @@ -439,7 +439,7 @@ class WidgetManager extends ManagerBase implements IDisposable { return this._onUnhandledIOPubMessage; } - register(data: IWidgetRegistryData) { + register(data: IWidgetRegistryData): void { this._registry.set(data.name, data.version, data.exports); } @@ -492,9 +492,9 @@ class WidgetManager extends ManagerBase implements IDisposable { * the @jupyter-widgets/schema package. * * @param options - The options for what state to return. - * @returns Promise for a state dictionary + * @returns A state dictionary */ - get_state_sync(options: IStateOptions = {}) { + get_state_sync(options: IStateOptions = {}): ReadonlyPartialJSONValue { const models = []; for (const model of this._modelsSync.values()) { if (model.comm_live) { @@ -509,7 +509,7 @@ class WidgetManager extends ManagerBase implements IDisposable { * * TODO: perhaps should also set dirty when any model changes any data */ - setDirty() { + setDirty(): void { if (this._settings.saveState) { this._context.model.dirty = true; } diff --git a/packages/jupyterlab-manager/src/output.ts b/packages/jupyterlab-manager/src/output.ts index 5ab3fdb3b5..dcb037a767 100644 --- a/packages/jupyterlab-manager/src/output.ts +++ b/packages/jupyterlab-manager/src/output.ts @@ -36,18 +36,18 @@ const OUTPUT_WIDGET_VERSION = outputBase.OUTPUT_WIDGET_VERSION; export class OutputModel extends outputBase.OutputModel { - defaults() { + defaults(): Backbone.ObjectHash { return {...super.defaults(), msg_id: '', outputs: [] }; } - initialize(attributes: any, options: any) { + initialize(attributes: any, options: any): void { super.initialize(attributes, options); // The output area model is trusted since widgets are only rendered in trusted contexts. this._outputs = new OutputAreaModel({trusted: true}); - this._msgHook = (msg) => { + this._msgHook = (msg): boolean => { this.add(msg); return false; }; @@ -63,7 +63,7 @@ class OutputModel extends outputBase.OutputModel { /** * Register a new kernel */ - _handleKernelChanged({oldValue}: Session.ISessionConnection.IKernelChangedArgs) { + _handleKernelChanged({oldValue}: Session.ISessionConnection.IKernelChangedArgs): void { const msgId = this.get('msg_id'); if (msgId && oldValue) { oldValue.removeMessageHook(msgId, this._msgHook); @@ -74,7 +74,7 @@ class OutputModel extends outputBase.OutputModel { /** * Reset the message id. */ - reset_msg_id() { + reset_msg_id(): void { const kernel = this.widget_manager.context.sessionContext.session.kernel; const msgId = this.get('msg_id'); const oldMsgId = this.previous('msg_id'); @@ -90,7 +90,7 @@ class OutputModel extends outputBase.OutputModel { } } - add(msg: KernelMessage.IIOPubMessage) { + add(msg: KernelMessage.IIOPubMessage): void { const msgType = msg.header.msg_type; switch (msgType) { case 'execute_result': @@ -112,15 +112,15 @@ class OutputModel extends outputBase.OutputModel { this.save_changes(); } - clear_output(wait = false) { + clear_output(wait = false): void { this._outputs.clear(wait); } - get outputs() { + get outputs(): OutputAreaModel { return this._outputs; } - setOutputs(model?: any, value?: any, options?: any) { + setOutputs(model?: any, value?: any, options?: any): void { if (!(options && options.newMessage)) { // fromJSON does not clear the existing output this.clear_output(); @@ -150,7 +150,7 @@ class JupyterPhosphorPanelWidget extends Panel { * Any custom phosphor widget used inside a Jupyter widget should override * the processMessage function like this. */ - processMessage(msg: Message) { + processMessage(msg: Message): void { super.processMessage(msg); this._view.processPhosphorMessage(msg); } @@ -160,7 +160,7 @@ class JupyterPhosphorPanelWidget extends Panel { * * This causes the view to be destroyed as well with 'remove' */ - dispose() { + dispose(): void { if (this.isDisposed) { return; } @@ -177,12 +177,12 @@ class JupyterPhosphorPanelWidget extends Panel { export class OutputView extends outputBase.OutputView { - _createElement(tagName: string) { + _createElement(tagName: string): HTMLElement { this.pWidget = new JupyterPhosphorPanelWidget({ view: this }); return this.pWidget.node; } - _setElement(el: HTMLElement) { + _setElement(el: HTMLElement): void { if (this.el || el !== this.pWidget.node) { // Boxes don't allow setting the element beyond the initial creation. throw new Error('Cannot reset the DOM element.'); @@ -195,7 +195,7 @@ class OutputView extends outputBase.OutputView { /** * Called when view is rendered. */ - render() { + render(): void { super.render(); this._outputView = new OutputArea({ rendermime: this.model.widget_manager.rendermime, @@ -213,7 +213,7 @@ class OutputView extends outputBase.OutputView { this.update(); // Set defaults. } - remove() { + remove(): any { this._outputView.dispose(); return super.remove(); } diff --git a/packages/jupyterlab-manager/src/plugin.ts b/packages/jupyterlab-manager/src/plugin.ts index 6870b9cfae..52e08b3112 100644 --- a/packages/jupyterlab-manager/src/plugin.ts +++ b/packages/jupyterlab-manager/src/plugin.ts @@ -79,7 +79,7 @@ const SETTINGS: WidgetManager.Settings = { saveState: false }; /** * Iterate through all widget renderers in a notebook. */ -function* widgetRenderers(nb: Notebook) { +function* widgetRenderers(nb: Notebook): Generator { for (const cell of nb.widgets) { if (cell.model.type === 'code') { for (const codecell of (cell as CodeCell).outputArea.widgets) { @@ -96,7 +96,7 @@ function* widgetRenderers(nb: Notebook) { /** * Iterate through all matching linked output views */ -function* outputViews(app: JupyterFrontEnd, path: string) { +function* outputViews(app: JupyterFrontEnd, path: string): Generator { const linkedViews = filter( app.shell.widgets(), w => w.id.startsWith('LinkedOutputView-') && (w as any).path === path @@ -112,7 +112,7 @@ function* outputViews(app: JupyterFrontEnd, path: string) { } } -function* chain(...args: IterableIterator[]) { +function* chain(...args: IterableIterator[]): Generator { for (const it of args) { yield* it; } @@ -122,7 +122,7 @@ export function registerWidgetManager( context: DocumentRegistry.IContext, rendermime: IRenderMimeRegistry, renderers: IterableIterator -) { +): DisposableDelegate { let wManager = Private.widgetManagerProperty.get(context); if (!wManager) { wManager = new WidgetManager(context, rendermime, SETTINGS); @@ -167,7 +167,7 @@ const plugin: JupyterFrontEndPlugin = { export default plugin; -function updateSettings(settings: ISettingRegistry.ISettings) { +function updateSettings(settings: ISettingRegistry.ISettings): void { SETTINGS.saveState = settings.get('saveState').composite as boolean; } @@ -184,7 +184,7 @@ function activateWidgetExtension( const {commands} = app; - const bindUnhandledIOPubMessageSignal = (nb: NotebookPanel) => { + const bindUnhandledIOPubMessageSignal = (nb: NotebookPanel): void => { if (!loggerRegistry) { return; } @@ -327,6 +327,6 @@ namespace Private { WidgetManager | undefined >({ name: 'widgetManager', - create: () => undefined + create: (owner: DocumentRegistry.Context): WidgetManager => undefined }); } diff --git a/packages/jupyterlab-manager/src/renderer.ts b/packages/jupyterlab-manager/src/renderer.ts index 001e8aaa0d..2f8ec72182 100644 --- a/packages/jupyterlab-manager/src/renderer.ts +++ b/packages/jupyterlab-manager/src/renderer.ts @@ -43,7 +43,7 @@ class WidgetRenderer extends Panel implements IRenderMime.IRenderer, IDisposable this._manager.resolve(value); } - async renderModel(model: IRenderMime.IMimeModel) { + async renderModel(model: IRenderMime.IMimeModel): Promise { const source: any = model.data[this.mimeType]; // Let's be optimistic, and hope the widget state will come later. @@ -121,7 +121,7 @@ class WidgetRenderer extends Panel implements IRenderMime.IRenderer, IDisposable this._manager = null; } - private _rerender() { + private _rerender(): void { if (this._rerenderMimeModel) { // Clear the error message this.node.textContent = ''; diff --git a/packages/jupyterlab-manager/src/semvercache.ts b/packages/jupyterlab-manager/src/semvercache.ts index 9a07a66b1f..ac5b5b58e1 100644 --- a/packages/jupyterlab-manager/src/semvercache.ts +++ b/packages/jupyterlab-manager/src/semvercache.ts @@ -11,7 +11,7 @@ import { */ export class SemVerCache { - set(key: string, version: string, object: T) { + set(key: string, version: string, object: T): void { if (!(key in this._cache)) { this._cache[key] = Object.create(null); } diff --git a/packages/output/src/output.ts b/packages/output/src/output.ts index a4fddeb782..c5d9cfa57c 100644 --- a/packages/output/src/output.ts +++ b/packages/output/src/output.ts @@ -7,7 +7,7 @@ export const OUTPUT_WIDGET_VERSION = '1.0.0'; export class OutputModel extends DOMWidgetModel { - defaults() { + defaults(): Backbone.ObjectHash { return { ...super.defaults(), _model_name: 'OutputModel',