chore(dev): app boilerplate

Electron, React, Vite app boilerplate

- license header
- pre-commit and commit-msg hooks
- storybook
- fix windows tests;
- fix linux build
- CI setup
- persistent store with electron-store and safeStorage
- localization with react-intl

Refs:
- https://github.com/haveno-dex/haveno-ui/projects/1#card-81001746
- https://github.com/haveno-dex/haveno-ui/projects/1#card-81001745

Authored-by: schowdhuri
Reviewed-by: localredhead
This commit is contained in:
Subir 2022-04-23 04:32:54 +05:30 committed by Subir
parent 3a379a7c55
commit a9893aa853
81 changed files with 16560 additions and 0 deletions

1
.browserslistrc Normal file
View File

@ -0,0 +1 @@
Chrome 98

18
.editorconfig Normal file
View File

@ -0,0 +1,18 @@
# EditorConfig is awesome: http://EditorConfig.org
# https://github.com/jokeyrhyme/standard-editorconfig
# top-most EditorConfig file
root = true
# defaults
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_size = 2
indent_style = space
[*.md]
trim_trailing_whitespace = false

View File

@ -0,0 +1,42 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
if (process.env.VITE_APP_VERSION === undefined) {
const now = new Date();
process.env.VITE_APP_VERSION = `${now.getUTCFullYear() - 2000}.${
now.getUTCMonth() + 1
}.${now.getUTCDate()}-${now.getUTCHours() * 60 + now.getUTCMinutes()}`;
}
/**
* @type {import('electron-builder').Configuration}
* @see https://www.electron.build/configuration/configuration
*/
const config = {
directories: {
output: "dist",
buildResources: "buildResources",
},
files: ["packages/**/dist/**"],
extraMetadata: {
version: process.env.VITE_APP_VERSION,
},
linux: {
target: "AppImage",
},
};
module.exports = config;

View File

@ -0,0 +1,4 @@
{
"chrome": "98",
"node": "16"
}

26
.eslintrc.json Normal file
View File

@ -0,0 +1,26 @@
{
"root": true,
"env": {
"es2021": true,
"node": true,
"browser": false
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"ignorePatterns": ["node_modules/**", "**/dist/**"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/consistent-type-imports": "error",
"prettier/prettier": "error"
}
}

3
.gitattributes vendored Normal file
View File

@ -0,0 +1,3 @@
.github/actions/**/*.js linguist-detectable=false
scripts/*.js linguist-detectable=false
*.config.js linguist-detectable=false

View File

@ -0,0 +1,23 @@
name: "Release Notes"
description: "Return release notes based on Git Commits"
inputs:
from:
description: "Commit from which start log"
required: true
to:
description: "Commit to which end log"
required: true
include-commit-body:
description: "Should the commit body be in notes"
required: false
default: "false"
include-abbreviated-commit:
description: "Should the commit sha be in notes"
required: false
default: "true"
outputs:
release-note: # id of output
description: "Release notes"
runs:
using: "node12"
main: "main.js"

342
.github/actions/release-notes/main.js vendored Normal file
View File

@ -0,0 +1,342 @@
// TODO: Refactor this action
const { execSync } = require("child_process");
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
function getInput(name, options) {
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
const START_FROM = getInput("from");
const END_TO = getInput("to");
const INCLUDE_COMMIT_BODY = getInput("include-commit-body") === "true";
const INCLUDE_ABBREVIATED_COMMIT =
getInput("include-abbreviated-commit") === "true";
/**
* @typedef {Object} ICommit
* @property {string | undefined} abbreviated_commit
* @property {string | undefined} subject
* @property {string | undefined} body
*/
/**
* @typedef {ICommit & {type: string | undefined, scope: string | undefined}} ICommitExtended
*/
/**
* Any unique string that is guaranteed not to be used in committee text.
* Used to split data in the commit line
* @type {string}
*/
const commitInnerSeparator = "~~~~";
/**
* Any unique string that is guaranteed not to be used in committee text.
* Used to split each commit line
* @type {string}
*/
const commitOuterSeparator = "₴₴₴₴";
/**
* Commit data to be obtained.
* @type {Map<string, string>}
*
* @see https://git-scm.com/docs/git-log#Documentation/git-log.txt-emnem
*/
const commitDataMap = new Map([
["subject", "%s"], // Required
]);
if (INCLUDE_COMMIT_BODY) {
commitDataMap.set("body", "%b");
}
if (INCLUDE_ABBREVIATED_COMMIT) {
commitDataMap.set("abbreviated_commit", "%h");
}
/**
* The type used to group commits that do not comply with the convention
* @type {string}
*/
const fallbackType = "other";
/**
* List of all desired commit groups and in what order to display them.
* @type {string[]}
*/
const supportedTypes = [
"feat",
"fix",
"perf",
"refactor",
"style",
"docs",
"test",
"build",
"ci",
"chore",
"revert",
"deps",
fallbackType,
];
/**
* @param {string} commitString
* @returns {ICommit}
*/
function parseCommit(commitString) {
/** @type {ICommit} */
const commitDataObj = {};
const commitDataArray = commitString
.split(commitInnerSeparator)
.map((s) => s.trim());
for (const [key] of commitDataMap) {
commitDataObj[key] = commitDataArray.shift();
}
return commitDataObj;
}
/**
* Returns an array of commits since the last git tag
* @return {ICommit[]}
*/
function getCommits() {
const format =
Array.from(commitDataMap.values()).join(commitInnerSeparator) +
commitOuterSeparator;
const logs = String(
execSync(
`git --no-pager log ${START_FROM}..${END_TO} --pretty=format:"${format}" --reverse`
)
);
return logs
.trim()
.split(commitOuterSeparator)
.filter((r) => !!r.trim()) // Skip empty lines
.map(parseCommit);
}
/**
*
* @param {ICommit} commit
* @return {ICommitExtended}
*/
function setCommitTypeAndScope(commit) {
const matchRE = new RegExp(
`^(?:(${supportedTypes.join("|")})(?:\\((\\S+)\\))?:)?(.*)`,
"i"
);
let [, type, scope, clearSubject] = commit.subject.match(matchRE);
/**
* Additional rules for checking committees that do not comply with the convention, but for which it is possible to determine the type.
*/
// Commits like `revert something`
if (type === undefined && commit.subject.startsWith("revert")) {
type = "revert";
}
return {
...commit,
type: (type || fallbackType).toLowerCase().trim(),
scope: (scope || "").toLowerCase().trim(),
subject: (clearSubject || commit.subject).trim(),
};
}
class CommitGroup {
constructor() {
this.scopes = new Map();
this.commits = [];
}
/**
*
* @param {ICommitExtended[]} array
* @param {ICommitExtended} commit
*/
static _pushOrMerge(array, commit) {
const similarCommit = array.find((c) => c.subject === commit.subject);
if (similarCommit) {
if (commit.abbreviated_commit !== undefined) {
similarCommit.abbreviated_commit += `, ${commit.abbreviated_commit}`;
}
} else {
array.push(commit);
}
}
/**
* @param {ICommitExtended} commit
*/
push(commit) {
if (!commit.scope) {
CommitGroup._pushOrMerge(this.commits, commit);
return;
}
const scope = this.scopes.get(commit.scope) || { commits: [] };
CommitGroup._pushOrMerge(scope.commits, commit);
this.scopes.set(commit.scope, scope);
}
get isEmpty() {
return this.commits.length === 0 && this.scopes.size === 0;
}
}
/**
* Groups all commits by type and scopes
* @param {ICommit[]} commits
* @returns {Map<string, CommitGroup>}
*/
function getGroupedCommits(commits) {
const parsedCommits = commits.map(setCommitTypeAndScope);
const types = new Map(supportedTypes.map((id) => [id, new CommitGroup()]));
for (const parsedCommit of parsedCommits) {
const typeId = parsedCommit.type;
const type = types.get(typeId);
type.push(parsedCommit);
}
return types;
}
/**
* Return markdown list with commits
* @param {ICommitExtended[]} commits
* @param {string} pad
* @returns {string}
*/
function getCommitsList(commits, pad = "") {
let changelog = "";
for (const commit of commits) {
changelog += `${pad}- ${commit.subject}.`;
if (commit.abbreviated_commit !== undefined) {
changelog += ` (${commit.abbreviated_commit})`;
}
changelog += "\r\n";
if (commit.body === undefined) {
continue;
}
const body = commit.body.replace("[skip ci]", "").trim();
if (body !== "") {
changelog += `${body
.split(/\r*\n+/)
.filter((s) => !!s.trim())
.map((s) => `${pad} ${s}`)
.join("\r\n")}${"\r\n"}`;
}
}
return changelog;
}
function replaceHeader(str) {
switch (str) {
case "feat":
return "New Features";
case "fix":
return "Bug Fixes";
case "docs":
return "Documentation Changes";
case "build":
return "Build System";
case "chore":
return "Chores";
case "ci":
return "Continuous Integration";
case "refactor":
return "Refactors";
case "style":
return "Code Style Changes";
case "test":
return "Tests";
case "perf":
return "Performance improvements";
case "revert":
return "Reverts";
case "deps":
return "Dependency updates";
case "other":
return "Other Changes";
default:
return str;
}
}
/**
* Return markdown string with changelog
* @param {Map<string, CommitGroup>} groups
*/
function getChangeLog(groups) {
let changelog = "";
for (const [typeId, group] of groups) {
if (group.isEmpty) {
continue;
}
changelog += `### ${replaceHeader(typeId)}${"\r\n"}`;
for (const [scopeId, scope] of group.scopes) {
if (scope.commits.length) {
changelog += `- #### ${replaceHeader(scopeId)}${"\r\n"}`;
changelog += getCommitsList(scope.commits, " ");
}
}
if (group.commits.length) {
changelog += getCommitsList(group.commits);
}
changelog += "\r\n" + "\r\n";
}
return changelog.trim();
}
function escapeData(s) {
return String(s)
.replace(/%/g, "%25")
.replace(/\r/g, "%0D")
.replace(/\n/g, "%0A");
}
try {
const commits = getCommits();
const grouped = getGroupedCommits(commits);
const changelog = getChangeLog(grouped);
process.stdout.write(
"::set-output name=release-note::" + escapeData(changelog) + "\r\n"
);
// require('fs').writeFileSync('../CHANGELOG.md', changelog, {encoding: 'utf-8'})
} catch (e) {
console.error(e);
process.exit(1);
}

42
.github/renovate.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
"extends": [
"config:base",
":semanticCommits",
":automergeTypes",
":disableDependencyDashboard"
],
"labels": ["dependencies"],
"baseBranches": ["main"],
"bumpVersion": "patch",
"patch": {
"automerge": true
},
"minor": {
"automerge": true
},
"packageRules": [
{
"packageNames": ["node", "npm"],
"enabled": false
},
{
"depTypeList": ["devDependencies"],
"semanticCommitType": "build"
},
{
"matchSourceUrlPrefixes": ["https://github.com/vitejs/vite/"],
"groupName": "Vite monorepo packages",
"automerge": false
},
{
"matchPackagePatterns": ["^@typescript-eslint", "^eslint"],
"automerge": true,
"groupName": "eslint"
},
{
"matchPackageNames": ["electron"],
"separateMajorMinor": false
}
],
"rangeStrategy": "pin"
}

