Skip to content

Commit

Permalink
refactor(utils): distribute color, numbers, strings and other group o…
Browse files Browse the repository at this point in the history
…f functions into separate util files from misc.ts (sanidhyas3s) (#5254)

* fix: Prevent theme switch when opening theme commandline from the footer

fixes #5103

* refactor(utils/misc): move functions and adjust usages
also renamed some functions for clarity
for #5187

* refactor(utils/misc): move color utils into separate file & add docstring
for #5187

* refactor(utils/misc): separte out number-related utils and more
add docstring to the functions in `utils/numbers`
also, move `getDiscordAvatarUrl` back into misc
because it was causing mt to not open somehow
for #5187

* refactor(utils/misc): move get-text functions into separate file & add docstring for them
    for #5187

* refactor(utils/misc): move get-data type functions into separate file & add docstrings
    for #5187

* Fix cyclic dependency by moving function

* Move strings utils to separate file and other minor changes to utils

* Shift Date & Time util functions to a separate file and add docstrings

* Shift more string functions to string util file

* separate out Arrays functions from misc utils

* Rename some utility files and move some functions

* lowercase filename

* rename module imports

* move ddr stuff into its own file

* temp file rename

* file rename

---------

Co-authored-by: Miodec <jack@monkeytype.com>
  • Loading branch information
sanidhyas3s and Miodec committed Apr 3, 2024
1 parent 8755f45 commit 39e611d
Show file tree
Hide file tree
Showing 79 changed files with 1,765 additions and 1,397 deletions.
2 changes: 1 addition & 1 deletion frontend/__tests__/test/misc.spec.ts
@@ -1,7 +1,7 @@
import {
getLanguageDisplayString,
removeLanguageSize,
} from "../../src/ts/utils/misc";
} from "../../src/ts/utils/strings";

