Skip to content

Commit

Permalink
chore: type general utils (#2381)
Browse files Browse the repository at this point in the history
* type camera

* type reducer store

* type actionhelpers

* type catchErrorsWrap callsite

* missed camera member var

* type nameCreators

* type makeContinousDimensionName callsite

* type promise limit

* type quantile

* type range

* introduce TypedArray + NumericArray

* type range

* cleanup test

* fix call sites

* type plimit call site

* finish typing camera

* use our TypedArray

* type scientific and sigFig utils and callsites

* simple typings

* type catLabelSort

* type callsite

* type

* callsites

* type camera methods

* swap back to strings, set defaults accordingly

* partially type centroid

* explicit tuple and undefined check

* fix references to this

* call constructor with new and casting

* Revert "introduce TypedArray + NumericArray"

This reverts commit cf21538.

* explicit tuple

* generics and import fixes

* add unsigned 8 clamped arrray

* back to literals

* use arraytypes

* fix return state

* type more actions

* Update client/src/util/actionHelpers.ts

Co-authored-by: Timmy Huang <[email protected]>

* properly type dispatch

* properly type thunk

* use new dispatch

* remove nullish coallescer

* use AppDispatch

* generic jsonrequest

* use dispatch again

* lint

Co-authored-by: Timmy Huang <[email protected]>
  • Loading branch information
seve and tihuan authored Aug 18, 2021
1 parent 45cecad commit 08b03ac
Show file tree
Hide file tree
Showing 31 changed files with 425 additions and 366 deletions.
13 changes: 7 additions & 6 deletions client/__tests__/e2e/cellxgeneActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,12 @@ export async function getAllCategoriesAndCounts(category: any) {
.querySelector("[data-testclass='categorical-value']")
.getAttribute("aria-label");

const count = (row.querySelector(
"[data-testclass='categorical-value-count']"
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
) as any).innerText;
const count = (
row.querySelector(
"[data-testclass='categorical-value-count']"
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
) as any
).innerText;

return [cat, count];
})
Expand Down Expand Up @@ -194,8 +196,7 @@ export async function expandCategory(category: any) {
if (notExpanded) await clickOn(`${category}:category-expand`);
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types --- FIXME: disabled temporarily on migrate to TS.
export async function clip(min = 0, max = 100) {
export async function clip(min = "0", max = "100"): Promise<void> {
await clickOn("visualization-settings");
await clearInputAndTypeInto("clip-min-input", min);
await clearInputAndTypeInto("clip-max-input", max);
Expand Down
1 change: 0 additions & 1 deletion client/__tests__/e2e/e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,6 @@ describe("clipping", () => {
test("clip continuous", async () => {
await goToPage(appUrlBase);

// @ts-expect-error ts-migrate(2345) FIXME: Argument of type 'string' is not assignable to par... Remove this comment to see the full error message
await clip(data.clip.min, data.clip.max);
const histBrushableAreaId = `histogram-${data.clip.metadata}-plot-brushable-area`;
const coords = await calcDragCoordinates(
Expand Down
4 changes: 1 addition & 3 deletions client/__tests__/util/promiseLimit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ describe("PromiseLimit", () => {
running -= 1;
};

// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 1.
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
await Promise.all(range(10).map((i: any) => plimit.add(() => callback(i))));
await Promise.all(range(10).map(() => plimit.add(() => callback())));

expect(maxRunning).toEqual(2);
});
Expand Down
6 changes: 0 additions & 6 deletions client/__tests__/util/range.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,14 @@ describe("range", () => {
});

test("range(stop)", () => {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 1.
expect(range(3)).toMatchObject([0, 1, 2]);
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 1.
expect(range(0)).toMatchObject([]);
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 1.
expect(range(1)).toMatchObject([0]);
});

test("range(start,stop)", () => {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 2.
expect(range(0, 0)).toMatchObject([]);
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 2.
expect(range(0, 2)).toMatchObject([0, 1]);
// @ts-expect-error ts-migrate(2554) FIXME: Expected 3 arguments, but got 2.
expect(range(4, 8)).toMatchObject([4, 5, 6, 7]);
});

Expand Down
47 changes: 23 additions & 24 deletions client/src/actions/embedding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
action creators related to embeddings choice
*/

import { Action, ActionCreator } from "redux";
import { ThunkAction } from "redux-thunk";
import { AnnoMatrixObsCrossfilter } from "../annoMatrix";
import type { AppDispatch, RootState } from "../reducers";
import { _setEmbeddingSubset } from "../util/stateManager/viewStackHelpers";

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types --- FIXME: disabled temporarily on migrate to TS.
Expand All @@ -29,30 +32,26 @@ export async function _switchEmbedding(
return [annoMatrix, obsCrossfilter];
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
export const layoutChoiceAction = (newLayoutChoice: any) => async (
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
dispatch: any,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
getState: any
) => {
/*
export const layoutChoiceAction: ActionCreator<
ThunkAction<Promise<void>, RootState, never, Action<"set layout choice">>
> =
(newLayoutChoice: string) =>
async (dispatch: AppDispatch, getState: () => RootState): Promise<void> => {
/*
On layout choice, make sure we have selected all on the previous layout, AND the new
layout.
*/
const {
annoMatrix: prevAnnoMatrix,
obsCrossfilter: prevCrossfilter,
} = getState();
const [annoMatrix, obsCrossfilter] = await _switchEmbedding(
prevAnnoMatrix,
prevCrossfilter,
newLayoutChoice
);
dispatch({
type: "set layout choice",
layoutChoice: newLayoutChoice,
obsCrossfilter,
annoMatrix,
});
};
const { annoMatrix: prevAnnoMatrix, obsCrossfilter: prevCrossfilter } =
getState();
const [annoMatrix, obsCrossfilter] = await _switchEmbedding(
prevAnnoMatrix,
prevCrossfilter,
newLayoutChoice
);
dispatch({
type: "set layout choice",
layoutChoice: newLayoutChoice,
obsCrossfilter,
annoMatrix,
});
};
198 changes: 101 additions & 97 deletions client/src/actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Config } from "../globals";
import * as globals from "../globals";
import { AnnoMatrixLoader, AnnoMatrixObsCrossfilter } from "../annoMatrix";
import {
Expand All @@ -11,6 +12,9 @@ import * as annoActions from "./annotation";
import * as viewActions from "./viewStack";
import * as embActions from "./embedding";
import * as genesetActions from "./geneset";
import { AppDispatch, RootState } from "../reducers";
import { EmbeddingSchema, Schema } from "../common/types/schema";
import { UserInfoPayload } from "../reducers/userInfo";

// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
function setGlobalConfig(config: any) {
Expand All @@ -36,35 +40,34 @@ async function userColorsFetchAndLoad(dispatch: any) {
);
}

async function schemaFetch() {
return fetchJson("schema");
async function schemaFetch(): Promise<{ schema: Schema }> {
return fetchJson<{ schema: Schema }>("schema");
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
async function configFetch(dispatch: any) {
return fetchJson("config").then((response) => {
const config = { ...globals.configDefaults, ...response.config };
async function configFetch(dispatch: AppDispatch): Promise<Config> {
const response = await fetchJson<{ config: globals.Config }>("config");
const config = { ...globals.configDefaults, ...response.config };

setGlobalConfig(config);
setGlobalConfig(config);

dispatch({
type: "configuration load complete",
config,
});
return config;
dispatch({
type: "configuration load complete",
config,
});
return config;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
async function userInfoFetch(dispatch: any) {
return fetchJson("userinfo").then((response) => {
const { userinfo: userInfo } = response || {};
dispatch({
type: "userInfo load complete",
userInfo,
});
return userInfo;
});
async function userInfoFetch(dispatch: AppDispatch): Promise<UserInfoPayload> {
return fetchJson<{ userinfo: UserInfoPayload }>("userinfo").then(
(response) => {
const { userinfo: userInfo } = response || {};
dispatch({
type: "userInfo load complete",
userInfo,
});
return userInfo;
}
);
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
Expand Down Expand Up @@ -104,17 +107,17 @@ function prefetchEmbeddings(annoMatrix: any) {
/*
Application bootstrap
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types --- FIXME: disabled temporarily on migrate to TS.
const doInitialDataLoad = () =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
catchErrorsWrap(async (dispatch: any) => {
const doInitialDataLoad = (): ((
dispatch: AppDispatch,
getState: () => RootState
) => void) =>
catchErrorsWrap(async (dispatch: AppDispatch) => {
dispatch({ type: "initial data load start" });

try {
const [config, schema] = await Promise.all([
configFetch(dispatch),
// @ts-expect-error ts-migrate(2554) FIXME: Expected 0 arguments, but got 1.
schemaFetch(dispatch),
schemaFetch(),
userColorsFetchAndLoad(dispatch),
userInfoFetch(dispatch),
]);
Expand All @@ -137,8 +140,7 @@ const doInitialDataLoad = () =>
const layoutSchema = schema?.schema?.layout?.obs ?? [];
if (
defaultEmbedding &&
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
layoutSchema.some((s: any) => s.name === defaultEmbedding)
layoutSchema.some((s: EmbeddingSchema) => s.name === defaultEmbedding)
) {
dispatch(embActions.layoutChoiceAction(defaultEmbedding));
}
Expand Down Expand Up @@ -188,87 +190,89 @@ const dispatchDiffExpErrors = (dispatch: any, response: any) => {
}
};

const requestDifferentialExpression = (
const requestDifferentialExpression =
(
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
set1: any,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
set2: any,
num_genes = 50
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
) =>
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
set1: any,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
set2: any,
num_genes = 50
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any -- - FIXME: disabled temporarily on migrate to TS.
) => async (dispatch: any, getState: any) => {
dispatch({ type: "request differential expression started" });
try {
/*
async (dispatch: any, getState: any) => {
dispatch({ type: "request differential expression started" });
try {
/*
Steps:
1. get the most differentially expressed genes
2. get expression data for each
*/
const { annoMatrix } = getState();
const varIndexName = annoMatrix.schema.annotations.var.index;
const { annoMatrix } = getState();
const varIndexName = annoMatrix.schema.annotations.var.index;

// Legal values are null, Array or TypedArray. Null is initial state.
if (!set1) set1 = [];
if (!set2) set2 = [];

// Legal values are null, Array or TypedArray. Null is initial state.
if (!set1) set1 = [];
if (!set2) set2 = [];
// These lines ensure that we convert any TypedArray to an Array.
// This is necessary because JSON.stringify() does some very strange
// things with TypedArrays (they are marshalled to JSON objects, rather
// than being marshalled as a JSON array).
set1 = Array.isArray(set1) ? set1 : Array.from(set1);
set2 = Array.isArray(set2) ? set2 : Array.from(set2);

// These lines ensure that we convert any TypedArray to an Array.
// This is necessary because JSON.stringify() does some very strange
// things with TypedArrays (they are marshalled to JSON objects, rather
// than being marshalled as a JSON array).
set1 = Array.isArray(set1) ? set1 : Array.from(set1);
set2 = Array.isArray(set2) ? set2 : Array.from(set2);
const res = await fetch(
`${globals.API.prefix}${globals.API.version}diffexp/obs`,
{
method: "POST",
headers: new Headers({
Accept: "application/json",
"Content-Type": "application/json",
}),
body: JSON.stringify({
mode: "topN",
count: num_genes,
set1: { filter: { obs: { index: set1 } } },
set2: { filter: { obs: { index: set2 } } },
}),
credentials: "include",
}
);

const res = await fetch(
`${globals.API.prefix}${globals.API.version}diffexp/obs`,
{
method: "POST",
headers: new Headers({
Accept: "application/json",
"Content-Type": "application/json",
}),
body: JSON.stringify({
mode: "topN",
count: num_genes,
set1: { filter: { obs: { index: set1 } } },
set2: { filter: { obs: { index: set2 } } },
}),
credentials: "include",
if (!res.ok || res.headers.get("Content-Type") !== "application/json") {
return dispatchDiffExpErrors(dispatch, res);
}
);

if (!res.ok || res.headers.get("Content-Type") !== "application/json") {
return dispatchDiffExpErrors(dispatch, res);
}
const response = await res.json();
const varIndex = await annoMatrix.fetch("var", varIndexName);
const diffexpLists = { negative: [], positive: [] };
for (const polarity of Object.keys(diffexpLists)) {
// @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
diffexpLists[polarity] = response[polarity].map((v: any) => [
varIndex.at(v[0], varIndexName),
...v.slice(1),
]);
}

const response = await res.json();
const varIndex = await annoMatrix.fetch("var", varIndexName);
const diffexpLists = { negative: [], positive: [] };
for (const polarity of Object.keys(diffexpLists)) {
// @ts-expect-error ts-migrate(7053) FIXME: Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
diffexpLists[polarity] = response[polarity].map((v: any) => [
varIndex.at(v[0], varIndexName),
...v.slice(1),
]);
/* then send the success case action through */
return dispatch({
type: "request differential expression success",
data: diffexpLists,
});
} catch (error) {
return dispatch({
type: "request differential expression error",
error,
});
}
};

/* then send the success case action through */
return dispatch({
type: "request differential expression success",
data: diffexpLists,
});
} catch (error) {
return dispatch({
type: "request differential expression error",
error,
});
}
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any --- FIXME: disabled temporarily on migrate to TS.
function fetchJson(pathAndQuery: any) {
return doJsonRequest(
function fetchJson<T>(pathAndQuery: string): Promise<T> {
return doJsonRequest<T>(
`${globals.API.prefix}${globals.API.version}${pathAndQuery}`
);
) as Promise<T>;
}

export default {
Expand Down
Loading

0 comments on commit 08b03ac

Please sign in to comment.