36
.github/workflows/lint.yml vendored Normal file
View File

@ -0,0 +1,36 @@
name: Linters
on:
push:
branches:
- main
paths:
- "**.js"
- "**.ts"
- ".github/workflows/lint.yml"
pull_request:
paths:
- "**.js"
- "**.ts"
- "package-lock.json"
- ".github/workflows/lint.yml"
defaults:
run:
shell: "bash"
jobs:
eslint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16 # Need for npm >=7.7
cache: "yarn"
# TODO: Install not all dependencies, but only those required for this workflow
- name: Install dependencies
run: yarn install --frozen-lockfile
- run: yarn lint

140
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,140 @@
name: Release
on:
push:
branches:
- main
paths-ignore:
- "**.md"
- "**.spec.js"
- ".idea"
- ".gitignore"
- ".github/**"
- "!.github/workflows/release.yml"
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: true
defaults:
run:
shell: "bash"
jobs:
draft:
runs-on: ubuntu-latest
outputs:
release-note: ${{ steps.release-note.outputs.release-note }}
version: ${{ steps.version.outputs.build-version }}
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- uses: actions/setup-node@v2
with:
node-version: 14
- name: Get last git tag
id: tag
run: echo "::set-output name=last-tag::$(git describe --tags --abbrev=0 || git rev-list --max-parents=0 ${{github.ref}})"
- name: Generate release notes
uses: ./.github/actions/release-notes
id: release-note
with:
from: ${{ steps.tag.outputs.last-tag }}
to: ${{ github.ref }}
include-commit-body: true
include-abbreviated-commit: true
- name: Get version from current date
id: version
run: echo "::set-output name=build-version::$(node -e "try{console.log(require('./.electron-builder.config.js').extraMetadata.version)}catch(e){console.error(e);process.exit(1)}")"
- name: Waiting on All checks
uses: lewagon/wait-on-check-action@v0.2
with:
ref: ${{ github.ref }}
repo-token: ${{ secrets.GITHUB_TOKEN }}
running-workflow-name: "draft"
- name: Delete outdated drafts
uses: hugo19941994/delete-draft-releases@v1.0.0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Create Release Draft
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.github_token }}
with:
prerelease: true
draft: true
tag_name: v${{ steps.version.outputs.build-version }}
name: v${{ steps.version.outputs.build-version }}
body: ${{ steps.release-note.outputs.release-note }}
upload_artifacts:
needs: [draft]
strategy:
matrix:
os: [ubuntu-latest]
# To compile the application for different platforms, use:
# os: [ macos-latest, ubuntu-latest, windows-latest ]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16 # Need for npm >=7.7
cache: "yarn"
- name: Install dependencies
run: yarn install --frozen-lockfile
# The easiest way to transfer release notes to a compiled application is create `release-notes.md` in the build resources.
# See https://github.com/electron-userland/electron-builder/issues/1511#issuecomment-310160119
- name: Prepare release notes
env:
RELEASE_NOTE: ${{ needs.draft.outputs.release-note }}
run: echo "$RELEASE_NOTE" >> ./buildResources/release-notes.md
# Compile app and upload artifacts
- name: Compile & release Electron app
uses: samuelmeuli/action-electron-builder@v1
env:
VITE_APP_VERSION: ${{ needs.draft.outputs.version }}
with:
build_script_name: build
args: --config .electron-builder.config.js
# GitHub token, automatically provided to the action
# (No need to define this secret in the repo settings)
github_token: ${{ secrets.github_token }}
# If the commit is tagged with a version (e.g. "v1.0.0"),
# release the app after building
release: true
# Sometimes the build may fail due to a connection problem with Apple, GitHub, etc. servers.
# This option will restart the build as many attempts as possible
max_attempts: 3
# Code Signing params
# Base64-encoded code signing certificate for Windows
# windows_certs: ''
# Password for decrypting `windows_certs`
# windows_certs_password: ''
# Base64-encoded code signing certificate for macOS
# mac_certs: ''
# Password for decrypting `mac_certs`
# mac_certs_password: ''

75
.github/workflows/tests.yml vendored Normal file
View File

@ -0,0 +1,75 @@
name: Tests
on:
push:
branches:
- main
paths:
- "packages/**"
- "tests/**"
- "package-lock.json"
- ".github/workflows/tests.yml"
pull_request:
paths:
- "packages/**"
- "tests/**"
- "package-lock.json"
- ".github/workflows/tests.yml"
defaults:
run:
shell: "bash"
jobs:
main:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
cache: "yarn"
- run: yarn install --frozen-lockfile
- run: yarn test:main
preload:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
cache: "yarn"
- run: yarn install --frozen-lockfile
- run: yarn test:preload
renderer:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
cache: "yarn"
- run: yarn install --frozen-lockfile
- run: yarn test:renderer
e2e:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
cache: "yarn"
- run: yarn install --frozen-lockfile
env:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
- run: npx playwright install --with-deps chromium
- run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- yarn test:e2e
if: matrix.os == 'ubuntu-latest'
- run: yarn test:e2e
if: matrix.os != 'ubuntu-latest'

37
.github/workflows/typechecking.yml vendored Normal file
View File

