Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

convert Focus to TypeScript #700

Merged
merged 30 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
afe5cc7
chore: add test:type script
unional Jan 11, 2024
48061e3
refactor: convert some code to TS
unional Jan 11, 2024
d6f15a1
refactor: migrate padToN
unional Jan 19, 2024
0f4fbeb
chore: add w (watch) script for testing
unional Jan 19, 2024
01fcc03
chore: update vitest and add coverage
unional Jan 27, 2024
10e5247
refactor: extract str2ab
unional Jan 27, 2024
a2396de
chore: simplify test scripts
unional Jan 27, 2024
78b7769
test: zero length
unional Jan 27, 2024
d53bb69
chore: exclude test files from coverage
unional Jan 27, 2024
ca1fd2b
test: convert ascii and trim
unional Jan 27, 2024
c1bb710
chore: formatting
unional Jan 27, 2024
36d1d3a
refactor: extract constants
unional Jan 27, 2024
cfe2ad5
refactor: padToN signature
unional Jan 27, 2024
62dce59
refactor: extract num2hexstr
unional Jan 27, 2024
4e34179
refactor: remove extra usage of padToN
unional Jan 27, 2024
b6bb07e
refactor: stricter TypeScript config
unional Jan 27, 2024
47d392d
chore: rename test files
unional Jan 27, 2024
cbb561e
chore: remove extra files field
unional Jan 27, 2024
5214657
chore: update forge.config with strictes rules
unional Jan 28, 2024
8c992e3
chore: include webpack and vite config to strict check
unional Jan 28, 2024
f95f7ed
refactor: convert Focus to TypeScript
unional Jan 28, 2024
ddda81b
refactor: extract delay function
unional Jan 28, 2024
904e28f
refactor: move code into Focus.ts
unional Jan 28, 2024
053d602
refactor: change new Focus to Focus.getInstance
unional Jan 28, 2024
b5ac4c9
test: debugLog
unional Jan 28, 2024
6cc77e2
test: find empty
unional Jan 28, 2024
864ca3c
test: find
unional Jan 28, 2024
5a17a1b
refactor: mark some methods as private
unional Jan 28, 2024
035474f
refactor: add some types
unional Jan 28, 2024
b60c30f
Merge branch 'newFocusArch' into focus2
unional Feb 10, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions forge.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ const packagerConfig: ForgePackagerOptions = {
appCopyright: "Copyright © 2018, 2023 DygmaLab SL; distributed under the GPLv3",
};

