Skip to content

Commit

Permalink
frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
Miodec committed Sep 11, 2024
1 parent a0d4471 commit d25b0d2
Show file tree
Hide file tree
Showing 25 changed files with 89 additions and 47 deletions.
2 changes: 1 addition & 1 deletion frontend/src/ts/ape/adapters/ts-rest-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function buildApi(timeout: number): (args: ApiFetcherArgs) => Promise<{
: AbortSignal.timeout(timeout),
});

const body = await response.json();
const body = (await response.json()) as object;
if (response.status >= 400) {
console.error(`${request.method} ${request.path} failed`, {
status: response.status,
Expand Down
12 changes: 7 additions & 5 deletions frontend/src/ts/controllers/analytics-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import { createErrorMessage } from "../utils/misc";

let analytics: AnalyticsType;

type AcceptedCookies = {
security: boolean;
analytics: boolean;
};

export async function log(
eventName: string,
params?: Record<string, string>
Expand All @@ -21,12 +26,9 @@ export async function log(
}

const lsString = localStorage.getItem("acceptedCookies");
let acceptedCookies: {
security: boolean;
analytics: boolean;
} | null;
let acceptedCookies;
if (lsString !== undefined && lsString !== null && lsString !== "") {
acceptedCookies = JSON.parse(lsString);
acceptedCookies = JSON.parse(lsString) as AcceptedCookies;
} else {
acceptedCookies = null;
}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/ts/controllers/captcha-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ export function render(
}

//@ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const widgetId = grecaptcha.render(element, {
sitekey: siteKey,
callback,
});

captchas[id] = widgetId;
captchas[id] = widgetId as number;
}

export function reset(id: string): void {
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/ts/controllers/pw-ad-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ export function init(): void {
headOfDocument.appendChild(rampScript);

window._pwGA4PageviewId = "".concat(Date.now());
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/no-unsafe-assignment
window.dataLayer = window.dataLayer || [];
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
window.gtag =
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
window.gtag ||
Expand All @@ -156,6 +157,7 @@ export function init(): void {
gtag("config", "G-KETCPNHRJF", { send_page_view: false });
gtag("event", "ramp_js", {
send_to: "G-KETCPNHRJF",
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
pageview_id: window._pwGA4PageviewId,
});
}
Expand Down
7 changes: 7 additions & 0 deletions frontend/src/ts/elements/account/result-filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,10 +350,12 @@ export function updateActive(): void {
}

for (const [id, select] of Object.entries(groupSelects)) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
const ss = select;
const group = getGroup(id as ResultFiltersGroup);
const everythingSelected = Object.values(group).every((v) => v === true);

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
const newData = ss.store.getData();

const allOption = $(
Expand Down Expand Up @@ -682,8 +684,10 @@ function adjustScrollposition(
group: ResultFiltersGroup,
topItem: number = 0
): void {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
const slimSelect = groupSelects[group];
if (slimSelect === undefined) return;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
const listElement = slimSelect.render.content.list;
const topListItem = listElement.children.item(topItem) as HTMLElement;

Expand Down Expand Up @@ -779,6 +783,7 @@ export async function appendButtons(
);
if (el) {
el.innerHTML = html;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
groupSelects["language"] = new SlimSelect({
select: el.querySelector(".languageSelect") as HTMLSelectElement,
settings: {
Expand Down Expand Up @@ -840,6 +845,7 @@ export async function appendButtons(
);
if (el) {
el.innerHTML = html;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
groupSelects["funbox"] = new SlimSelect({
select: el.querySelector(".funboxSelect") as HTMLSelectElement,
settings: {
Expand Down Expand Up @@ -897,6 +903,7 @@ export async function appendButtons(
);
if (el) {
el.innerHTML = html;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
groupSelects["tags"] = new SlimSelect({
select: el.querySelector(".tagsSelect") as HTMLSelectElement,
settings: {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/ts/elements/leaderboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,7 @@ export function show(): void {
Config.typingSpeedUnit + '<br><div class="sub">accuracy</div>'
);

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
languageSelector = new SlimSelect({
select:
"#leaderboardsWrapper #leaderboards .leaderboardsTop .buttonGroup.timeRange .languageSelect",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/elements/settings/settings-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export default class SettingsGroup<T extends ConfigValue> {
select.value = this.configValue as string;

//@ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unnecessary-type-assertion -- TODO: update slim-select
const ss = select.slim as SlimSelect | undefined;
ss?.store.setSelectedBy("value", [this.configValue as string]);
ss?.render.renderValues();
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/ts/elements/test-activity-calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ export class TestActivityCalendar implements MonkeyTypes.TestActivityCalendar {
lastDay: Date
): (number | null | undefined)[] {
//fill calendar with enough values
const values: (number | null | undefined)[] = new Array(
Math.max(0, 386 - data.length)
).fill(undefined);
const values = new Array(Math.max(0, 386 - data.length)).fill(
undefined
) as (number | null | undefined)[];
values.push(...data);

//discard values outside the calendar range
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/ts/elements/test-activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export function init(
}
$("#testActivity").removeClass("hidden");

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
yearSelector = getYearSelector();
initYearSelector("current", userSignUpDate?.getFullYear() || 2022);
update(calendar);
Expand Down Expand Up @@ -84,6 +85,7 @@ export function initYearSelector(
}
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
const yearSelect = getYearSelector();
yearSelect.setData(years);
years.length > 1 ? yearSelect.enable() : yearSelect.disable();
Expand All @@ -102,6 +104,7 @@ function updateMonths(months: MonkeyTypes.TestActivityMonth[]): void {

function getYearSelector(): SlimSelect {
if (yearSelector !== undefined) return yearSelector;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
yearSelector = new SlimSelect({
select: "#testActivity .yearSelect",
settings: {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/event-handlers/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ window.onerror = function (message, url, line, column, error): void {

window.onunhandledrejection = function (e): void {
if (Misc.isDevEnvironment()) {
const message = e.reason.message ?? e.reason;
const message = (e.reason.message ?? e.reason) as string;
Notifications.add(`${message}`, -1, {
customTitle: "DEV: Unhandled rejection",
duration: 5,
});
console.error(e);
}
void log("error", {
error: e.reason.stack ?? "",
error: (e.reason.stack ?? "") as string,
});
};
4 changes: 2 additions & 2 deletions frontend/src/ts/modals/edit-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ async function apply(): Promise<void> {
"data-preset-id"
) as string;

const updateConfig: boolean = $("#editPresetModal .modal label input").prop(
const updateConfig = $("#editPresetModal .modal label input").prop(
"checked"
);
) as boolean;

let configChanges: MonkeyTypes.ConfigChanges = {};

Expand Down
1 change: 1 addition & 0 deletions frontend/src/ts/modals/quote-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export async function show(
$("#quoteReportModal .reason").val("Grammatical error");
$("#quoteReportModal .comment").val("");

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
state.reasonSelect = new SlimSelect({
select: "#quoteReportModal .reason",
settings: {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/ts/modals/quote-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ export async function show(showOptions?: ShowOptions): Promise<void> {
$("#quoteSearchModal .goToQuoteApprove").addClass("hidden");
}

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
lengthSelect = new SlimSelect({
select: "#quoteSearchModal .quoteLengthFilter",

Expand Down
1 change: 1 addition & 0 deletions frontend/src/ts/modals/quote-submit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export async function show(showOptions: ShowOptions): Promise<void> {
);
await initDropdown();

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
select = new SlimSelect({
select: "#quoteSubmitModal .newQuoteLanguage",
});
Expand Down
1 change: 1 addition & 0 deletions frontend/src/ts/modals/user-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export async function show(options: ShowOptions): Promise<void> {
"Inappropriate name";
(modalEl.querySelector(".comment") as HTMLTextAreaElement).value = "";

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
select = new SlimSelect({
select: modalEl.querySelector(".reason") as HTMLElement,
settings: {
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/ts/modals/word-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,18 +159,21 @@ export async function show(showOptions?: ShowOptions): Promise<void> {
void modal.show({
...showOptions,
beforeAnimation: async (modalEl) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
languageSelect = new SlimSelect({
select: "#wordFilterModal .languageInput",
settings: {
contentLocation: modalEl,
},
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
layoutSelect = new SlimSelect({
select: "#wordFilterModal .layoutInput",
settings: {
contentLocation: modal.getModal(),
},
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- TODO: update slim-select
presetSelect = new SlimSelect({
select: "#wordFilterModal .presetInput",
settings: {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/pages/account-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ export function updateUI(): void {
}

$(".page.pageAccountSettings").on("click", ".tabs button", (event) => {
state.activeTab = $(event.target).data("tab");
state.activeTab = $(event.target).data("tab") as State["activeTab"];
updateTabs();
});

Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/pages/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1062,7 +1062,7 @@ $(".pageSettings .section.tags").on(
"click",
".tagsList .tag .tagButton",
(e) => {
const target = e.currentTarget;
const target = e.currentTarget as HTMLElement;
const tagid = $(target).parent(".tag").attr("data-id") as string;
TagController.toggle(tagid);
$(target).toggleClass("active");
Expand All @@ -1073,7 +1073,7 @@ $(".pageSettings .section.presets").on(
"click",
".presetsList .preset .presetButton",
async (e) => {
const target = e.currentTarget;
const target = e.currentTarget as HTMLElement;
const presetid = $(target).parent(".preset").attr("data-id") as string;
await PresetController.apply(presetid);
void update();
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/test/poetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function getPoem(): Promise<Section | false> {

try {
const response = await axios.get(apiURL);
const poemObj: PoemObject = response.data[0];
const poemObj = response.data[0] as PoemObject;

const words: string[] = [];

Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/test/test-logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1182,9 +1182,9 @@ async function saveResult(
}

if (data.insertedId !== undefined) {
const result: MonkeyTypes.FullResult<Mode> = JSON.parse(
const result = JSON.parse(
JSON.stringify(completedEvent)
);
) as MonkeyTypes.FullResult<Mode>;
result._id = data.insertedId;
if (data.isPb !== undefined && data.isPb) {
result.isPb = true;
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/ts/test/wikipedia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ export async function getSection(language: string): Promise<Section> {
let pageid = 0;

if (randomPostReq.status === 200) {
const postObj: Post = await randomPostReq.json();
const postObj = (await randomPostReq.json()) as Post;
sectionObj.title = postObj.title;
sectionObj.author = postObj.author;
pageid = postObj.pageid;
Expand All @@ -286,8 +286,9 @@ export async function getSection(language: string): Promise<Section> {
sectionReq.onload = (): void => {
if (sectionReq.readyState === 4) {
if (sectionReq.status === 200) {
let sectionText: string = JSON.parse(sectionReq.responseText).query
.pages[pageid.toString()].extract;
let sectionText = JSON.parse(sectionReq.responseText).query.pages[
pageid.toString()
].extract as string;

// Converting to one paragraph
sectionText = sectionText.replace(/<\/p><p>+/g, " ");
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/utils/local-storage-with-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export class LocalStorageWithSchema<T> {
return this.fallback;
}

let jsonParsed;
let jsonParsed: unknown;
try {
jsonParsed = JSON.parse(value);
} catch (e) {
Expand Down
21 changes: 21 additions & 0 deletions frontend/src/ts/utils/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Mode2,
PersonalBests,
} from "@monkeytype/contracts/schemas/shared";
import { ZodError, ZodSchema } from "zod";

export function kogasa(cov: number): number {
return (
Expand Down Expand Up @@ -684,4 +685,24 @@ export function isObject(obj: unknown): obj is Record<string, unknown> {
return typeof obj === "object" && !Array.isArray(obj) && obj !== null;
}

/**
* Parse a JSON string into an object and validate it against a schema
* @param input JSON string
* @param schema Zod schema to validate the JSON against
* @returns The parsed JSON object
*/
export function parseJsonWithSchema<T>(input: string, schema: ZodSchema<T>): T {
try {
const jsonParsed = JSON.parse(input) as unknown;
const zodParsed = schema.parse(jsonParsed);
return zodParsed;
} catch (error) {
if (error instanceof ZodError) {
throw new Error(error.errors.map((err) => err.message).join("\n"));
} else {
throw error;
}
}
}

// DO NOT ALTER GLOBAL OBJECTSONSTRUCTOR, IT WILL BREAK RESULT HASHES
4 changes: 2 additions & 2 deletions frontend/src/ts/utils/results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ export async function syncNotSignedInLastResult(uid: string): Promise<void> {
return;
}

const result: MonkeyTypes.FullResult<Mode> = JSON.parse(
const result = JSON.parse(
JSON.stringify(notSignedInLastResult)
);
) as MonkeyTypes.FullResult<Mode>;
result._id = response.body.data.insertedId;
if (response.body.data.isPb) {
result.isPb = true;
Expand Down
Loading

0 comments on commit d25b0d2

Please sign in to comment.