@ -0,0 +1,37 @@
name: Typechecking
on:
push:
branches:
- main
paths:
- "**.ts"
- "**/tsconfig.json"
- "yarn.lock"
- ".github/workflows/typechecking.yml"
pull_request:
paths:
- "**.ts"
- "**/tsconfig.json"
- "yarn.lock"
- ".github/workflows/typechecking.yml"
defaults:
run:
shell: "bash"
jobs:
typescript:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16 # Need for npm >=7.7
cache: "yarn"
# TODO: Install not all dependencies, but only those required for this workflow
- name: Install dependencies
run: yarn install --frozen-lockfile
- run: yarn typecheck

View File

@ -0,0 +1,41 @@
name: Update Electon vendors versions
on:
push:
branches:
- main
paths:
- "yarn.lock"
concurrency:
group: update-electron-vendors-${{ github.ref }}
cancel-in-progress: true
defaults:
run:
shell: "bash"
jobs:
node-chrome:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16 # Need for npm >=7.7
cache: "yarn"
# TODO: Install not all dependencies, but only those required for this workflow
- name: Install dependencies
run: yarn install --frozen-lockfile
- run: node ./scripts/update-electron-vendors.js
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
delete-branch: true
commit-message: Update electron vendors
branch: autoupdates/electron-vendors
title: Update electron vendors
body: Updated versions of electron vendors in `.electron-vendors.cache.json` and `.browserslistrc` files

56
.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
node_modules
.DS_Store
dist
*.local
thumbs.db
.eslintcache
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
.idea/artifacts
.idea/compiler.xml
.idea/jarRepositories.xml
.idea/modules.xml
.idea/*.iml
.idea/modules
*.iml
*.ipr
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# Editor-based Rest Client
.idea/httpRequests
/.idea/csv-plugin.xml

4
.husky/commit-msg Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn commitlint --edit $1

5
.husky/pre-commit Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn format --list-different
yarn nano-staged

38
.nano-staged.mjs Normal file
View File

@ -0,0 +1,38 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { resolve, sep } from "path";
export default {
// eslint
"*.{js,ts,tsx}": "eslint --cache --fix",
/**
* Run typechecking if any type-sensitive files was staged
* @param {string[]} filenames
* @return {string[]}
*/
"packages/**/{*.ts,*.tsx,tsconfig.json}": ({ filenames }) => {
const pathToPackages = resolve(process.cwd(), "packages") + sep;
return Array.from(
filenames.reduce((set, filename) => {
const pack = filename.replace(pathToPackages, "").split(sep)[0];
set.add(`npm run typecheck:${pack} --if-present`);
return set;
}, new Set())
);
},
};

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
node_modules
*.lock
buildResources
packages/main/dist
packages/preload/dist
packages/rendered/dist
dist/

42
.storybook/main.js Normal file
View File

@ -0,0 +1,42 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
const { mergeConfig } = require("vite");
const viteConfig = require("../packages/renderer/vite.config");
module.exports = {
stories: [
"../packages/renderer/**/*.stories.mdx",
"../packages/renderer/**/*.stories.@(js|jsx|ts|tsx)",
],
addons: [
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-interactions",
],
framework: "@storybook/react",
core: {
builder: "@storybook/builder-vite",
},
staticDirs: ["./public"],
viteFinal: async (config) => {
// return the customized config
return mergeConfig(config, {
root: viteConfig.root,
resolve: viteConfig.resolve,
});
},
};

View File

@ -0,0 +1,3 @@
<script>
window.global = window;
</script>

53
.storybook/preview.jsx Normal file
View File

@ -0,0 +1,53 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { RecoilRoot } from "recoil";
import { HashRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import { IntlProvider } from "@atoms/IntlProvider";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 60 * 1000, // 60 sec
},
},
});
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
export const decorators = [
(Story) => (
<HashRouter>
<RecoilRoot>
<IntlProvider>
<QueryClientProvider client={queryClient}>
{Story()}
</QueryClientProvider>
</IntlProvider>
</RecoilRoot>
</HashRouter>
),
];

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#B69056" />
<meta name="description" content="Haveno" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
rel="stylesheet"
/>
<title>Haveno :: Storybook</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="app"></div>
</body>
</html>

View File

@ -1,2 +1,3 @@
# haveno-ui
Haveno user interface

0
buildResources/.gitkeep Normal file
View File

BIN
buildResources/icon.icns Normal file

Binary file not shown.

BIN
buildResources/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

19
commitlint.config.js Normal file
View File

@ -0,0 +1,19 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
module.exports = {
extends: ["@commitlint/config-conventional"],
};

87
package.json Normal file
View File

@ -0,0 +1,87 @@
{
"name": "haveno-ui",
"version": "0.1.0",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/haveno-dex/haveno-ui.git"
},
"engines": {
"node": ">=v16.13",
"npm": ">=8.1"
},
"main": "packages/main/dist/index.cjs",
"scripts": {
"build": "npm run build:main && npm run build:preload && npm run build:renderer",
"build:main": "cd ./packages/main && vite build",
"build:preload": "cd ./packages/preload && vite build",
"build:renderer": "cd ./packages/renderer && vite build",
"compile": "cross-env MODE=production npm run build && electron-builder build --config .electron-builder.config.js --dir --config.asar=false",
"test": "npm run test:main && npm run test:preload && npm run test:renderer && npm run test:e2e",
"test:e2e": "npm run build && vitest run",
"test:main": "vitest run -r packages/main --passWithNoTests",
"test:preload": "vitest run -r packages/preload --passWithNoTests",
"test:renderer": "vitest run -r packages/renderer --passWithNoTests",
"watch": "node scripts/watch.js",
"format": "prettier --write .",
"lint": "eslint .",
"typecheck:main": "tsc --noEmit -p packages/main/tsconfig.json",
"typecheck:preload": "tsc --noEmit -p packages/preload/tsconfig.json",
"typecheck:renderer": "tsc --noEmit -p packages/renderer/tsconfig.json",
"typecheck": "npm run typecheck:main && npm run typecheck:preload && npm run typecheck:renderer",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
"license": "node scripts/license"
},
"devDependencies": {
"@babel/core": "^7.17.9",
"@commitlint/cli": "^16.2.3",
"@commitlint/config-conventional": "^16.2.1",
"@storybook/addon-actions": "^6.4.22",
"@storybook/addon-essentials": "^6.4.22",
"@storybook/addon-interactions": "^6.4.22",
"@storybook/addon-links": "^6.4.22",
"@storybook/builder-vite": "^0.1.29",
"@storybook/react": "^6.4.22",
"@storybook/testing-library": "^0.0.10",
"@types/react": "<18.0.0",
"@types/react-dom": "<18.0.0",
"@typescript-eslint/eslint-plugin": "5.12.1",
"@typescript-eslint/parser": "^5.19.0",
"@vitejs/plugin-react": "^1.3.0",
"babel-loader": "^8.2.5",
"cross-env": "7.0.3",
"electron": "17.1.0",
"electron-builder": "22.14.13",
"electron-devtools-installer": "3.2.0",
"eslint": "8.9.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.29.4",
"happy-dom": "2.41.0",
"husky": "^7.0.4",
"nano-staged": "^0.7.0",
"playwright": "1.19.1",
"prettier": "^2.6.2",
"typescript": "4.5.5",
"vite": "2.8.4",
"vite-plugin-svgr": "^1.1.0",
"vitest": "0.5.4"
},
"dependencies": {
"@mantine/core": "^4.1.2",
"@mantine/dates": "^4.1.2",
"@mantine/hooks": "^4.1.2",
"@mantine/modals": "^4.1.2",
"@mantine/notifications": "^4.1.2",
"dayjs": "^1.11.0",
"electron-store": "^8.0.1",
"electron-updater": "4.6.5",
"react": "<18.0.0",
"react-dom": "<18.0.0",
"react-intl": "^5.24.8",
"react-query": "^3.34.19",
"react-router-dom": "6",
"recoil": "^0.7.0"
}
}

View File