if (process.env.NODE_ENV !== "development") {
if (process.env["NODE_ENV"] !== "development") {
packagerConfig.osxNotarize = {
tool: "notarytool",
appleId: process.env.APPLE_ID || "",
appleIdPassword: process.env.APPLE_ID_PASSWORD || "",
teamId: process.env.APPLE_TEAM_ID || "",
appleId: process.env["APPLE_ID"] || "",
appleIdPassword: process.env["APPLE_ID_PASSWORD"] || "",
teamId: process.env["APPLE_TEAM_ID"] || "",
};
packagerConfig.osxSign = {
optionsForFile: () => ({
Expand Down Expand Up @@ -79,7 +79,7 @@ const config: ForgeConfig = {
}),
],
hooks: {
packageAfterPrune: async (forgeConfig, buildPath, electronVersion, platform, arch) => {
packageAfterPrune: async (_forgeConfig, buildPath, _electronVersion, platform, _arch) => {
/**
* Serialport, usb and uiohook-napi are problematic libraries to run in Electron.
* When Electron app is been built, these libraries are not included properly in the final executable.
Expand All @@ -95,7 +95,7 @@ const config: ForgeConfig = {
};

fs.writeFileSync(path.resolve(buildPath, "package.json"), JSON.stringify(packageJson));
const npmInstall = spawnSync("npm", ["install", "--omit=dev"], {
spawnSync("npm", ["install", "--omit=dev"], {
cwd: buildPath,
stdio: "inherit",
shell: true,
Expand Down
10 changes: 8 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"main": ".webpack/main",
"scripts": {
"coverage": "vitest run --coverage",
"clean": "rm -rf dist && rm -rf out && rm -rf node_modules",
"start": "cross-env NODE_ENV=development electron-forge start",
"make-dev": "cross-env NODE_ENV=development electron-forge make",
Expand All @@ -22,7 +23,10 @@
"make-lin": "electron-forge make --platform=linux",
"lint": "eslint --ext .ts,.tsx,.js,.jsx .",
"prettier": "prettier --write \"./**/*.{js,json,css,scss,md}\"",
"test": "vitest run src",
"t": "vitest",
"tc": "vitest --coverage",
"test": "vitest",
"test:type": "tsc && tsc -p tsconfig.strict.json",
"e2e": "yarn playwright test",
"commit": "cz -s",
"prepare": "husky install"
Expand Down Expand Up @@ -75,7 +79,9 @@
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"@vercel/webpack-asset-relocator-loader": "1.7.3",
"@vitest/coverage-v8": "^1.2.2",
"@xpd/tailwind-3dtransforms": "^1.0.3",
"assertron": "^11.5.0",
"autoprefixer": "^10.4.16",
"babel-loader": "9.1.2",
"copy-webpack-plugin": "^11.0.0",
Expand Down Expand Up @@ -112,7 +118,7 @@
"ts-node": "^10.0.0",
"typescript": "~4.5.4",
"vite": "^4.5.2",
"vitest": "^0.32.2",
"vitest": "^1.2.2",
"webpack-cli": "^5.1.3"
},
"dependencies": {
Expand Down
9 changes: 8 additions & 1 deletion src/api/color/RGBWtoRGB.js → src/api/color/RGBWtoRGB.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
export default function rgbw2b(rgbw) {
type RGBW = {
r: number,
g: number,
b: number,
w: number
}

export default function rgbw2b(rgbw: RGBW) {
const r = rgbw.w + rgbw.r > 255 ? 255 : rgbw.w + rgbw.r;
const g = rgbw.w + rgbw.g > 255 ? 255 : rgbw.w + rgbw.g;
const b = rgbw.w + rgbw.b > 255 ? 255 : rgbw.w + rgbw.b;
Expand Down
8 changes: 7 additions & 1 deletion src/api/color/RGBtoRGBW.js → src/api/color/RGBtoRGBW.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
export default function rgb2w(rgb) {
type RGB = {
r: number,
g: number,
b: number
}

export default function rgb2w(rgb: RGB) {
const Ri = rgb.r;
const Gi = rgb.g;
const Bi = rgb.b;
Expand Down
2 changes: 1 addition & 1 deletion src/api/colormap/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export default class Colormap {
}
}

const focus = new Focus();
const focus = Focus.getInstance();
focus.addCommands({ colormap: new Colormap() });
focus.addMethod("setLayerSize", "colormap");
focus.addMethod("setLEDMode", "colormap");
2 changes: 1 addition & 1 deletion src/api/flash/decodeHexLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function decodeHexLine(line: string) {
const bytes = new ArrayBuffer(byteData.length);
const bytesView = new Uint8Array(bytes, 0, byteData.length);

for (let i = 0; i < byteData.length; i++) bytesView[i] = byteData[i];
byteData.forEach((v, i) => bytesView[i] = v)

return {
str: line,
Expand Down
34 changes: 4 additions & 30 deletions src/api/flash/defyFlasher/NRf52833-flasher.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,11 @@
import async from "async";
import Focus from "../../focus";
import { decodeHexLine } from "../decodeHexLine";
import { MAX_MS, PACKET_SIZE, TYPE_DAT, TYPE_ELA, TYPE_ESA } from "../flasherConstants";
import { num2hexstr } from "../num2hexstr";
import { str2ab } from "../str2ab";

const MAX_MS = 2000;

const PACKET_SIZE = 4096;

const TYPE_DAT = 0x00;
const TYPE_ESA = 0x02;
const TYPE_ELA = 0x04;

const focus = new Focus();
const focus = Focus.getInstance();

/**
* Writes data to the given bootloader serial port.
Expand Down Expand Up @@ -108,27 +103,6 @@ async function disconnect_cb(cb) {
cb(null, "");
}

function padToN(number, numberToPad) {
let str = "";

for (let i = 0; i < numberToPad; i++) str += "0";

return (str + number).slice(-numberToPad);
}

function num2hexstr(number, paddedTo) {
return padToN(number.toString(16), paddedTo);
}

function str2ab(str) {
const buf = new ArrayBuffer(str.length); // 2 bytes for each char
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i) & 0xff;
}
return buf;
}

/**
* Object NRf52833 with flash method.
*
Expand Down
24 changes: 12 additions & 12 deletions src/api/flash/defyFlasher/flash.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
* this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { ipcRenderer } from "electron";
import fs from "fs";
import path from "path";
import { ipcRenderer } from "electron";
import Focus from "../../focus";
import Hardware from "../../hardware";
import { delay } from '../delay';
import NRf52833 from "./NRf52833-flasher";

/**
Expand All @@ -44,7 +45,6 @@ class FlashDefyWireless {
firmwareFile: "File has not being selected",
};
this.backup = [];
this.delay = ms => new Promise(res => setTimeout(res, ms));
}

/**
Expand All @@ -66,7 +66,7 @@ class FlashDefyWireless {
* @returns {boolean} if device found - true, if no - false
*/
async foundDevices(hardware, message, bootloader) {
const focus = new Focus();
const focus = Focus.getInstance();
let isFindDevice = false;
await focus.find(...hardware).then(devices => {
for (const device of devices) {
Expand Down Expand Up @@ -100,7 +100,7 @@ class FlashDefyWireless {
* Takes backup settings from keyboard and writes its in backupfile.
*/
async backupSettings() {
const focus = new Focus();
const focus = Focus.getInstance();

const commands = [
"hardware.keyscan",
Expand Down Expand Up @@ -204,7 +204,7 @@ class FlashDefyWireless {
* @returns {promise}
*/
async resetKeyboard(backup, stateUpdate) {
const focus = new Focus();
const focus = Focus.getInstance();
console.log("reset start");
const errorMessage =
"The firmware update couldn't start because the Defy Bootloader wasn't found. Please check our Help Center for more details or schedule a video call with us.";
Expand All @@ -216,7 +216,7 @@ class FlashDefyWireless {
if (err) console.log("answer after shutdown not received");
});
console.log("waiting for bootloader");
await this.delay(1000);
await delay(1000);
stateUpdate("reset", 30);
try {
let bootCount = 10;
Expand All @@ -227,7 +227,7 @@ class FlashDefyWireless {
stateUpdate("reset", 100);
break;
}
await this.delay(300);
await delay(300);
bootCount--;
}
if (bootCount != true) {
Expand All @@ -248,14 +248,14 @@ class FlashDefyWireless {
*/
async updateFirmware(firmware, bootloader, stateUpdate) {
if (!bootloader) {
const focus = new Focus();
const focus = Focus.getInstance();
await focus.close();
}
console.log("Begin update firmware with NRf52833", bootloader);
return new Promise(async (resolve, reject) => {
try {
if (!bootloader) {
const focus = new Focus();
const focus = Focus.getInstance();
if (focus.closed) {
await focus.open(this.currentPath, this.currentPort.device, null);
}
Expand All @@ -266,7 +266,7 @@ class FlashDefyWireless {
else {
stateUpdate("neuron", 100);
console.log("End update firmware with NRf52833");
// await this.delay(1500);
// await delay(1500);
// await this.detectKeyboard();
resolve();
}
Expand All @@ -290,7 +290,7 @@ class FlashDefyWireless {
// wait until the bootloader serial port disconnects and the keyboard serial port reconnects
const findKeyboard = async () =>
new Promise(async resolve => {
await this.delay(timeouts);
await delay(timeouts);
if (await this.foundDevices(Hardware.serial, "Keyboard detected", false)) {
resolve(true);
} else {
Expand Down Expand Up @@ -329,7 +329,7 @@ class FlashDefyWireless {
*/
async restoreSettings(backup, stateUpdate) {
stateUpdate("restore", 0);
const focus = new Focus();
const focus = Focus.getInstance();
const errorMessage = "Firmware update failed, because the settings could not be restored";
console.log(backup);
if (backup === undefined || backup.length === 0) {
Expand Down
3 changes: 2 additions & 1 deletion src/api/flash/defyFlasher/rp2040-flasher.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import { ipcRenderer } from "electron";
import fs from "fs";
import * as path from "path";
import { delay } from "../delay";
import sideFlaser from "./sideFlasher";

/**
Expand Down Expand Up @@ -54,7 +55,7 @@ export default class rp2040 {
if (result.error) finished(result.error, result.message);
console.log("Left side flash has error? ", result.error);
step += 25;
await this.delay(20);
await delay(20);
finished(false, "");
}

Expand Down
3 changes: 3 additions & 0 deletions src/api/flash/delay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function delay(ms:number) {
return new Promise(res => setTimeout(res, ms))
}
7 changes: 7 additions & 0 deletions src/api/flash/flasherConstants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const MAX_MS = 2000;

export const PACKET_SIZE = 4096;

export const TYPE_DAT = 0x00;
export const TYPE_ESA = 0x02;
export const TYPE_ELA = 0x04;
5 changes: 5 additions & 0 deletions src/api/flash/num2hexstr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { padToN } from './padToN'

export function num2hexstr(number: number, paddedTo?: number | undefined) {
return padToN(number.toString(16), paddedTo);
}
6 changes: 6 additions & 0 deletions src/api/flash/num2hexstr.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expect, it } from 'vitest'
import { num2hexstr } from './num2hexstr'

it('converts number to hex string', () =>{
expect(num2hexstr(128)).toEqual('80')
})
7 changes: 7 additions & 0 deletions src/api/flash/padToN.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function padToN(number: string, numberToPad: number = 0) {
let str = "";

for (let i = 0; i < numberToPad; i++) str += "0";

return (str + number).slice(-numberToPad);
}
20 changes: 20 additions & 0 deletions src/api/flash/padToN.unit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect, it } from "vitest";
import { padToN } from "./padToN";

it("pads number to N digit string", () => {
expect(padToN("1", 8)).toEqual("00000001");
});

it("does not add additional digits if number already has N", () => {
expect(padToN("1234", 4)).toEqual("1234");
});

// Behavior does not match function name.
// Suggest fixing this.ts
it("trims to N digit string", () => {
expect(padToN("1234", 3)).toEqual("234");
});

it('number to pad is optional', () => {
expect(padToN('123')).toEqual('123')
})
Loading
Loading