Skip to content

Commit

Permalink
chore: migrate the Redux and helper code to TS (#84)
Browse files Browse the repository at this point in the history
* chore: migrate the Redux and helper code to TS

* chore: fix TypeScript errors
  • Loading branch information
nicomiguelino authored Jan 2, 2025
1 parent 339d9cd commit f55a58d
Show file tree
Hide file tree
Showing 19 changed files with 821 additions and 277 deletions.
940 changes: 709 additions & 231 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@
"typescript": "^5.3.3",
"webpack": "^5.96.1",
"webpack-cli": "^5.1.4",
"webpack-merge": "^6.0.1"
"webpack-merge": "^6.0.1",
"ts-loader": "^9.5.1"
},
"scripts": {
"test": "karma start --single-run --browsers ChromeHeadlessNoSandbox karma.conf.js",
Expand Down
9 changes: 0 additions & 9 deletions src/assets/js/store.js

This file was deleted.

File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { PopupSpinner } from '@/components/popup-spinner';
import { SaveAuthWarning } from '@/components/save-auth-warning';
import { SaveAuthHelp } from '@/components/save-auth-help';

import * as cookiejs from '@/vendor/cookie';
import * as cookiejs from '@/vendor/cookie.mjs';
import {
getAssetDashboardLink,
getUser,
Expand All @@ -19,7 +19,7 @@ import {
import {
notifyAssetSaveSuccess,
openSettings,
} from '@/features/popupSlice';
} from '@/features/popup-slice';

interface ErrorState {
show: boolean;
Expand Down Expand Up @@ -85,7 +85,7 @@ export const Proposal: React.FC = () => {
currentProposal.state = state;
} catch (error: any) {
if (error.status === 404) {
State.setSavedAssetState(url, null);
State.setSavedAssetState(url, null, false, false);
currentProposal.state = undefined;
} else {
throw error;
Expand Down Expand Up @@ -163,7 +163,7 @@ export const Proposal: React.FC = () => {
const originDomain = new URL(pageUrl).host;

const results = await Promise.all(
resourceEntries.map(url =>
resourceEntries.map((url: string) =>
browser.cookies.getAll({ url })
)
);
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { useState } from 'react';
import { useDispatch } from 'react-redux';
import classNames from 'classnames';

import { signOut } from '@/features/popupSlice';
import { signOut } from '@/features/popup-slice';
import { AppDispatch } from '@/store';

export const Settings: React.FC = () => {
const dispatch = useDispatch();
const dispatch = useDispatch<AppDispatch>();
const [isLoading, setIsLoading] = useState<boolean>(false);

const handleSignOut = async (event: React.MouseEvent<HTMLButtonElement>) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import classNames from 'classnames';
import { callApi } from '@/main';
import {
notifySignInSuccess,
} from '@/features/popupSlice';
} from '@/features/popup-slice';
import { TokenHelpText } from '@/components/token-help-text';

interface SignInFormErrorProps {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ const popupSlice = createSlice({
});

export const {
setAssetDashboardLink,
notifyAssetSaveSuccess,
notifySignInSuccess,
openSettings,
Expand Down
66 changes: 51 additions & 15 deletions src/assets/js/main.mjs → src/assets/ts/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
'use strict';

/* global browser */

import '@/vendor/normalize-url';

export function callApi(method, url, data, token) {
let init = {
interface RequestInit {
method: string;
headers: Record<string, string>;
body?: string;
}

declare global {
const browser: any;
interface Window {
normalizeUrl: (url: string, options: any) => string;
}
}

type BrowserStorageState = Record<string, any>;

export function callApi(
method: string,
url: string,
data: any,
token: string
) {
let init: RequestInit = {
method: method,
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -43,7 +61,13 @@ export function getUser() {
return browser.storage.sync.get(['token']);
}

export function createWebAsset(user, url, title, headers, disableVerification) {
export function createWebAsset(
user: any,
url: string,
title: string,
headers: any,
disableVerification: boolean
) {
return callApi(
'POST',
'https://api.screenlyapp.com/api/v4/assets/',
Expand All @@ -57,7 +81,14 @@ export function createWebAsset(user, url, title, headers, disableVerification) {
);
}

export function updateWebAsset(assetId, user, url, title, headers, disableVerification) { // eslint-disable-line no-unused-vars
export function updateWebAsset(
assetId: string,
user: any,
url: string,
title: string,
headers: any,
disableVerification: boolean
) { // eslint-disable-line no-unused-vars
let queryParams = `id=eq.${encodeURIComponent(assetId)}`;
return callApi(
'PATCH',
Expand All @@ -70,7 +101,7 @@ export function updateWebAsset(assetId, user, url, title, headers, disableVerifi
);
}

export function getWebAsset(assetId, user) {
export function getWebAsset(assetId: string, user: any) {
return callApi(
'GET',
`https://api.screenlyapp.com/api/v4/assets/${encodeURIComponent(assetId)}/`,
Expand All @@ -79,7 +110,7 @@ export function getWebAsset(assetId, user) {
)
}

export function getAssetDashboardLink(assetId) {
export function getAssetDashboardLink(assetId: string) {
return `https://login.screenlyapp.com/login?next=/manage/assets/${assetId}`;
}

Expand All @@ -89,7 +120,7 @@ export class State {
}

// Make a new URL equivalent to the given URL but in a normalized format.
static normalizeUrl(url) {
static normalizeUrl(url: string) {
return window.normalizeUrl(url, {
removeTrailingSlash: false,
sortQueryParameters: false,
Expand All @@ -98,7 +129,7 @@ export class State {
}

// Simplify a URL heavily, even if it slightly changes its meaning.
static simplifyUrl(url) {
static simplifyUrl(url: string) {
return window.normalizeUrl(url, {
removeTrailingSlash: true,
sortQueryParameters: true,
Expand All @@ -108,7 +139,12 @@ export class State {
})
}

static setSavedAssetState(url, assetId, withCookies, withBypass) {
static setSavedAssetState(
url: string,
assetId: string | null,
withCookies: boolean,
withBypass: boolean
) {
url = State.simplifyUrl(url);

const savedState = {
Expand All @@ -118,7 +154,7 @@ export class State {
};

return browser.storage.sync.get(['state'])
.then((state) => {
.then((state: BrowserStorageState) => {
state = state || {};

if (assetId) {
Expand All @@ -127,7 +163,7 @@ export class State {
delete state[url];

return browser.storage.sync.set({'state': state})
.catch((error) => {
.catch((error: Error) => {

if (!error || !error.message || !error.message.includes('QUOTA_BYTES')) {
// Unknown error. Ignore.
Expand All @@ -149,11 +185,11 @@ export class State {
});
}

static getSavedAssetState(url) {
static getSavedAssetState(url: string) {
url = State.simplifyUrl(url);

return browser.storage.sync.get(['state'])
.then(({state}) => {
.then(({state}: {state: BrowserStorageState}) => {
state = state || {};
const v = state[url];
if (typeof v != 'object') {
Expand Down
6 changes: 3 additions & 3 deletions src/assets/js/popup.tsx → src/assets/ts/popup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ import { SignInSuccess } from '@/components/sign-in-success';
import { Settings } from '@/components/settings';

import { store } from '@/store';
import { signIn } from '@/features/popupSlice';
import { RootState } from '@/types';
import { signIn } from '@/features/popup-slice';
import { RootState, AppDispatch } from '@/store';

interface CustomEvent extends Event {
detail: string;
}

const PopupPage: React.FC = () => {
const dispatch = useDispatch();
const dispatch = useDispatch<AppDispatch>();

const {
showSignIn,
Expand Down
12 changes: 12 additions & 0 deletions src/assets/ts/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { configureStore } from '@reduxjs/toolkit';

import popupReducer from '@/features/popup-slice';

export const store = configureStore({
reducer: {
popup: popupReducer,
},
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
2 changes: 1 addition & 1 deletion src/test/spec/test-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import {
State
} from "../../assets/js/main.mjs";
} from "@/main";

describe("State.normalizeUrl", function() {
const behaviours = [
Expand Down
24 changes: 23 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1 +1,23 @@

{
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"jsx": "react-jsx",
"module": "esnext",
"moduleResolution": "node",
"allowJs": true,
"esModuleInterop": true,
"strict": true,
"baseUrl": ".",
"paths": {
"@/components/*": ["src/assets/ts/components/*"],
"@/features/*": ["src/assets/ts/features/*"],
"@/scss/*": ["src/assets/scss/*"],
"@/vendor/*": ["src/lib/vendor/*"],
"@/store": ["src/assets/ts/store.ts"],
"@/main": ["src/assets/ts/main.ts"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
20 changes: 12 additions & 8 deletions webpack.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,25 @@ const webpack = require('webpack');

module.exports = {
entry: {
'popup': './src/assets/js/popup.tsx',
'popup': './src/assets/ts/popup.tsx',
},

module: {
rules: [
{
test: /\.(js|jsx|mjs|ts|tsx)$/,
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.(js|jsx|mjs)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript'
'@babel/preset-react'
]
}
}
Expand Down Expand Up @@ -84,10 +88,10 @@ module.exports = {

resolve: {
alias: {
'@/store': path.resolve(__dirname, 'src/assets/js/store.js'),
'@/main': path.resolve(__dirname, 'src/assets/js/main.mjs'),
'@/components': path.resolve(__dirname, 'src/assets/js/components'),
'@/features': path.resolve(__dirname, 'src/assets/js/features'),
'@/store': path.resolve(__dirname, 'src/assets/ts/store.ts'),
'@/main': path.resolve(__dirname, 'src/assets/ts/main.ts'),
'@/components': path.resolve(__dirname, 'src/assets/ts/components'),
'@/features': path.resolve(__dirname, 'src/assets/ts/features'),
'@/scss': path.resolve(__dirname, 'src/assets/scss'),
'@/vendor': path.resolve(__dirname, 'src/lib/vendor'),
},
Expand Down

0 comments on commit f55a58d

Please sign in to comment.