@ -0,0 +1,90 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { app } from "electron";
import "./security-restrictions";
import { restoreOrCreateWindow } from "@src/mainWindow";
import { registerStoreHandlers } from "./services/store";
/**
* Prevent multiple instances
*/
const isSingleInstance = app.requestSingleInstanceLock();
if (!isSingleInstance) {
app.quit();
process.exit(0);
}
app.on("second-instance", restoreOrCreateWindow);
/**
* Disable Hardware Acceleration for more power-save
*/
app.disableHardwareAcceleration();
/**
* Shout down background process if all windows was closed
*/
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
/**
* @see https://www.electronjs.org/docs/v14-x-y/api/app#event-activate-macos Event: 'activate'
*/
app.on("activate", restoreOrCreateWindow);
/**
* Create app window when background process will be ready
*/
app
.whenReady()
.then(restoreOrCreateWindow)
.catch((e) => console.error("Failed create window:", e));
app
.whenReady()
.then(registerStoreHandlers)
.catch((e) => console.error("Failed to register store handlers:", e));
/**
* Install devtools in development mode only
*/
if (import.meta.env.DEV) {
app
.whenReady()
.then(() => import("electron-devtools-installer"))
.then(({ default: installExtension, REACT_DEVELOPER_TOOLS }) =>
installExtension(REACT_DEVELOPER_TOOLS, {
loadExtensionOptions: {
allowFileAccess: true,
},
})
)
.catch((e) => console.error("Failed install extension:", e));
}
/**
* Check new app version in production mode only
*/
if (import.meta.env.PROD) {
app
.whenReady()
.then(() => import("electron-updater"))
.then(({ autoUpdater }) => autoUpdater.checkForUpdatesAndNotify())
.catch((e) => console.error("Failed check updates:", e));
}

View File

@ -0,0 +1,78 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { BrowserWindow } from "electron";
import { join } from "path";
import { URL } from "url";
async function createWindow() {
const browserWindow = new BrowserWindow({
show: false, // Use 'ready-to-show' event to show window
webPreferences: {
nativeWindowOpen: true,
webviewTag: false, // The webview tag is not recommended. Consider alternatives like iframe or Electron's BrowserView. https://www.electronjs.org/docs/latest/api/webview-tag#warning
preload: join(__dirname, "../../preload/dist/index.cjs"),
},
});
/**
* If you install `show: true` then it can cause issues when trying to close the window.
* Use `show: false` and listener events `ready-to-show` to fix these issues.
*
* @see https://github.com/electron/electron/issues/25012
*/
browserWindow.on("ready-to-show", () => {
browserWindow?.show();
if (import.meta.env.DEV) {
browserWindow?.webContents.openDevTools();
}
});
/**
* URL for main window.
* Vite dev server for development.
* `file://../renderer/index.html` for production and test
*/
const pageUrl =
import.meta.env.DEV && import.meta.env.VITE_DEV_SERVER_URL !== undefined
? import.meta.env.VITE_DEV_SERVER_URL
: new URL(
"../renderer/dist/index.html",
"file://" + __dirname
).toString();
await browserWindow.loadURL(pageUrl);
return browserWindow;
}
/**
* Restore existing BrowserWindow or Create new BrowserWindow
*/
export async function restoreOrCreateWindow() {
let window = BrowserWindow.getAllWindows().find((w) => !w.isDestroyed());
if (window === undefined) {
window = await createWindow();
}
if (window.isMinimized()) {
window.restore();
}
window.focus();
}

View File

@ -0,0 +1,159 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { app, shell } from "electron";
import { URL } from "url";
/**
* List of origins that you allow open INSIDE the application and permissions for each of them.
*
* In development mode you need allow open `VITE_DEV_SERVER_URL`
*/
const ALLOWED_ORIGINS_AND_PERMISSIONS = new Map<
string,
Set<
| "clipboard-read"
| "media"
| "display-capture"
| "mediaKeySystem"
| "geolocation"
| "notifications"
| "midi"
| "midiSysex"
| "pointerLock"
| "fullscreen"
| "openExternal"
| "unknown"
>
>(
import.meta.env.DEV && import.meta.env.VITE_DEV_SERVER_URL
? [[new URL(import.meta.env.VITE_DEV_SERVER_URL).origin, new Set()]]
: []
);
/**
* List of origins that you allow open IN BROWSER.
* Navigation to origins below is possible only if the link opens in a new window
*
* @example
* <a
* target="_blank"
* href="https://github.com/"
* >
*/
const ALLOWED_EXTERNAL_ORIGINS = new Set<`https://${string}`>([
"https://github.com",
]);
app.on("web-contents-created", (_, contents) => {
/**
* Block navigation to origins not on the allowlist.
*
* Navigation is a common attack vector. If an attacker can convince the app to navigate away
* from its current page, they can possibly force the app to open web sites on the Internet.
*
* @see https://www.electronjs.org/docs/latest/tutorial/security#13-disable-or-limit-navigation
*/
contents.on("will-navigate", (event, url) => {
const { origin } = new URL(url);
if (ALLOWED_ORIGINS_AND_PERMISSIONS.has(origin)) {
return;
}
// Prevent navigation
event.preventDefault();
if (import.meta.env.DEV) {
console.warn("Blocked navigating to an unallowed origin:", origin);
}
});
/**
* Block requested unallowed permissions.
* By default, Electron will automatically approve all permission requests.
*
* @see https://www.electronjs.org/docs/latest/tutorial/security#5-handle-session-permission-requests-from-remote-content
*/
contents.session.setPermissionRequestHandler(
(webContents, permission, callback) => {
const { origin } = new URL(webContents.getURL());
const permissionGranted =
!!ALLOWED_ORIGINS_AND_PERMISSIONS.get(origin)?.has(permission);
callback(permissionGranted);
if (!permissionGranted && import.meta.env.DEV) {
console.warn(
`${origin} requested permission for '${permission}', but was blocked.`
);
}
}
);
/**
* Hyperlinks to allowed sites open in the default browser.
*
* The creation of new `webContents` is a common attack vector. Attackers attempt to convince the app to create new windows,
* frames, or other renderer processes with more privileges than they had before; or with pages opened that they couldn't open before.
* You should deny any unexpected window creation.
*
* @see https://www.electronjs.org/docs/latest/tutorial/security#14-disable-or-limit-creation-of-new-windows
* @see https://www.electronjs.org/docs/latest/tutorial/security#15-do-not-use-openexternal-with-untrusted-content
*/
contents.setWindowOpenHandler(({ url }) => {
const { origin } = new URL(url);
// @ts-expect-error Type checking is performed in runtime
if (ALLOWED_EXTERNAL_ORIGINS.has(origin)) {
// Open default browser
shell.openExternal(url).catch(console.error);
} else if (import.meta.env.DEV) {
console.warn("Blocked the opening of an unallowed origin:", origin);
}
// Prevent creating new window in application
return { action: "deny" };
});
/**
* Verify webview options before creation
*
* Strip away preload scripts, disable Node.js integration, and ensure origins are on the allowlist.
*
* @see https://www.electronjs.org/docs/latest/tutorial/security#12-verify-webview-options-before-creation
*/
contents.on("will-attach-webview", (event, webPreferences, params) => {
const { origin } = new URL(params.src);
if (!ALLOWED_ORIGINS_AND_PERMISSIONS.has(origin)) {
if (import.meta.env.DEV) {
console.warn(
`A webview tried to attach ${params.src}, but was blocked.`
);
}
event.preventDefault();
return;
}
// Strip away preload scripts if unused or verify their location is legitimate
delete webPreferences.preload;
// @ts-expect-error `preloadURL` exists - see https://www.electronjs.org/docs/latest/api/web-contents#event-will-attach-webview
delete webPreferences.preloadURL;
// Disable Node.js integration
webPreferences.nodeIntegration = false;
});
});

View File

@ -0,0 +1,60 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { ipcMain, safeStorage } from "electron";
import Store from "electron-store";
import type {
IStoreSchema,
IUserInfo,
UserInfoInputType,
IUserPermission,
} from "@src/types";
import { StoreKeys, StoreSchema } from "@src/types";
const store = new Store<IStoreSchema>({ schema: StoreSchema });
export function registerStoreHandlers() {
ipcMain.handle("store:userinfo", async (_, payload?: UserInfoInputType) => {
const prevData = store.get(StoreKeys.UserInfo);
// retrieve encrypted data like so:
// safeStorage.decryptString(Buffer.from(prevData.password));
if (!payload) {
return prevData;
}
const userInfo: IUserInfo = {
...payload,
// encrypt sensitive data before storage
password: safeStorage.encryptString(payload.password),
};
store.set(StoreKeys.UserInfo, {
...(prevData ?? {}),
...userInfo,
});
return store.get(StoreKeys.UserInfo);
});
ipcMain.handle(
"store:permissions",
async (_, permissions?: Array<IUserPermission>) => {
const prevData = store.get(StoreKeys.Permissions);
if (!permissions) {
return prevData;
}
store.set(StoreKeys.Permissions, [...(prevData || []), ...permissions]);
return store.get(StoreKeys.Permissions);
}
);
}