describe("misc.ts", () => {
describe("getLanguageDisplayString", () => {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/html/pages/about.html
Expand Up @@ -80,7 +80,7 @@ <h2>
You can use
<key>tab</key>
and
<key>enter</key>
<key>enter</key>
(or just
<key>tab</key>
if you have quick tab mode enabled) to restart the typing test. Open the
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/account/all-time-stats.ts
@@ -1,5 +1,5 @@
import * as DB from "../db";
import * as Misc from "../utils/misc";
import * as DateTime from "../utils/date-and-time";

export function clear(): void {
$(".pageAccount .globalTimeTyping .val").text(`-`);
Expand All @@ -19,7 +19,7 @@ export function update(): void {
if (seconds === 0) {
string = "-";
} else {
string = Misc.secondsToString(Math.round(seconds), true, true);
string = DateTime.secondsToString(Math.round(seconds), true, true);
}
$(".pageAccount .globalTimeTyping .val").text(string);
}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/ts/account/mini-result-chart.ts
@@ -1,6 +1,7 @@
import * as ChartController from "../controllers/chart-controller";
import Config from "../config";
import * as Misc from "../utils/misc";
import * as Arrays from "../utils/arrays";

export function updatePosition(x: number, y: number): void {
$(".pageAccount .miniResultChartWrapper").css({ top: y, left: x });
Expand Down Expand Up @@ -28,7 +29,7 @@ export function updateData(data: SharedTypes.ChartData): void {
data.err = data.err.slice(0, data.raw.length);
labels = labels.slice(0, data.raw.length);

const smoothedRawData = Misc.smooth(data.raw, 1);
const smoothedRawData = Arrays.smooth(data.raw, 1);

ChartController.miniResult.data.labels = labels;

Expand Down
8 changes: 5 additions & 3 deletions frontend/src/ts/account/result-filters.ts
@@ -1,4 +1,6 @@
import * as Misc from "../utils/misc";
import * as Strings from "../utils/strings";
import * as JSONData from "../utils/json-data";
import * as DB from "../db";
import Config from "../config";
import * as Notifications from "../elements/notifications";
Expand Down Expand Up @@ -637,7 +639,7 @@ $(".pageAccount .topFilters button.toggleAdvancedFilters").on("click", () => {
export async function appendButtons(): Promise<void> {
let languageList;
try {
languageList = await Misc.getLanguageList();
languageList = await JSONData.getLanguageList();
} catch (e) {
console.error(
Misc.createErrorMessage(e, "Failed to append language buttons")
Expand All @@ -646,7 +648,7 @@ export async function appendButtons(): Promise<void> {
if (languageList) {
let html = "";
for (const language of languageList) {
html += `<button filter="${language}">${Misc.getLanguageDisplayString(
html += `<button filter="${language}">${Strings.getLanguageDisplayString(
language
)}</button>`;
}
Expand All @@ -658,7 +660,7 @@ export async function appendButtons(): Promise<void> {

let funboxList;
try {
funboxList = await Misc.getFunboxList();
funboxList = await JSONData.getFunboxList();
} catch (e) {
console.error(
Misc.createErrorMessage(e, "Failed to append funbox buttons")
Expand Down
13 changes: 7 additions & 6 deletions frontend/src/ts/commandline/lists.ts
Expand Up @@ -92,6 +92,7 @@ import KeymapLayoutsCommands, {

import Config, * as UpdateConfig from "../config";
import * as Misc from "../utils/misc";
import * as JSONData from "../utils/json-data";
import { randomizeTheme } from "../controllers/theme-controller";
import * as CustomTextPopup from "../popups/custom-text-popup";
import * as Settings from "../pages/settings";
Expand All @@ -102,7 +103,7 @@ import * as TestStats from "../test/test-stats";
import * as QuoteSearchModal from "../modals/quote-search";
import * as FPSCounter from "../elements/fps-counter";

const layoutsPromise = Misc.getLayoutsList();
const layoutsPromise = JSONData.getLayoutsList();
layoutsPromise
.then((layouts) => {
updateLayoutsCommands(layouts);
Expand All @@ -114,7 +115,7 @@ layoutsPromise
);
});

const languagesPromise = Misc.getLanguageList();
const languagesPromise = JSONData.getLanguageList();
languagesPromise
.then((languages) => {
updateLanguagesCommands(languages);
Expand All @@ -125,7 +126,7 @@ languagesPromise
);
});

const funboxPromise = Misc.getFunboxList();
const funboxPromise = JSONData.getFunboxList();
funboxPromise
.then((funboxes) => {
updateFunboxCommands(funboxes);
Expand All @@ -141,7 +142,7 @@ funboxPromise
);
});

const fontsPromise = Misc.getFontsList();
const fontsPromise = JSONData.getFontsList();
fontsPromise
.then((fonts) => {
updateFontFamilyCommands(fonts);
Expand All @@ -152,7 +153,7 @@ fontsPromise
);
});

const themesPromise = Misc.getThemesList();
const themesPromise = JSONData.getThemesList();
themesPromise
.then((themes) => {
updateThemesCommands(themes);
Expand All @@ -163,7 +164,7 @@ themesPromise
);
});

const challengesPromise = Misc.getChallengeList();
const challengesPromise = JSONData.getChallengeList();
challengesPromise
.then((challenges) => {
updateLoadChallengeCommands(challenges);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/commandline/lists/keymap-layouts.ts
@@ -1,6 +1,6 @@
import * as UpdateConfig from "../../config";
import * as TestLogic from "../../test/test-logic";
import { capitalizeFirstLetterOfEachWord } from "../../utils/misc";
import { capitalizeFirstLetterOfEachWord } from "../../utils/strings";

const subgroup: MonkeyTypes.CommandsSubgroup = {
title: "Change keymap layout...",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/commandline/lists/languages.ts
Expand Up @@ -2,7 +2,7 @@ import * as UpdateConfig from "../../config";
import {
capitalizeFirstLetterOfEachWord,
getLanguageDisplayString,
} from "../../utils/misc";
} from "../../utils/strings";

const subgroup: MonkeyTypes.CommandsSubgroup = {
title: "Language...",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/commandline/lists/layouts.ts
@@ -1,6 +1,6 @@
import * as UpdateConfig from "../../config";
import * as TestLogic from "../../test/test-logic";
import { capitalizeFirstLetterOfEachWord } from "../../utils/misc";
import { capitalizeFirstLetterOfEachWord } from "../../utils/strings";

const subgroup: MonkeyTypes.CommandsSubgroup = {
title: "Layout emulator...",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/commandline/lists/load-challenge.ts
@@ -1,7 +1,7 @@
import { navigate } from "../../controllers/route-controller";
import * as ChallengeController from "../../controllers/challenge-controller";
import * as TestLogic from "../../test/test-logic";
import { capitalizeFirstLetterOfEachWord } from "../../utils/misc";
import { capitalizeFirstLetterOfEachWord } from "../../utils/strings";

const subgroup: MonkeyTypes.CommandsSubgroup = {
title: "Load challenge...",
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/commandline/lists/result-screen.ts
@@ -1,7 +1,7 @@
import * as TestLogic from "../../test/test-logic";
import * as TestUI from "../../test/test-ui";
import * as PractiseWords from "../../test/practise-words";
import * as Misc from "../../utils/misc";
import * as GetText from "../../utils/generate";
import * as Notifications from "../../elements/notifications";

const copyWords: MonkeyTypes.CommandsSubgroup = {
Expand All @@ -15,7 +15,7 @@ const copyWords: MonkeyTypes.CommandsSubgroup = {
id: "copyYes",
display: "Yes, I am sure",
exec: (): void => {
const words = Misc.getWords();
const words = GetText.getWords();

navigator.clipboard.writeText(words).then(
() => {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ts/commandline/lists/themes.ts
@@ -1,5 +1,5 @@
import Config, * as UpdateConfig from "../../config";
import { capitalizeFirstLetterOfEachWord } from "../../utils/misc";
import { capitalizeFirstLetterOfEachWord } from "../../utils/strings";
import * as ThemeController from "../../controllers/theme-controller";

const subgroup: MonkeyTypes.CommandsSubgroup = {
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/ts/config-validation.ts
@@ -1,4 +1,5 @@
import * as Misc from "./utils/misc";
import * as JSONData from "./utils/json-data";
import * as Notifications from "./elements/notifications";

type PossibleType =
Expand Down Expand Up @@ -121,7 +122,7 @@ export async function isConfigValueValidAsync(
if (layoutNames.length < 2 || layoutNames.length > 5) break;

try {
await Misc.getLayoutsList();
await JSONData.getLayoutsList();
} catch (e) {
customMessage = Misc.createErrorMessage(
e,
Expand All @@ -132,7 +133,7 @@ export async function isConfigValueValidAsync(

// convert the layout names to layouts
const layouts = await Promise.all(
layoutNames.map(async (layoutName) => Misc.getLayout(layoutName))
layoutNames.map(async (layoutName) => JSONData.getLayout(layoutName))
);

// check if all layouts exist
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/ts/controllers/account-controller.ts
Expand Up @@ -3,6 +3,7 @@ import * as Notifications from "../elements/notifications";
import Config, * as UpdateConfig from "../config";
import * as AccountButton from "../elements/account-button";
import * as Misc from "../utils/misc";
import * as JSONData from "../utils/json-data";
import * as Settings from "../pages/settings";
import * as AllTimeStats from "../account/all-time-stats";
import * as DB from "../db";
Expand Down Expand Up @@ -125,7 +126,7 @@ async function getDataAndInit(): Promise<boolean> {

ResultFilters.loadTags(snapshot.tags);

Promise.all([Misc.getLanguageList(), Misc.getFunboxList()])
Promise.all([JSONData.getLanguageList(), JSONData.getFunboxList()])
.then((values) => {
const [languages, funboxes] = values;
languages.forEach((language) => {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/ts/controllers/ad-controller.ts
@@ -1,5 +1,5 @@
import { debounce } from "throttle-debounce";
import * as Misc from "../utils/misc";
import * as Numbers from "../utils/numbers";
import * as ConfigEvent from "../observables/config-event";
import * as BannerEvent from "../observables/banner-event";
import Config from "../config";
Expand Down Expand Up @@ -90,7 +90,7 @@ function removeResult(): void {

function updateVerticalMargin(): void {
const height = $("#bannerCenter").height() as number;
const margin = height + Misc.convertRemToPixels(2) + "px";
const margin = height + Numbers.convertRemToPixels(2) + "px";
$("#ad-vertical-left-wrapper").css("margin-top", margin);
$("#ad-vertical-right-wrapper").css("margin-top", margin);
}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/ts/controllers/challenge-controller.ts
@@ -1,4 +1,5 @@
import * as Misc from "../utils/misc";
import * as JSONData from "../utils/json-data";
import * as Notifications from "../elements/notifications";
import * as ManualRestart from "../test/manual-restart-tracker";
import * as CustomText from "../test/custom-text";
Expand Down Expand Up @@ -209,7 +210,7 @@ export async function setup(challengeName: string): Promise<boolean> {

let list;
try {
list = await Misc.getChallengeList();
list = await JSONData.getChallengeList();
} catch (e) {
const message = Misc.createErrorMessage(e, "Failed to setup challenge");
Notifications.add(message, -1);
Expand Down
32 changes: 18 additions & 14 deletions frontend/src/ts/controllers/chart-controller.ts
Expand Up @@ -63,7 +63,10 @@ import Config from "../config";
import * as ThemeColors from "../elements/theme-colors";
import * as ConfigEvent from "../observables/config-event";
import * as TestInput from "../test/test-input";
import * as Misc from "../utils/misc";
import * as DateTime from "../utils/date-and-time";
import * as Arrays from "../utils/arrays";
import * as Numbers from "../utils/numbers";
import { blendTwoHexColors } from "../utils/colors";

class ChartWithUpdateColors<
TType extends ChartType = ChartType,
Expand Down Expand Up @@ -242,7 +245,8 @@ export const result = new ChartWithUpdateColors<

const unique = [...new Set(wordsToHighlight)];
const firstHighlightWordIndex = unique[0];
const lastHighlightWordIndex = unique[unique.length - 1];
const lastHighlightWordIndex =
Arrays.lastElementFromArray(unique);
if (
firstHighlightWordIndex === undefined ||
lastHighlightWordIndex === undefined
Expand Down Expand Up @@ -496,9 +500,9 @@ export const accountHistory = new ChartWithUpdateColors<
const resultData = tooltipItem.dataset.data[
tooltipItem.dataIndex
] as MonkeyTypes.AccChartData;
return `error rate: ${Misc.roundTo2(
return `error rate: ${Numbers.roundTo2(
resultData.errorRate
)}%\nacc: ${Misc.roundTo2(100 - resultData.errorRate)}%`;
)}%\nacc: ${Numbers.roundTo2(100 - resultData.errorRate)}%`;
}
const resultData = tooltipItem.dataset.data[
tooltipItem.dataIndex
Expand Down Expand Up @@ -674,13 +678,13 @@ export const accountActivity = new ChartWithUpdateColors<
] as MonkeyTypes.ActivityChartDataPoint;
switch (tooltipItem.datasetIndex) {
case 0:
return `Time Typing: ${Misc.secondsToString(
return `Time Typing: ${DateTime.secondsToString(
Math.round(resultData.y * 60),
true,
true
)}\nTests Completed: ${resultData.amount}`;
case 1:
return `Average ${Config.typingSpeedUnit}: ${Misc.roundTo2(
return `Average ${Config.typingSpeedUnit}: ${Numbers.roundTo2(
resultData.y
)}`;
default:
Expand Down Expand Up @@ -777,15 +781,15 @@ export const accountHistogram = new ChartWithUpdateColors<
// ] as MonkeyTypes.ActivityChartDataPoint;
// switch (tooltipItem.datasetIndex) {
// case 0:
// return `Time Typing: ${Misc.secondsToString(
// return `Time Typing: ${DateTime.secondsToString(
// Math.round(resultData.y),
// true,
// true
// )}\nTests Completed: ${resultData.amount}`;
// case 1:
// return `Average ${
// Config.typingSpeedUnit
// }: ${Misc.roundTo2(resultData.y)}`;
// }: ${Numbers.roundTo2(resultData.y)}`;
// default:
// return "";
// }
Expand Down Expand Up @@ -1113,7 +1117,7 @@ async function updateColors<
const errorcolor = await ThemeColors.get("error");
const textcolor = await ThemeColors.get("text");

const gridcolor = Misc.blendTwoHexColors(bgcolor, subaltcolor, 0.75);
const gridcolor = blendTwoHexColors(bgcolor, subaltcolor, 0.75);

//@ts-expect-error
chart.data.datasets[0].borderColor = (ctx): string => {
Expand Down Expand Up @@ -1182,12 +1186,12 @@ async function updateColors<
const avg10On = Config.accountChart[2] === "on";
const avg100On = Config.accountChart[3] === "on";

const text02 = Misc.blendTwoHexColors(bgcolor, textcolor, 0.2);
const main02 = Misc.blendTwoHexColors(bgcolor, maincolor, 0.2);
const main04 = Misc.blendTwoHexColors(bgcolor, maincolor, 0.4);
const text02 = blendTwoHexColors(bgcolor, textcolor, 0.2);
const main02 = blendTwoHexColors(bgcolor, maincolor, 0.2);
const main04 = blendTwoHexColors(bgcolor, maincolor, 0.4);

const sub02 = Misc.blendTwoHexColors(bgcolor, subcolor, 0.2);
const sub04 = Misc.blendTwoHexColors(bgcolor, subcolor, 0.4);
const sub02 = blendTwoHexColors(bgcolor, subcolor, 0.2);
const sub04 = blendTwoHexColors(bgcolor, subcolor, 0.4);

const [
wpmDataset,
Expand Down
6 changes: 4 additions & 2 deletions frontend/src/ts/controllers/input-controller.ts
Expand Up @@ -4,6 +4,8 @@ import * as TestStats from "../test/test-stats";
import * as Monkey from "../test/monkey";
import Config from "../config";
import * as Misc from "../utils/misc";
import * as JSONData from "../utils/json-data";
import * as Numbers from "../utils/numbers";
import * as LiveAcc from "../test/live-acc";
import * as LiveBurst from "../test/live-burst";
import * as Funbox from "../test/funbox/funbox";
Expand Down Expand Up @@ -53,7 +55,7 @@ function setWordsInput(value: string): void {
}

function updateUI(): void {
const acc: number = Misc.roundTo2(TestStats.calculateAccuracy());
const acc: number = Numbers.roundTo2(TestStats.calculateAccuracy());
if (!isNaN(acc)) LiveAcc.update(acc);

if (Config.keymapMode === "next" && Config.mode !== "zen") {
Expand Down Expand Up @@ -1115,7 +1117,7 @@ $(document).on("keydown", async (event) => {
Config.oppositeShiftMode === "keymap" &&
Config.keymapLayout !== "overrideSync"
) {
const keymapLayout = await Misc.getLayout(Config.keymapLayout).catch(
const keymapLayout = await JSONData.getLayout(Config.keymapLayout).catch(
() => undefined
);
if (keymapLayout === undefined) {
Expand Down

0 comments on commit 39e611d

Please sign in to comment.