View File

@ -0,0 +1,17 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
export * from "./store";

View File

@ -0,0 +1,64 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { Schema } from "electron-store";
export enum StoreKeys {
UserInfo = "UserInfo",
Permissions = "Permissions",
}
// TS types for StoreSchema
export interface IStoreSchema {
[StoreKeys.UserInfo]: IUserInfo;
[StoreKeys.Permissions]: Array<IUserPermission>;
}
export interface IUserInfo {
username: string;
password: Buffer;
}
export type UserInfoInputType = Omit<IUserInfo, "password"> & {
password: string;
};
export interface IUserPermission {
name: string;
}
// this schema is used by electron-store
// must mirror IStoreSchema
export const StoreSchema: Schema<IStoreSchema> = {
[StoreKeys.UserInfo]: {
type: "object",
required: [],
properties: {
username: { type: "string" },
},
},
[StoreKeys.Permissions]: {
type: "array",
default: [],
items: {
type: "object",
required: [],
properties: {
name: { type: "string" },
},
},
},
};

View File

@ -0,0 +1,82 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { MaybeMocked } from "vitest";
import { beforeEach, expect, test, vi } from "vitest";
import { restoreOrCreateWindow } from "../src/mainWindow";
import { BrowserWindow } from "electron";
/**
* Mock real electron BrowserWindow API
*/
vi.mock("electron", () => {
const bw = vi.fn() as MaybeMocked<typeof BrowserWindow>;
// @ts-expect-error It's work in runtime, but I Haven't idea how to fix this type error
bw.getAllWindows = vi.fn(() => bw.mock.instances);
bw.prototype.loadURL = vi.fn();
bw.prototype.on = vi.fn();
bw.prototype.destroy = vi.fn();
bw.prototype.isDestroyed = vi.fn();
bw.prototype.isMinimized = vi.fn();
bw.prototype.focus = vi.fn();
bw.prototype.restore = vi.fn();
return { BrowserWindow: bw };
});
beforeEach(() => {
vi.clearAllMocks();
});
test("Should create new window", async () => {
const { mock } = vi.mocked(BrowserWindow);
expect(mock.instances).toHaveLength(0);
await restoreOrCreateWindow();
expect(mock.instances).toHaveLength(1);
expect(mock.instances[0].loadURL).toHaveBeenCalledOnce();
expect(mock.instances[0].loadURL).toHaveBeenCalledWith(
expect.stringMatching(/index\.html$/)
);
});
test("Should restore existing window", async () => {
const { mock } = vi.mocked(BrowserWindow);
// Create Window and minimize it
await restoreOrCreateWindow();
expect(mock.instances).toHaveLength(1);
const appWindow = vi.mocked(mock.instances[0]);
appWindow.isMinimized.mockReturnValueOnce(true);
await restoreOrCreateWindow();
expect(mock.instances).toHaveLength(1);
expect(appWindow.restore).toHaveBeenCalledOnce();
});
test("Should create new window if previous was destroyed", async () => {
const { mock } = vi.mocked(BrowserWindow);
// Create Window and destroy it
await restoreOrCreateWindow();
expect(mock.instances).toHaveLength(1);
const appWindow = vi.mocked(mock.instances[0]);
appWindow.isDestroyed.mockReturnValueOnce(true);
await restoreOrCreateWindow();
expect(mock.instances).toHaveLength(2);
});

View File

@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "esnext",
"target": "esnext",
"sourceMap": false,
"moduleResolution": "Node",
"skipLibCheck": true,
"strict": true,
"isolatedModules": true,
"allowSyntheticDefaultImports": true,
"types": ["node", "vite-plugin-svgr/client"],
"baseUrl": ".",
"paths": {
"@src/*": ["./src/*"],
"@services/*": ["./src/services/*"],
"@types/*": ["./src/types/*"]
}
},
"include": ["src/**/*.ts", "../../types/**/*.d.ts"],
"exclude": ["**/*.spec.ts", "**/*.test.ts"]
}

View File

@ -0,0 +1,63 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { node } from "../../.electron-vendors.cache.json";
import { join } from "path";
import { builtinModules } from "module";
const PACKAGE_ROOT = __dirname;
/**
* @type {import('vite').UserConfig}
* @see https://vitejs.dev/config/
*/
const config = {
mode: process.env.MODE,
root: PACKAGE_ROOT,
envDir: process.cwd(),
resolve: {
alias: {
"@src/": join(PACKAGE_ROOT, "src") + "/",
"@services/": join(PACKAGE_ROOT, "src", "services") + "/",
"@types/": join(PACKAGE_ROOT, "src", "types") + "/",
},
},
build: {
sourcemap: "inline",
target: `node${node}`,
outDir: "dist",
assetsDir: ".",
minify: process.env.MODE !== "development",
lib: {
entry: "src/index.ts",
formats: ["cjs"],
},
rollupOptions: {
external: [
"electron",
"electron-devtools-installer",
...builtinModules.flatMap((p) => [p, `node:${p}`]),
],
output: {
entryFileNames: "[name].cjs",
},
},
emptyOutDir: true,
brotliSize: false,
},
};
export default config;

26
packages/preload/contracts.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
/* eslint-disable @typescript-eslint/consistent-type-imports */
interface Exposed {
readonly nodeCrypto: Readonly<typeof import("./src/nodeCrypto").nodeCrypto>;
readonly versions: Readonly<typeof import("./src/versions").versions>;
readonly electronStore: Readonly<typeof import("./src/store").store>;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Window extends Exposed {}

View File

@ -0,0 +1,32 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { contextBridge } from "electron";
/**
* Typesafe wrapper for `electron.contextBridge.exposeInMainWorld`.
* Guarantees that all exposed APIs will comply with contracts.
* @param key The key to inject the API onto window with. The API will be accessible on window[apiKey].
* @param api Your API
*
* @see https://www.electronjs.org/docs/latest/api/context-bridge#contextbridgeexposeinmainworldapikey-api
*/
export function exposeInMainWorld<T extends keyof Exposed & string>(
key: T,
api: Exposed[T]
) {
return contextBridge.exposeInMainWorld(key, api);
}

View File

@ -0,0 +1,23 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
/**
* @module preload
*/
import "./nodeCrypto";
import "./versions";
import "./store";

View File

@ -0,0 +1,27 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { type BinaryLike, createHash } from "crypto";
import { exposeInMainWorld } from "./exposeInMainWorld";
function sha256sum(data: BinaryLike) {
return createHash("sha256").update(data).digest("hex");
}
// Export for types in contracts.d.ts
export const nodeCrypto = { sha256sum } as const;
exposeInMainWorld("nodeCrypto", nodeCrypto);

View File

@ -0,0 +1,27 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { ipcRenderer } from "electron";
import { exposeInMainWorld } from "./exposeInMainWorld";
import type { UserInfoInputType } from "./types";
// Export for types in contracts.d.ts
export const store = {
storeUserinfo: async (data?: UserInfoInputType) =>
ipcRenderer.invoke("store:userinfo", data),
};
exposeInMainWorld("electronStore", store);

View File

@ -0,0 +1,17 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
export * from "./store";

View File

@ -0,0 +1,64 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { Schema } from "electron-store";
export enum StoreKeys {
UserInfo = "UserInfo",
Permissions = "Permissions",
}
// TS types for StoreSchema
export interface IStoreSchema {
[StoreKeys.UserInfo]: IUserInfo;
[StoreKeys.Permissions]: Array<IUserPermission>;
}
export interface IUserInfo {
username: string;
password: Buffer;
}
export type UserInfoInputType = Omit<IUserInfo, "password"> & {
password: string;
};
export interface IUserPermission {
name: string;
}
// this schema is used by electron-store
// must mirror IStoreSchema
export const StoreSchema: Schema<IStoreSchema> = {
[StoreKeys.UserInfo]: {
type: "object",
required: [],
properties: {
username: { type: "string" },
},
},
[StoreKeys.Permissions]: {
type: "array",
default: [],
items: {
type: "object",
required: [],
properties: {
name: { type: "string" },
},
},
},
};

View File

@ -0,0 +1,22 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { exposeInMainWorld } from "./exposeInMainWorld";
// Export for types in contracts.d.ts
export const versions = process.versions;
exposeInMainWorld("versions", versions);

View File

@ -0,0 +1,47 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { createHash } from "crypto";
import { afterEach, expect, test, vi } from "vitest";
const exposeInMainWorldMock = vi.fn();
vi.mock("electron", () => ({
contextBridge: { exposeInMainWorld: exposeInMainWorldMock },
}));
afterEach(() => {
vi.clearAllMocks();
});
test("versions", async () => {
await import("../src/versions");
expect(exposeInMainWorldMock).toBeCalledTimes(1);
expect(exposeInMainWorldMock).lastCalledWith("versions", process.versions);
});
test("nodeCrypto", async () => {
await import("../src/nodeCrypto");
expect(exposeInMainWorldMock).toBeCalledTimes(1);
expect(exposeInMainWorldMock.mock.calls[0][0]).toBe("nodeCrypto");
expect(exposeInMainWorldMock.mock.calls[0][1]).toHaveProperty("sha256sum");
const data = "rawData";
const expectedHash = createHash("sha256").update(data).digest("hex");
expect(exposeInMainWorldMock.mock.calls[0][1].sha256sum(data)).toBe(
expectedHash
);
});

View File

@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "esnext",
"target": "esnext",
"sourceMap": false,
"moduleResolution": "Node",
"skipLibCheck": true,
"strict": true,
"isolatedModules": true,
"types": ["node"],
"baseUrl": "."
},
"include": ["src/**/*.ts", "contracts.d.ts", "../../types/**/*.d.ts"],
"exclude": ["**/*.spec.ts", "**/*.test.ts"]
}

View File

@ -0,0 +1,54 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { chrome } from "../../.electron-vendors.cache.json";
import { builtinModules } from "module";
const PACKAGE_ROOT = __dirname;
/**
* @type {import('vite').UserConfig}
* @see https://vitejs.dev/config/
*/
const config = {
mode: process.env.MODE,
root: PACKAGE_ROOT,
envDir: process.cwd(),
build: {
sourcemap: "inline",
target: `chrome${chrome}`,
outDir: "dist",
assetsDir: ".",
minify: process.env.MODE !== "development",
lib: {
entry: "src/index.ts",
formats: ["cjs"],
},
rollupOptions: {
external: [
"electron",
...builtinModules.flatMap((p) => [p, `node:${p}`]),
],
output: {
entryFileNames: "[name].cjs",
},
},
emptyOutDir: true,
brotliSize: false,
},
};
export default config;

View File

@ -0,0 +1,29 @@
{
"env": {
"browser": true,
"node": false
},
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:prettier/recommended"
],
"parserOptions": {
"parser": "@typescript-eslint/parser",
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "react"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/consistent-type-imports": "error",
"prettier/prettier": "error"
},
"settings": {
"react": {
"version": "detect"
}
}
}

View File

@ -0,0 +1,15 @@
<svg width="410" height="404" viewBox="0 0 410 404" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M399.641 59.5246L215.643 388.545C211.844 395.338 202.084 395.378 198.228 388.618L10.5817 59.5563C6.38087 52.1896 12.6802 43.2665 21.0281 44.7586L205.223 77.6824C206.398 77.8924 207.601 77.8904 208.776 77.6763L389.119 44.8058C397.439 43.2894 403.768 52.1434 399.641 59.5246Z" fill="url(#paint0_linear)"/>
<path d="M292.965 1.5744L156.801 28.2552C154.563 28.6937 152.906 30.5903 152.771 32.8664L144.395 174.33C144.198 177.662 147.258 180.248 150.51 179.498L188.42 170.749C191.967 169.931 195.172 173.055 194.443 176.622L183.18 231.775C182.422 235.487 185.907 238.661 189.532 237.56L212.947 230.446C216.577 229.344 220.065 232.527 219.297 236.242L201.398 322.875C200.278 328.294 207.486 331.249 210.492 326.603L212.5 323.5L323.454 102.072C325.312 98.3645 322.108 94.137 318.036 94.9228L279.014 102.454C275.347 103.161 272.227 99.746 273.262 96.1583L298.731 7.86689C299.767 4.27314 296.636 0.855181 292.965 1.5744Z" fill="url(#paint1_linear)"/>
<defs>
<linearGradient id="paint0_linear" x1="6.00017" y1="32.9999" x2="235" y2="344" gradientUnits="userSpaceOnUse">
<stop stop-color="#41D1FF"/>
<stop offset="1" stop-color="#BD34FE"/>
</linearGradient>
<linearGradient id="paint1_linear" x1="194.651" y1="8.81818" x2="236.076" y2="292.989" gradientUnits="userSpaceOnUse">
<stop stop-color="#FFEA83"/>
<stop offset="0.0833333" stop-color="#FFDD35"/>
<stop offset="1" stop-color="#FFA800"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="script-src 'self' blob:"
/>
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script src="./src/index.tsx" type="module"></script>
</body>
</html>

View File

@ -0,0 +1,33 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { Routes, Route } from "react-router-dom";
import { Home } from "@pages/Home";
import { Page2 } from "@pages/Page2";
export const ROUTES = {
Home: "/",
Page2: "page2",
};
export function AppRoutes() {
return (
<Routes>
<Route path={ROUTES.Home} element={<Home />} />
<Route path={ROUTES.Page2} element={<Page2 />} />
</Routes>
);
}

View File

@ -0,0 +1,27 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { Box } from "@mantine/core";
import { FormattedMessage } from "react-intl";
import { LangKeys } from "@constants/lang/LangKeys";
export function Header() {
return (
<Box component="header">
<FormattedMessage id={LangKeys.AppTitle} defaultMessage="Header" />
</Box>
);
}

View File

@ -0,0 +1,53 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { FC } from "react";
import { useEffect, useMemo, useState } from "react";
import { IntlProvider as ReacIntlProvider } from "react-intl";
import type { LangKeys } from "@src/constants/lang/LangKeys";
const SupportedLocales = {
EN: "en",
ES: "es",
};
const DEFAULT_LOCALE = SupportedLocales.EN;
export const IntlProvider: FC = ({ children }) => {
const [messages, setMessages] = useState<{ [key in LangKeys]: string }>();
const locale = useMemo(
() =>
navigator.language in SupportedLocales
? navigator.language
: DEFAULT_LOCALE,
[navigator.language]
);
useEffect(() => {
console.log(navigator.language);
import(/* @vite-ignore */ `../../../constants/lang/${locale}.ts`).then(
(val) => {
setMessages(val.default);
}
);
}, [locale]);
return (
<ReacIntlProvider locale={locale} messages={messages}>
{children}
</ReacIntlProvider>
);
};

View File

@ -0,0 +1,30 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { ComponentStory, ComponentMeta } from "@storybook/react";
import { Header } from "../Header";
export default {
title: "atoms/Header",
component: Header,
} as ComponentMeta<typeof Header>;
const Template: ComponentStory<typeof Header> = () => {
return <Header />;
};
export const Default = Template.bind({});
Default.args = {};

View File

@ -0,0 +1,20 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
export enum LangKeys {
AppTitle = "app.title",
Header = "app.header",
}

View File

@ -0,0 +1,24 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { LangKeys } from "./LangKeys";
const LangPackEN: { [key in LangKeys]: string } = {
[LangKeys.AppTitle]: "Welcome",
[LangKeys.Header]: "Electron Starter",
};
export default LangPackEN;

View File

@ -0,0 +1,24 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { LangKeys } from "./LangKeys";
const LangPackES: { [key in LangKeys]: string } = {
[LangKeys.AppTitle]: "Bienvenido",
[LangKeys.Header]: "Electron Starter",
};
export default LangPackES;

View File

View File

@ -0,0 +1,47 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import { HashRouter } from "react-router-dom";
import { RecoilRoot } from "recoil";
import { IntlProvider } from "@atoms/IntlProvider";
import { AppRoutes } from "./Routes";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 60 * 1000, // 60 sec
},
},
});
ReactDOM.render(
<HashRouter>
<StrictMode>
<RecoilRoot>
<IntlProvider>
<QueryClientProvider client={queryClient}>
<AppRoutes />
</QueryClientProvider>
</IntlProvider>
</RecoilRoot>
</StrictMode>
</HashRouter>,
document.getElementById("app")
);

View File

@ -0,0 +1,32 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import { Link } from "react-router-dom";
import { ROUTES } from "@src/Routes";
import { FormattedMessage } from "react-intl";
import { LangKeys } from "@constants/lang/LangKeys";
export function Home() {
return (
<div>
<h1>Home</h1>
<h2>
<FormattedMessage id={LangKeys.AppTitle} defaultMessage="welcome" />
</h2>
<Link to={ROUTES.Page2}>Page 2</Link>
</div>
);
}

View File

@ -0,0 +1,64 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { FormEvent } from "react";
import { useEffect, useRef } from "react";
import { Link } from "react-router-dom";
import { ROUTES } from "@src/Routes";
export function Page2() {
const txtUserRef = useRef<HTMLInputElement>(null);
const txtPasswdRef = useRef<HTMLInputElement>(null);
const handleSubmit = (ev: FormEvent<HTMLFormElement>) => {
ev.preventDefault();
if (!txtUserRef.current || !txtPasswdRef.current) {
return;
}
window.electronStore
.storeUserinfo({
username: txtUserRef.current.value,
password: txtPasswdRef.current.value,
})
.then((value) => {
console.log({ value });
});
};
useEffect(() => {
if (txtUserRef.current) {
window.electronStore.storeUserinfo().then((value) => {
if (txtUserRef.current) {
txtUserRef.current.value = value.username;
}
});
}
}, [txtUserRef.current]);
return (
<div>
<h1>Page 2</h1>
<form onSubmit={handleSubmit}>
<input ref={txtUserRef} type="text" placeholder="username" />
<br />
<input ref={txtPasswdRef} type="password" placeholder="password" />
<button type="submit">Let me in</button>
</form>
<Link to={ROUTES.Home}>Go Home</Link>
</div>
);
}

View File

View File

@ -0,0 +1,17 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
export * from "./store";

View File

@ -0,0 +1,64 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { Schema } from "electron-store";
export enum StoreKeys {
UserInfo = "UserInfo",
Permissions = "Permissions",
}
// TS types for StoreSchema
export interface IStoreSchema {
[StoreKeys.UserInfo]: IUserInfo;
[StoreKeys.Permissions]: Array<IUserPermission>;
}
export interface IUserInfo {
username: string;
password: Buffer;
}
export type UserInfoInputType = Omit<IUserInfo, "password"> & {
password: string;
};
export interface IUserPermission {
name: string;
}
// this schema is used by electron-store
// must mirror IStoreSchema
export const StoreSchema: Schema<IStoreSchema> = {
[StoreKeys.UserInfo]: {
type: "object",
required: [],
properties: {
username: { type: "string" },
},
},
[StoreKeys.Permissions]: {
type: "array",
default: [],
items: {
type: "object",
required: [],
properties: {
name: { type: "string" },
},
},
},
};

View File

View File

View File

@ -0,0 +1,36 @@
{
"compilerOptions": {
"module": "esnext",
"target": "esnext",
"sourceMap": false,
"moduleResolution": "Node",
"skipLibCheck": true,
"strict": true,
"isolatedModules": true,
"types": ["node", "vite-plugin-svgr/client"],
"jsx": "react-jsx",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"baseUrl": "./src",
"paths": {
"@atoms/*": ["components/atoms/*"],
"@constants/*": ["constants/*"],
"@molecules/*": ["components/molecules/*"],
"@organisms/*": ["components/organisms/*"],
"@pages/*": ["pages/*"],
"@src/*": ["./*"],
"@templates/*": ["components/templates/*"],
"@utils/*": ["utils/*"]
},
"lib": ["ESNext", "dom", "dom.iterable"]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"types/**/*.d.ts",
"../../types/**/*.d.ts",
"../preload/contracts.d.ts"
],
"exclude": ["**/*.spec.ts", "**/*.test.ts"]
}

View File

View File

@ -0,0 +1,77 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
/* eslint-env node */
const { chrome } = require("../../.electron-vendors.cache.json");
const { join } = require("path");
const { builtinModules } = require("module");
const react = require("@vitejs/plugin-react");
const svgrPlugin = require("vite-plugin-svgr");
const PACKAGE_ROOT = __dirname;
/**
* @type {import('vite').UserConfig}
* @see https://vitejs.dev/config/
*/
const config = {
mode: process.env.MODE,
root: PACKAGE_ROOT,
resolve: {
alias: {
"@atoms/": join(PACKAGE_ROOT, "src", "components", "atoms") + "/",
"@constants/": join(PACKAGE_ROOT, "src", "constants") + "/",
"@molecules/": join(PACKAGE_ROOT, "src", "components", "molecules") + "/",
"@organisms/": join(PACKAGE_ROOT, "src", "components", "organisms") + "/",
"@pages/": join(PACKAGE_ROOT, "src", "pages") + "/",
"@src/": join(PACKAGE_ROOT, "src") + "/",
"@templates/": join(PACKAGE_ROOT, "src", "components", "templates") + "/",
"@utils/": join(PACKAGE_ROOT, "src", "utils") + "/",
},
},
plugins: [
react(),
svgrPlugin({
svgrOptions: {
icon: true,
},
}),
],
base: "",
server: {
fs: {
strict: true,
},
},
build: {
sourcemap: true,
target: `chrome${chrome}`,
outDir: "dist",
assetsDir: ".",
rollupOptions: {
input: join(PACKAGE_ROOT, "index.html"),
external: [...builtinModules.flatMap((p) => [p, `node:${p}`])],
},
emptyOutDir: true,
brotliSize: false,
},
test: {
environment: "happy-dom",
},
};
module.exports = config;

117
scripts/license.js Normal file
View File

@ -0,0 +1,117 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
const glob = require("glob");
const fsPromise = require("fs/promises");
const DIVIDER = "=".repeat(77);
/**
* Returns the list of source files which require a license header
* @param {number} year - Copyright year
* @param {string} owner - Copyright owner
* @returns {string}
*/
const fnLicense = (year, owner) =>
`// ${DIVIDER}
Copyright ${year} ${owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
${DIVIDER}`
.replace(/\n/g, "\n// ")
.replace(/ +\n/g, "\n");
async function main() {
console.log("Checking copyright headers...");
const licenseHeader = fnLicense(new Date().getFullYear(), "Haveno");
const files = await getFiles([
"{packages,scripts,tests,types,.storybook}/**/*.{js,jsx,ts,tsx}",
"*.{js,ts,mjs}",
]);
await Promise.all(
files.map(async (file) => {
let contents = (await fsPromise.readFile(file)).toString("utf-8");
if (contents.startsWith(licenseHeader)) {
// license exists
return;
}
if (contents.startsWith("#!")) {
// script; skip
return;
}
const lines = contents.split("\n");
const index = lines.findIndex((line) =>
/\/\/ {2}Copyright (\d{4}) (.+)/.test(line)
);
if (index === 1) {
// if the copyright is on line #2
// remove the header
while (lines[0].startsWith("//")) {
lines.shift();
}
console.log("updating the license header in", file);
contents = `${licenseHeader}\n${lines.join("\n")}`;
} else {
console.log("adding license header to", file);
contents = `${licenseHeader}\n\n${contents}`;
}
await fsPromise.writeFile(file, contents);
})
);
}
/**
* Returns the list of source files which require a license header
* @param {Array<string>} patterns - glob patterns
* @return {Promise<Array<string>>}
*/
async function getFiles(patterns) {
const files = new Set();
await Promise.all(
patterns.map(
(pattern) =>
new Promise((resolve, reject) => {
glob(
pattern,
{
dot: true,
ignore: ["**/dist/**/*"],
},
(err, paths) => {
if (err) {
return reject(err);
}
paths.map((path) => files.add(path));
resolve();
}
);
})
)
);
return [...files];
}
main();

View File

@ -0,0 +1,69 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
const { writeFile } = require("fs/promises");
const { execSync } = require("child_process");
const electron = require("electron");
const path = require("path");
/**
* Returns versions of electron vendors
* The performance of this feature is very poor and can be improved
* @see https://github.com/electron/electron/issues/28006
*
* @returns {NodeJS.ProcessVersions}
*/
function getVendors() {
const output = execSync(`${electron} -p "JSON.stringify(process.versions)"`, {
env: { ELECTRON_RUN_AS_NODE: "1" },
encoding: "utf-8",
});
return JSON.parse(output);
}
function updateVendors() {
const electronRelease = getVendors();
const nodeMajorVersion = electronRelease.node.split(".")[0];
const chromeMajorVersion = electronRelease.v8
.split(".")
.splice(0, 2)
.join("");
const browserslistrcPath = path.resolve(process.cwd(), ".browserslistrc");
return Promise.all([
writeFile(
"./.electron-vendors.cache.json",
JSON.stringify(
{
chrome: chromeMajorVersion,
node: nodeMajorVersion,
},
null,
2
) + "\n"
),
writeFile(browserslistrcPath, `Chrome ${chromeMajorVersion}\n`, "utf8"),
]);
}
updateVendors().catch((err) => {
console.error(err);
process.exit(1);
});

123
scripts/watch.js Normal file
View File

@ -0,0 +1,123 @@
#!/usr/bin/env node
const { createServer, build, createLogger } = require("vite");
const electronPath = require("electron");
const { spawn } = require("child_process");
/** @type 'production' | 'development'' */
const mode = (process.env.MODE = process.env.MODE || "development");
/** @type {import('vite').LogLevel} */
const LOG_LEVEL = "info";
/** @type {import('vite').InlineConfig} */
const sharedConfig = {
mode,
build: {
watch: {},
},
logLevel: LOG_LEVEL,
};
/** Messages on stderr that match any of the contained patterns will be stripped from output */
const stderrFilterPatterns = [
// warning about devtools extension
// https://github.com/cawa-93/vite-electron-builder/issues/492
// https://github.com/MarshallOfSound/electron-devtools-installer/issues/143
/ExtensionLoadWarning/,
];
/**
* @param {{name: string; configFile: string; writeBundle: import('rollup').OutputPlugin['writeBundle'] }} param0
*/
const getWatcher = ({ name, configFile, writeBundle }) => {
return build({
...sharedConfig,
configFile,
plugins: [{ name, writeBundle }],
});
};
/**
* Start or restart App when source files are changed
* @param {{config: {server: import('vite').ResolvedServerOptions}}} ResolvedServerOptions
*/
const setupMainPackageWatcher = ({ config: { server } }) => {
// Create VITE_DEV_SERVER_URL environment variable to pass it to the main process.
{
const protocol = server.https ? "https:" : "http:";
const host = server.host || "localhost";
const port = server.port; // Vite searches for and occupies the first free port: 3000, 3001, 3002 and so on
const path = "/";
process.env.VITE_DEV_SERVER_URL = `${protocol}//${host}:${port}${path}`;
}
const logger = createLogger(LOG_LEVEL, {
prefix: "[main]",
});
/** @type {ChildProcessWithoutNullStreams | null} */
let spawnProcess = null;
return getWatcher({
name: "reload-app-on-main-package-change",
configFile: "packages/main/vite.config.js",
writeBundle() {
if (spawnProcess !== null) {
spawnProcess.off("exit", process.exit);
spawnProcess.kill("SIGINT");
spawnProcess = null;
}
spawnProcess = spawn(String(electronPath), ["."]);
spawnProcess.stdout.on(
"data",
(d) =>
d.toString().trim() && logger.warn(d.toString(), { timestamp: true })
);
spawnProcess.stderr.on("data", (d) => {
const data = d.toString().trim();
if (!data) return;
const mayIgnore = stderrFilterPatterns.some((r) => r.test(data));
if (mayIgnore) return;
logger.error(data, { timestamp: true });
});
// Stops the watch script when the application has been quit
spawnProcess.on("exit", process.exit);
},
});
};
/**
* Start or restart App when source files are changed
* @param {{ws: import('vite').WebSocketServer}} WebSocketServer
*/
const setupPreloadPackageWatcher = ({ ws }) =>
getWatcher({
name: "reload-page-on-preload-package-change",
configFile: "packages/preload/vite.config.js",
writeBundle() {
ws.send({
type: "full-reload",
});
},
});
(async () => {
try {
const viteDevServer = await createServer({
...sharedConfig,
configFile: "packages/renderer/vite.config.js",
});
await viteDevServer.listen();
await setupPreloadPackageWatcher(viteDevServer);
await setupMainPackageWatcher(viteDevServer);
} catch (e) {
console.error(e);
process.exit(1);
}
})();

98
tests/e2e.spec.ts Normal file
View File

@ -0,0 +1,98 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import type { ElectronApplication } from "playwright";
import { _electron as electron } from "playwright";
import { afterAll, beforeAll, expect, test } from "vitest";
import { createHash } from "crypto";
import "../packages/preload/contracts.d.ts";
let electronApp: ElectronApplication;
beforeAll(async () => {
electronApp = await electron.launch({ args: ["."] });
});
afterAll(async () => {
await electronApp.close();
});
test("Main window state", async () => {
const windowState: {
isVisible: boolean;
isDevToolsOpened: boolean;
isCrashed: boolean;
} = await electronApp.evaluate(({ BrowserWindow }) => {
const mainWindow = BrowserWindow.getAllWindows()[0];
const getState = () => ({
isVisible: mainWindow.isVisible(),
isDevToolsOpened: mainWindow.webContents.isDevToolsOpened(),
isCrashed: mainWindow.webContents.isCrashed(),
});
return new Promise((resolve) => {
if (mainWindow.isVisible()) {
resolve(getState());
} else
mainWindow.once("ready-to-show", () =>
setTimeout(() => resolve(getState()), 0)
);
});
});
expect(windowState.isCrashed, "App was crashed").toBeFalsy();
expect(windowState.isVisible, "Main window was not visible").toBeTruthy();
expect(windowState.isDevToolsOpened, "DevTools was opened").toBeFalsy();
});
test("Main window web content", async () => {
const page = await electronApp.firstWindow();
const element = await page.$("#app", { strict: true });
expect(element, "Can't find root element").toBeDefined();
expect(
(await element.innerHTML()).trim(),
"Window content was empty"
).not.equal("");
});
test("Preload versions", async () => {
const page = await electronApp.firstWindow();
const exposedVersions = await page.evaluate(() => globalThis.versions);
const expectedVersions = await electronApp.evaluate(() => process.versions);
expect(exposedVersions).toBeDefined();
expect(exposedVersions).to.deep.equal(expectedVersions);
});
test("Preload nodeCrypto", async () => {
const page = await electronApp.firstWindow();
const exposedNodeCrypto = await page.evaluate(() => globalThis.nodeCrypto);
expect(exposedNodeCrypto).toHaveProperty("sha256sum");
const sha256sumType = await page.evaluate(
() => typeof globalThis.nodeCrypto.sha256sum
);
expect(sha256sumType).toEqual("function");
const rawTestData = "raw data";
const hash = await page.evaluate(
(d: string) => globalThis.nodeCrypto.sha256sum(d),
rawTestData
);
const expectedHash = createHash("sha256").update(rawTestData).digest("hex");
expect(hash).toEqual(expectedHash);
});

37
types/env.d.ts vendored Normal file
View File

@ -0,0 +1,37 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
/// <reference types="vite/client" />
/**
* Describes all existing environment variables and their types.
* Required for Code completion and type checking
*
* Note: To prevent accidentally leaking env variables to the client, only variables prefixed with `VITE_` are exposed to your Vite-processed code
*
* @see https://github.com/vitejs/vite/blob/cab55b32de62e0de7d7789e8c2a1f04a8eae3a3f/packages/vite/types/importMeta.d.ts#L62-L69 Base Interface
* @see https://vitejs.dev/guide/env-and-mode.html#env-files Vite Env Variables Doc
*/
interface ImportMetaEnv {
/**
* The value of the variable is set in scripts/watch.js and depend on packages/main/vite.config.js
*/
readonly VITE_DEV_SERVER_URL: undefined | string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}

39
vitest.config.js Normal file
View File

@ -0,0 +1,39 @@
// =============================================================================
// Copyright 2022 Haveno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
/**
* Config for global end-to-end tests
* placed in project root tests folder
* @type {import('vite').UserConfig}
* @see https://vitest.dev/config/
*/
const config = {
test: {
/**
* By default, vitest search test files in all packages.
* For e2e tests have sense search only is project root tests folder
*/
include: ["./tests/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],
/**
* A default timeout of 5000ms is sometimes not enough for playwright.
*/
testTimeout: 30_000,
hookTimeout: 30_000,
},
};
export default config;

13311
yarn.lock Normal file

File diff suppressed because it is too large Load Diff