formatted files

This commit is contained in:
Fran Jurmanović
2021-06-11 19:06:43 +02:00
parent 47f6207798
commit 130246ca88
70 changed files with 3281 additions and 21038 deletions

View File

@@ -1,20 +1,37 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
"env": {
"browser": true,
"node": true,
"es6": true
},
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"modules": true,
"experimentalObjectRestSpread": true
}
},
"globals": {
"__CONFIG__": true
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"no-multiple-empty-lines": [
2,
{
"max": 1
}
],
"no-unused-vars": [
2,
{
"ignoreRestSiblings": true
}
]
}
}

10
.prettierrc Normal file
View File

@@ -0,0 +1,10 @@
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": true,
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"jsxBracketSameLine": false
}

18126
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,37 +7,42 @@
"scripts": {
"start": "webpack serve --mode development --hot",
"build": "webpack --mode production",
"format": "eslint"
"format": "prettier --write src/**/*.{js,ts,html}"
},
"dependencies": {
"@github/catalyst": "^1.1.3",
"lit-html": "^1.4.1",
"validator": "^13.6.0"
},
"devDependencies": {
"@babel/core": "^7.14.3",
"@babel/plugin-proposal-class-properties": "^7.13.0",
"@babel/plugin-proposal-decorators": "^7.14.2",
"@babel/plugin-proposal-object-rest-spread": "^7.14.2",
"@babel/preset-env": "^7.14.2",
"@babel/preset-typescript": "^7.13.0",
"@github/catalyst": "^1.1.3",
"@github/jtml": "^0.4.0",
"@typescript-eslint/eslint-plugin": "^4.26.0",
"@typescript-eslint/parser": "^4.26.0",
"babel-loader": "^8.2.2",
"babel-plugin-module-resolver": "^4.1.0",
"babel-polyfill": "^6.26.0",
"compression-webpack-plugin": "^8.0.0",
"connect-history-api-fallback": "^1.6.0",
"css-loader": "^5.2.6",
"eslint": "^7.28.0",
"eslint-config-prettier": "^8.3.0",
"eslint-loader": "^4.0.2",
"eslint-plugin-import": "^2.23.4",
"html-webpack-plugin": "^5.3.1",
"lit-html": "^1.4.1",
"node-sass": "^6.0.0",
"prettier": "^2.3.1",
"sass-loader": "^11.1.1",
"sass-to-string": "^1.5.1",
"validator": "^13.6.0",
"webpack": "^5.38.1",
"webpack-dev-server": "^3.11.2"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^4.26.0",
"@typescript-eslint/parser": "^4.26.0",
"compression-webpack-plugin": "^8.0.0",
"eslint": "^7.27.0",
"terser-webpack-plugin": "^5.1.3",
"webpack-cli": "^4.7.0"
"uglify-js": "^3.13.9",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2"
}
}

View File

@@ -1,4 +1,4 @@
import { BaseElement } from "common/";
import { BaseElement } from 'common/';
class BaseComponentElement extends BaseElement {}

View File

@@ -1 +1 @@
export { default as BaseComponentElement } from "./BaseComponentElement/BaseComponentElement";
export { default as BaseComponentElement } from './BaseComponentElement/BaseComponentElement';

View File

@@ -1,13 +1,8 @@
import { html, render, TemplateResult } from "lit-html";
import {
AppLoaderElement,
AppMainElement,
AppModalElement,
AppRootElement,
} from "components/";
import { AppService, RouterService } from "core/services";
import { AuthStore } from "core/store";
import { closest } from "core/utils";
import { html, render, TemplateResult } from 'lit-html';
import { AppLoaderElement, AppMainElement, AppModalElement, AppRootElement } from 'components/';
import { AppService, RouterService } from 'core/services';
import { AuthStore } from 'core/store';
import { closest } from 'core/utils';
class BaseElement extends HTMLElement {
@closest appMain: AppMainElement;
@@ -51,11 +46,9 @@ class BaseElement extends HTMLElement {
public bindEvents = (attrName): void => {
const _elems = this.querySelectorAll(`[${attrName}]`);
_elems?.forEach((el) => {
for (const action of (el.getAttribute(attrName) || "")
.trim()
.split(/\s+/)) {
const eventSep = action.lastIndexOf(":");
const methodSep = action.lastIndexOf("#");
for (const action of (el.getAttribute(attrName) || '').trim().split(/\s+/)) {
const eventSep = action.lastIndexOf(':');
const methodSep = action.lastIndexOf('#');
const tag = action.slice(eventSep + 1, methodSep);
const type = action.slice(0, eventSep);
@@ -63,15 +56,13 @@ class BaseElement extends HTMLElement {
if (tag.toUpperCase() === this.tagName) {
el.addEventListener(type, this?.[method]);
const _callback = () =>
el.removeEventListener(type, this?.[method]);
const _callback = () => el.removeEventListener(type, this?.[method]);
this.elementDisconnectCallbacks.push(_callback);
} else {
this.childNodes.forEach((child: HTMLElement) => {
if (child.tagName == tag.toUpperCase()) {
el.addEventListener(type, child?.[method]);
const _callback = () =>
el.removeEventListener(type, child?.[method]);
const _callback = () => el.removeEventListener(type, child?.[method]);
this.elementDisconnectCallbacks.push(_callback);
}
});
@@ -88,8 +79,8 @@ class BaseElement extends HTMLElement {
update = (): void => {
render(this.render(), this);
this.bindEvents("data-action");
this.bindEvents("app-action");
this.bindEvents('data-action');
this.bindEvents('app-action');
this.updateCallback();
};
@@ -103,7 +94,7 @@ class BaseElement extends HTMLElement {
this.elementDisconnected(_appMain);
if (Array.isArray(this.elementDisconnectCallbacks)) {
this.elementDisconnectCallbacks.forEach((callback: Function) => {
if (typeof callback == "function") {
if (typeof callback == 'function') {
callback(_appMain);
}
});

View File

@@ -1,4 +1,4 @@
export { default as BaseElement } from "./core/BaseElement/BaseElement";
export * from "./layouts";
export * from "./components";
export * from "./pages";
export { default as BaseElement } from './core/BaseElement/BaseElement';
export * from './layouts';
export * from './components';
export * from './pages';

View File

@@ -1,5 +1,5 @@
import { target } from "@github/catalyst";
import { BaseElement } from "common/";
import { target } from '@github/catalyst';
import { BaseElement } from 'common/';
class BaseLayoutElement extends BaseElement {
@target appSlot: HTMLElement;
@@ -14,7 +14,7 @@ class BaseLayoutElement extends BaseElement {
}
compareTags = (tag: string | HTMLElement): boolean => {
if (typeof tag === "string") {
if (typeof tag === 'string') {
return this.slotTag === tag;
}
return tag?.tagName === this.slotTag;

View File

@@ -1 +1 @@
export { default as BaseLayoutElement } from "./BaseLayoutElement/BaseLayoutElement";
export { default as BaseLayoutElement } from './BaseLayoutElement/BaseLayoutElement';

View File

@@ -1,10 +1,10 @@
import { attr } from "@github/catalyst";
import { html, render } from "lit-html";
import { BaseElement } from "common/";
import { isTrue } from "core/utils";
import { attr } from '@github/catalyst';
import { html, render } from 'lit-html';
import { BaseElement } from 'common/';
import { isTrue } from 'core/utils';
class BasePageElement extends BaseElement {
public pageTitle: string = "";
public pageTitle: string = '';
@attr hidetitle: string;
@attr customtitle: string;
constructor(options: OptionType) {
@@ -18,9 +18,7 @@ class BasePageElement extends BaseElement {
public renderTitle = () => {
if (!isTrue(this.hidetitle)) {
return html`<div class="page --title">
${this.customtitle ? this.customtitle : this.pageTitle}
</div>`;
return html`<div class="page --title">${this.customtitle ? this.customtitle : this.pageTitle}</div>`;
}
return html``;
};
@@ -28,7 +26,7 @@ class BasePageElement extends BaseElement {
update = (): void => {
const _render = () => html` ${this.renderTitle()} ${this.render()} `;
render(_render(), this);
this.bindEvents("app-action");
this.bindEvents('app-action');
this.updateCallback();
};

View File

@@ -1 +1 @@
export { default as BasePageElement } from "./BasePageElement/BasePageElement";
export { default as BasePageElement } from './BasePageElement/BasePageElement';

View File

@@ -1,10 +1,10 @@
import { attr, controller, target } from "@github/catalyst";
import { findMethod, firstUpper } from "core/utils";
import { html } from "lit-html";
import randomId from "core/utils/random-id";
import validator from "validator";
import { validatorErrors } from "core/constants";
import { BaseComponentElement } from "common/";
import { attr, controller, target } from '@github/catalyst';
import { findMethod, firstUpper } from 'core/utils';
import { html } from 'lit-html';
import randomId from 'core/utils/random-id';
import validator from 'validator';
import { validatorErrors } from 'core/constants';
import { BaseComponentElement } from 'common/';
@controller
class AppDropdownElement extends BaseComponentElement {
@@ -13,8 +13,8 @@ class AppDropdownElement extends BaseComponentElement {
@attr rules: string;
@target main: HTMLElement;
@target inp: HTMLElement;
@attr displaykey: string = "name";
@attr valuekey: string = "id";
@attr displaykey: string = 'name';
@attr valuekey: string = 'id';
@attr fetch: string;
fetchFunc: any;
@@ -37,7 +37,7 @@ class AppDropdownElement extends BaseComponentElement {
super();
}
getItems = async (options?: any): Promise<void> => {
if (typeof this.fetchFunc !== "function") return;
if (typeof this.fetchFunc !== 'function') return;
try {
const response = await this.fetchFunc(options);
this.setItems(response);
@@ -76,7 +76,7 @@ class AppDropdownElement extends BaseComponentElement {
get optionValues() {
let values = [];
this.inp.childNodes.forEach((item: HTMLElement) => {
const value = item.getAttribute("value");
const value = item.getAttribute('value');
const name = item.innerText;
values.push({ name, value });
});
@@ -104,30 +104,27 @@ class AppDropdownElement extends BaseComponentElement {
}
get required(): boolean {
return this.rules.includes("required");
return this.rules.includes('required');
}
validate(): boolean {
let _return = true;
const rules = this.rules?.split("|").filter((a) => a);
const rules = this.rules?.split('|').filter((a) => a);
const value = (this.inp as HTMLSelectElement)?.value;
rules
.slice()
.reverse()
.forEach((rule) => {
let valid = true;
if (rule == "required") {
if (value === "") valid = false;
if (rule == 'required') {
if (value === '') valid = false;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll(
"{- name}",
firstUpper(this.name?.toString())
);
const error = validatorErrors[rule]?.replaceAll('{- name}', firstUpper(this.name?.toString()));
_return = false;
this.error = error;
}
@@ -153,7 +150,7 @@ class AppDropdownElement extends BaseComponentElement {
};
itemSelected = (e) => {
const value = (e.target as HTMLSpanElement).getAttribute("data-value");
const value = (e.target as HTMLSpanElement).getAttribute('data-value');
this.value = value;
this.isOpen = false;
};
@@ -163,26 +160,13 @@ class AppDropdownElement extends BaseComponentElement {
}
render = () => {
const {
label,
error,
errorMessage,
isOpen,
searchPhrase,
items,
selectedItem,
displaykey,
valuekey,
} = this;
const { label, error, errorMessage, isOpen, searchPhrase, items, selectedItem, displaykey, valuekey } = this;
console.log(isOpen);
const renderItem = (item) => {
return html` <li
class="dropdown-custom-listitem ${selectedItem?.[valuekey] ==
item[valuekey]
? "--selected"
: ""}"
class="dropdown-custom-listitem ${selectedItem?.[valuekey] == item[valuekey] ? '--selected' : ''}"
app-action="click:app-dropdown#itemSelected"
data-value="${item[valuekey]}"
>
@@ -198,19 +182,9 @@ class AppDropdownElement extends BaseComponentElement {
<div>
<label app-action="click:app-dropdown#openDropdown">
${label ? html`<div>${label}</div>` : html``}
<div
class="dropdown-custom"
app-action="click:app-dropdown#stopPropagation"
>
<div
class="dropdown-custom-top"
app-action="click:app-dropdown#toggleDropdown"
>
<span class="dropdown-custom-fieldname"
>${selectedItem
? selectedItem[displaykey]
: "Select"}</span
>
<div class="dropdown-custom" app-action="click:app-dropdown#stopPropagation">
<div class="dropdown-custom-top" app-action="click:app-dropdown#toggleDropdown">
<span class="dropdown-custom-fieldname">${selectedItem ? selectedItem[displaykey] : 'Select'}</span>
</div>
${isOpen
? html`
@@ -229,9 +203,7 @@ class AppDropdownElement extends BaseComponentElement {
`
: html``}
</div>
${error
? html` <div class="h5 text-red">${errorMessage}</div>`
: html``}
${error ? html` <div class="h5 text-red">${errorMessage}</div>` : html``}
</label>
</div>
`;

View File

@@ -1,9 +1,9 @@
import { attr, controller, target } from "@github/catalyst";
import { html, TemplateResult, unsafeHTML } from "lit-html";
import { BaseComponentElement } from "common/";
import { AppDropdownElement } from "components/app-dropdown/AppDropdownElement";
import { InputFieldElement } from "components/input-field/InputFieldElement";
import { findMethod, isTrue, querys } from "core/utils";
import { attr, controller, target } from '@github/catalyst';
import { html, TemplateResult, unsafeHTML } from 'lit-html';
import { BaseComponentElement } from 'common/';
import { AppDropdownElement } from 'components/app-dropdown/AppDropdownElement';
import { InputFieldElement } from 'components/input-field/InputFieldElement';
import { findMethod, isTrue, querys } from 'core/utils';
@controller
class AppFormElement extends BaseComponentElement {
@@ -58,7 +58,7 @@ class AppFormElement extends BaseComponentElement {
} else if (this.routerService?.canGoBack) {
this.routerService?.goBack();
} else {
this.routerService?.goTo("/");
this.routerService?.goTo('/');
}
};
@@ -86,7 +86,7 @@ class AppFormElement extends BaseComponentElement {
}
elementConnected = (): void => {
const _template = document.createElement("template");
const _template = document.createElement('template');
const _slot = this.innerHTML;
_template.innerHTML = _slot;
this.innerHTML = null;
@@ -110,24 +110,14 @@ class AppFormElement extends BaseComponentElement {
};
const renderCancel = (hasCancel: boolean) => {
if (hasCancel) {
return html`<button
type="button"
app-action="click:app-form#goBack"
>
Cancel
</button>`;
return html`<button type="button" app-action="click:app-form#goBack">Cancel</button>`;
}
return html``;
};
return html`<form
app-action="submit:app-form#onSubmit"
data-target="app-form.formElement"
>
return html`<form app-action="submit:app-form#onSubmit" data-target="app-form.formElement">
<slot data-target="app-form.innerSlot"></slot>
${renderError(this.error)}${renderSubmit(
this.isValid
)}${renderCancel(isTrue(this.hasCancel))}
${renderError(this.error)}${renderSubmit(this.isValid)}${renderCancel(isTrue(this.hasCancel))}
</form>`;
};
}

View File

@@ -1,9 +1,9 @@
import { attr, controller, target } from "@github/catalyst";
import { isTrue } from "core/utils";
import { html, TemplateResult } from "lit-html";
import { AppMainElement } from "components/app-main/AppMainElement";
import { RouterService } from "core/services";
import { BaseComponentElement } from "common/";
import { attr, controller, target } from '@github/catalyst';
import { isTrue } from 'core/utils';
import { html, TemplateResult } from 'lit-html';
import { AppMainElement } from 'components/app-main/AppMainElement';
import { RouterService } from 'core/services';
import { BaseComponentElement } from 'common/';
@controller
class AppLinkElement extends BaseComponentElement {
@@ -23,13 +23,13 @@ class AppLinkElement extends BaseComponentElement {
}
this.update();
if (isTrue(this.goBack)) {
this.appMain.addEventListener("routechanged", this.update);
this.appMain.addEventListener('routechanged', this.update);
}
};
elementDisconnected = (appMain: AppMainElement): void => {
if (isTrue(this.goBack)) {
appMain?.removeEventListener("routechanged", this.update);
appMain?.removeEventListener('routechanged', this.update);
}
};
@@ -52,12 +52,7 @@ class AppLinkElement extends BaseComponentElement {
render = (): TemplateResult => {
return html`${this.disabled
? html`<a
class="btn btn-link btn-disabled"
data-target="app-link.main"
style="color:grey"
>${this.title}</a
>`
? html`<a class="btn btn-link btn-disabled" data-target="app-link.main" style="color:grey">${this.title}</a>`
: html`<a
class="btn btn-link"
data-target="app-link.main"

View File

@@ -1,6 +1,6 @@
import { controller, target } from "@github/catalyst";
import { html } from "lit-html";
import { BaseComponentElement } from "common/";
import { controller, target } from '@github/catalyst';
import { html } from 'lit-html';
import { BaseComponentElement } from 'common/';
@controller
class AppLoaderElement extends BaseComponentElement {

View File

@@ -1,9 +1,9 @@
import { controller, target } from "@github/catalyst";
import { AppService, HttpClient, RouterService } from "core/services";
import { AuthStore } from "core/store";
import { AppModalElement, AppRootElement } from "components/";
import { closest } from "core/utils";
import { AppLoaderElement } from "components/app-loader/AppLoaderElement";
import { controller, target } from '@github/catalyst';
import { AppService, HttpClient, RouterService } from 'core/services';
import { AuthStore } from 'core/store';
import { AppModalElement, AppRootElement } from 'components/';
import { closest } from 'core/utils';
import { AppLoaderElement } from 'components/app-loader/AppLoaderElement';
@controller
class AppMainElement extends HTMLElement {
@@ -16,9 +16,9 @@ class AppMainElement extends HTMLElement {
@target appLoader: AppLoaderElement;
@closest appMain: AppMainElement;
public domEvents: any = {
routechanged: new Event("routechanged"),
tokenchange: new Event("tokenchange"),
walletupdate: new Event("walletupdate"),
routechanged: new Event('routechanged'),
tokenchange: new Event('tokenchange'),
walletupdate: new Event('walletupdate'),
};
constructor() {
@@ -34,69 +34,69 @@ class AppMainElement extends HTMLElement {
this.authStore = new AuthStore(this, this.appService);
this.routerService.setRoutes([
{
path: "/",
component: "home-page",
layout: "menu-layout",
path: '/',
component: 'home-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: "/home",
component: "home-page",
layout: "menu-layout",
path: '/home',
component: 'home-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: "/history",
component: "history-page",
layout: "menu-layout",
path: '/history',
component: 'history-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: "/wallet",
component: "history-page",
layout: "menu-layout",
path: '/wallet',
component: 'history-page',
layout: 'menu-layout',
middleware: this.isAuth,
children: [
{
path: "/all",
component: "wallet-list",
layout: "menu-layout",
path: '/all',
component: 'wallet-list',
layout: 'menu-layout',
},
{
path: "/:walletId",
component: "wallet-page",
layout: "menu-layout",
path: '/:walletId',
component: 'wallet-page',
layout: 'menu-layout',
},
],
},
{
path: "/register",
component: "register-page",
layout: "initial-layout",
path: '/register',
component: 'register-page',
layout: 'initial-layout',
},
{
path: "/login",
component: "login-page",
layout: "initial-layout",
path: '/login',
component: 'login-page',
layout: 'initial-layout',
},
{
path: "/unauthorized",
component: "login-page",
layout: "initial-layout",
path: '/unauthorized',
component: 'login-page',
layout: 'initial-layout',
},
{
path: "/token-expired",
component: "login-page",
layout: "initial-layout",
path: '/token-expired',
component: 'login-page',
layout: 'initial-layout',
},
{
path: "/not-found",
component: "not-found",
layout: "initial-layout",
path: '/not-found',
component: 'not-found',
layout: 'initial-layout',
},
{
path: "/logout",
component: "logout-page",
path: '/logout',
component: 'logout-page',
},
]);
this.routerService.init();
@@ -104,14 +104,14 @@ class AppMainElement extends HTMLElement {
middleAuth = () => {
if (!this.isAuth) {
this.routerService.goTo("/unauthorized");
this.routerService.goTo('/unauthorized');
return true;
}
};
createModal = (element: string) => {
this.closeModal();
this.appMain.addEventListener("routechanged", this.closeModal);
this.appMain.addEventListener('routechanged', this.closeModal);
const _appModal = this.createAppModal();
const _modalContent = this.createModalContent(element);
@@ -132,38 +132,38 @@ class AppMainElement extends HTMLElement {
};
private createAppModal = () => {
const _appModal = document.createElement("app-modal");
_appModal.setAttribute("data-target", "app-main.appModal");
const _appModal = document.createElement('app-modal');
_appModal.setAttribute('data-target', 'app-main.appModal');
return _appModal;
};
private createLoader = () => {
const _loader = document.createElement("app-loader");
_loader.setAttribute("data-target", "app-main.appLoader");
const _loader = document.createElement('app-loader');
_loader.setAttribute('data-target', 'app-main.appLoader');
this.appendChild(_loader);
};
private createModalContent = (element: string) => {
const _modalElement = document.createElement(element);
const _divEl = document.createElement("div");
_modalElement.setAttribute("data-target", "app-modal.modalElement");
_divEl.setAttribute("data-target", "app-modal.modalContent");
_divEl.setAttribute("data-action", "click:app-main#preventClosing");
const _divEl = document.createElement('div');
_modalElement.setAttribute('data-target', 'app-modal.modalElement');
_divEl.setAttribute('data-target', 'app-modal.modalContent');
_divEl.setAttribute('data-action', 'click:app-main#preventClosing');
_divEl.appendChild(_modalElement);
return _divEl;
};
private createModalOverlay = () => {
const _divOverlay = document.createElement("div");
_divOverlay.setAttribute("data-target", "app-modal.modalOverlay");
_divOverlay.setAttribute("data-action", "click:app-main#closeModal");
const _divOverlay = document.createElement('div');
_divOverlay.setAttribute('data-target', 'app-modal.modalOverlay');
_divOverlay.setAttribute('data-action', 'click:app-main#closeModal');
return _divOverlay;
};
private createMainRoot = () => {
if (this.mainRoot) this.removeChild(this.mainRoot);
const _mainRoot = document.createElement("app-root");
_mainRoot.setAttribute("data-target", "app-main.mainRoot");
const _mainRoot = document.createElement('app-root');
_mainRoot.setAttribute('data-target', 'app-main.mainRoot');
this.appendChild(_mainRoot);
return _mainRoot;
};
@@ -174,7 +174,7 @@ class AppMainElement extends HTMLElement {
closeModal = () => {
if (this.appModal) this.removeChild(this.appModal);
this.appMain.removeEventListener("routechanged", this.closeModal);
this.appMain.removeEventListener('routechanged', this.closeModal);
};
isAuth = (): boolean => {

View File

@@ -1,9 +1,9 @@
import { controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { BaseComponentElement } from "common/";
import { AppMainElement } from "components/app-main/AppMainElement";
import { MenuItemElement } from "components/menu-item/MenuItemElement";
import { WalletService } from "services/";
import { controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { BaseComponentElement } from 'common/';
import { AppMainElement } from 'components/app-main/AppMainElement';
import { MenuItemElement } from 'components/menu-item/MenuItemElement';
import { WalletService } from 'services/';
@controller
class AppMenuElement extends BaseComponentElement {
@@ -21,13 +21,13 @@ class AppMenuElement extends BaseComponentElement {
this.getWallets();
}
this.update();
this.appMain.addEventListener("tokenchange", this.updateToken);
this.appMain.addEventListener("walletupdate", this.updateToken);
this.appMain.addEventListener('tokenchange', this.updateToken);
this.appMain.addEventListener('walletupdate', this.updateToken);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.updateToken);
appMain?.removeEventListener("walletupdate", this.updateToken);
appMain?.removeEventListener('tokenchange', this.updateToken);
appMain?.removeEventListener('walletupdate', this.updateToken);
};
getWallets = async (): Promise<void> => {
@@ -63,9 +63,7 @@ class AppMenuElement extends BaseComponentElement {
renderWallets = (): Array<TemplateResult> => {
if (this.isAuth && this.totalWallets > 0) {
return this.walletData.map(
(wallet) => html`<menu-item data-path="/wallet/${wallet.id}"
>${wallet.name}</menu-item
>`
(wallet) => html`<menu-item data-path="/wallet/${wallet.id}">${wallet.name}</menu-item>`
);
}
return null;
@@ -76,7 +74,7 @@ class AppMenuElement extends BaseComponentElement {
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("wallet-create");
this.appMain.createModal('wallet-create');
}
};
@@ -85,42 +83,26 @@ class AppMenuElement extends BaseComponentElement {
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("transaction-create");
this.appMain.createModal('transaction-create');
}
};
render = (): TemplateResult => {
const { isAuth, totalWallets, walletData } = this;
const regularMenu = (
path: string,
title: string,
action?: string
): TemplateResult => {
const regularMenu = (path: string, title: string, action?: string): TemplateResult => {
if (action) {
return html`
<menu-item data-path="${path}" data-customaction="${action}"
>${title}</menu-item
>
`;
return html` <menu-item data-path="${path}" data-customaction="${action}">${title}</menu-item> `;
}
return html`<menu-item data-path="${path}">${title}</menu-item>`;
};
const authMenu = (
path: string,
title: string,
action?: string
): TemplateResult => {
const authMenu = (path: string, title: string, action?: string): TemplateResult => {
if (isAuth) {
return regularMenu(path, title, action);
}
return html``;
};
const notAuthMenu = (
path: string,
title: string,
action?: string
): TemplateResult => {
const notAuthMenu = (path: string, title: string, action?: string): TemplateResult => {
if (!isAuth) {
return regularMenu(path, title, action);
}
@@ -129,33 +111,19 @@ class AppMenuElement extends BaseComponentElement {
const renderWallets = (wallets: Array<any>) => {
if (isAuth && totalWallets > 0) {
return html`<div class="menu-item divider"></div>
${wallets.map((wallet) =>
regularMenu(`/wallet/${wallet.id}`, wallet.name)
)}`;
${wallets.map((wallet) => regularMenu(`/wallet/${wallet.id}`, wallet.name))}`;
}
return html``;
};
const menuHeader = (title) =>
html`<div class="menu-item menu-header">${title}</div>`;
const menuHeader = (title) => html`<div class="menu-item menu-header">${title}</div>`;
return html`
<div data-target="app-menu.sidebar">
${menuHeader(__CONFIG__.appName)} ${regularMenu("/", "Home")}
${authMenu(
"/history",
"Transaction History",
"click:app-menu#modalTransaction"
)}
${authMenu(
"/wallet/all",
"My Wallets",
"click:app-menu#modalWallet"
)}
${renderWallets(walletData)}
${menuHeader(__CONFIG__.appName)} ${regularMenu('/', 'Home')}
${authMenu('/history', 'Transaction History', 'click:app-menu#modalTransaction')}
${authMenu('/wallet/all', 'My Wallets', 'click:app-menu#modalWallet')} ${renderWallets(walletData)}
<span class="menu-item divider"></span>
${authMenu("/logout", "Logout")}
${notAuthMenu("/login", "Login")}
${notAuthMenu("/register", "Register")}
${authMenu('/logout', 'Logout')} ${notAuthMenu('/login', 'Login')} ${notAuthMenu('/register', 'Register')}
</div>
`;
};

View File

@@ -1,5 +1,5 @@
import { controller, target } from "@github/catalyst";
import { BaseComponentElement } from "common/";
import { controller, target } from '@github/catalyst';
import { BaseComponentElement } from 'common/';
@controller
class AppModalElement extends BaseComponentElement {

View File

@@ -1,7 +1,7 @@
import { attr, controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { BaseComponentElement } from "common/";
import { CircleLoaderElement } from "components/circle-loader/CircleLoaderElement";
import { attr, controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { BaseComponentElement } from 'common/';
import { CircleLoaderElement } from 'components/circle-loader/CircleLoaderElement';
@controller
class AppPaginationElement extends BaseComponentElement {
@@ -106,9 +106,9 @@ class AppPaginationElement extends BaseComponentElement {
return html`<circle-loader></circle-loader>`;
} else {
if (items?.length > 0) {
return html`<div class="table">
return html`<table>
${items?.map((item) => renderItem(item))}
</div>`;
</table>`;
}
return html``;
}
@@ -120,18 +120,13 @@ class AppPaginationElement extends BaseComponentElement {
return html`
<div>
<button
class="btn btn-primary btn-squared ${page <= 1
? "disabled"
: ""}"
class="btn btn-primary btn-squared ${page <= 1 ? 'disabled' : ''}"
app-action="click:app-pagination#pageBack"
>
Prev
</button>
<button
class="btn btn-primary btn-squared ${page >=
pageRange
? "disabled"
: ""}"
class="btn btn-primary btn-squared ${page >= pageRange ? 'disabled' : ''}"
app-action="click:app-pagination#pageNext"
>
Next

View File

@@ -1,5 +1,5 @@
import { controller, target } from "@github/catalyst";
import { BaseComponentElement } from "common/";
import { controller, target } from '@github/catalyst';
import { BaseComponentElement } from 'common/';
@controller
class AppRootElement extends BaseComponentElement {

View File

@@ -1,5 +1,5 @@
import { controller } from "@github/catalyst";
import style from "styles/main.scss";
import { controller } from '@github/catalyst';
import style from 'styles/main.scss';
(function () {
const _shadow = new WeakMap();
@@ -8,13 +8,13 @@ import style from "styles/main.scss";
class AppShadowElement extends HTMLElement {
constructor() {
super();
_shadow.set(this, this.attachShadow({ mode: "closed" }));
_shadow.set(this, this.attachShadow({ mode: 'closed' }));
}
connectedCallback() {
const _root = _shadow.get(this);
const _appMain = document.createElement("app-main");
const _style = document.createElement("style");
const _appMain = document.createElement('app-main');
const _style = document.createElement('style');
_style.innerHTML = style;
_root.appendChild(_style);

View File

@@ -1,5 +1,5 @@
import { controller, target } from "@github/catalyst";
import { BaseComponentElement } from "common/";
import { controller, target } from '@github/catalyst';
import { BaseComponentElement } from 'common/';
@controller
class AppSlotElement extends BaseComponentElement {

View File

@@ -1,6 +1,6 @@
import { attr, controller } from "@github/catalyst";
import { html } from "lit-html";
import { BaseComponentElement } from "common/";
import { attr, controller } from '@github/catalyst';
import { html } from 'lit-html';
import { BaseComponentElement } from 'common/';
@controller
class CircleLoaderElement extends BaseComponentElement {
@@ -14,9 +14,7 @@ class CircleLoaderElement extends BaseComponentElement {
};
render = () => {
return html`<div
class="circle-loader ${this.size ? `-${this.size}` : ""}"
></div>`;
return html`<div class="circle-loader ${this.size ? `-${this.size}` : ''}"></div>`;
};
}

View File

@@ -1,17 +1,17 @@
export * from "./app-link/AppLinkElement";
export * from "./menu-item/MenuItemElement";
export * from "./app-pagination/AppPaginationElement";
export * from "./app-modal/AppModalElement";
export * from "./app-root/AppRootElement";
export * from "./app-slot/AppSlotElement";
export * from "./app-menu/AppMenuElement";
export * from "./input-field/InputFieldElement";
export * from "./app-dropdown/AppDropdownElement";
export * from "./app-loader/AppLoaderElement";
export * from "./circle-loader/CircleLoaderElement";
export * from "./app-form/AppFormElement";
export * from "./wallet-header/WalletHeaderElement";
export * from './app-link/AppLinkElement';
export * from './menu-item/MenuItemElement';
export * from './app-pagination/AppPaginationElement';
export * from './app-modal/AppModalElement';
export * from './app-root/AppRootElement';
export * from './app-slot/AppSlotElement';
export * from './app-menu/AppMenuElement';
export * from './input-field/InputFieldElement';
export * from './app-dropdown/AppDropdownElement';
export * from './app-loader/AppLoaderElement';
export * from './circle-loader/CircleLoaderElement';
export * from './app-form/AppFormElement';
export * from './wallet-header/WalletHeaderElement';
// LAST
export * from "./app-main/AppMainElement";
export * from "./app-shadow/AppShadowElement";
export * from './app-main/AppMainElement';
export * from './app-shadow/AppShadowElement';

View File

@@ -1,12 +1,12 @@
import { attr, controller, target } from "@github/catalyst";
import { closest, firstUpper } from "core/utils";
import { html, TemplateResult } from "lit-html";
import { RouterService } from "core/services";
import randomId from "core/utils/random-id";
import validator from "validator";
import { validatorErrors } from "core/constants";
import { BaseComponentElement } from "common/";
import { AppFormElement } from "components/app-form/AppFormElement";
import { attr, controller, target } from '@github/catalyst';
import { closest, firstUpper } from 'core/utils';
import { html, TemplateResult } from 'lit-html';
import { RouterService } from 'core/services';
import randomId from 'core/utils/random-id';
import validator from 'validator';
import { validatorErrors } from 'core/constants';
import { BaseComponentElement } from 'common/';
import { AppFormElement } from 'components/app-form/AppFormElement';
@controller
class InputFieldElement extends BaseComponentElement {
@@ -35,7 +35,7 @@ class InputFieldElement extends BaseComponentElement {
}
get required(): boolean {
return this.rules.includes("required");
return this.rules.includes('required');
}
get _value() {
@@ -44,25 +44,22 @@ class InputFieldElement extends BaseComponentElement {
validate = (): boolean => {
let _return = true;
const rules = this.rules?.split("|").filter((a) => a);
const rules = this.rules?.split('|').filter((a) => a);
const value = (this.inp as HTMLInputElement)?.value;
rules
.slice()
.reverse()
.forEach((rule) => {
let valid = true;
if (rule == "required") {
if (value === "") valid = false;
if (rule == 'required') {
if (value === '') valid = false;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll(
"{- name}",
firstUpper(this.name?.toString())
);
const error = validatorErrors[rule]?.replaceAll('{- name}', firstUpper(this.name?.toString()));
_return = false;
this.error = error;
}
@@ -90,9 +87,7 @@ class InputFieldElement extends BaseComponentElement {
render = (): TemplateResult => {
const renderMessage = (label: string) => {
if (this.label) {
return html`<label for="${this.randId}"
>${this.label}${this.required ? " (*)" : ""}</label
>`;
return html`<label for="${this.randId}">${this.label}${this.required ? ' (*)' : ''}</label>`;
}
return html``;
};
@@ -116,8 +111,7 @@ class InputFieldElement extends BaseComponentElement {
};
return html`<div class="input-main" data-target="input-field.main">
${renderMessage(this.label)} ${renderInput(this.type)}
${renderError(this.displayError, this.error)}
${renderMessage(this.label)} ${renderInput(this.type)} ${renderError(this.displayError, this.error)}
</div>`;
};
}

View File

@@ -1,7 +1,7 @@
import { attr, controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { AppMainElement } from "components/app-main/AppMainElement";
import { BaseComponentElement } from "common/";
import { attr, controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { AppMainElement } from 'components/app-main/AppMainElement';
import { BaseComponentElement } from 'common/';
@controller
class MenuItemElement extends BaseComponentElement {
@@ -21,11 +21,11 @@ class MenuItemElement extends BaseComponentElement {
this.title = _slottedText;
}
this.update();
this.appMain.addEventListener("routechanged", this.update);
this.appMain.addEventListener('routechanged', this.update);
};
public elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("routechanged", this.update);
appMain?.removeEventListener('routechanged', this.update);
};
get current(): boolean {
@@ -34,18 +34,10 @@ class MenuItemElement extends BaseComponentElement {
render = (): TemplateResult => {
return html`
<div
class="${this.current ? "selected " : ""}menu-item"
data-target="menu-item.itemEl"
>
<div class="${this.current ? 'selected ' : ''}menu-item" data-target="menu-item.itemEl">
<app-link data-to="${this.path}">${this.title}</app-link>
${this.customaction
? html`<div
data-target="menu-item.customButton"
app-action="${this.customaction}"
>
+
</div>`
? html`<div data-target="menu-item.customButton" app-action="${this.customaction}">+</div>`
: html``}
</div>
`;

View File

@@ -1,8 +1,8 @@
import { attr, controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { BaseComponentElement } from "common/";
import { CircleLoaderElement } from "components/circle-loader/CircleLoaderElement";
import { findMethod } from "core/utils";
import { attr, controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { BaseComponentElement } from 'common/';
import { CircleLoaderElement } from 'components/circle-loader/CircleLoaderElement';
import { findMethod } from 'core/utils';
@controller
class WalletHeaderElement extends BaseComponentElement {
@@ -52,15 +52,11 @@ class WalletHeaderElement extends BaseComponentElement {
if (this.loader && this.loader.loading) {
return html`<circle-loader></circle-loader>`;
}
return html`${renderItem(
"Last Month",
lastMonth,
currency
)}${renderItem(
"Current Balance",
return html`${renderItem('Last Month', lastMonth, currency)}${renderItem(
'Current Balance',
currentBalance,
currency
)}${renderItem("Next Month", nextMonth, currency)}`;
)}${renderItem('Next Month', nextMonth, currency)}`;
};
return html`<div>${renderHeader()}</div>`;

View File

@@ -1 +1 @@
export * from "./validatorErrors";
export * from './validatorErrors';

View File

@@ -1,4 +1,4 @@
export const validatorErrors = {
required: "{- name} is required.",
isEmail: "{- name} needs to be email format.",
required: '{- name} is required.',
isEmail: '{- name} needs to be email format.',
};

View File

@@ -1,37 +1,22 @@
import { AppMainElement } from "components/";
import { HttpClient } from "..";
import { AppMainElement } from 'components/';
import { HttpClient } from '..';
class AppService {
constructor(
public appMain: AppMainElement,
public httpClient: HttpClient
) {}
constructor(public appMain: AppMainElement, public httpClient: HttpClient) {}
post = async (
url: string,
data: Object,
headersParam: HeadersInit
): Promise<any> => {
post = async (url: string, data: Object, headersParam: HeadersInit): Promise<any> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,
};
try {
this?.appMain?.appLoader?.start?.();
const response = await this.httpClient.post(
url,
data,
headersParam
);
const response = await this.httpClient.post(url, data, headersParam);
this?.appMain?.appLoader?.stop?.();
if (
response?.statusCode == 400 ||
response?.statusCode == 500 ||
response?.statusCode == 401
) {
if (response?.statusCode == 400 || response?.statusCode == 500 || response?.statusCode == 401) {
if (response?.statusCode == 401) {
this.appMain.authStore.token = null;
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
}
throw response;
}
@@ -42,11 +27,7 @@ class AppService {
}
};
put = async (
url: string,
data: Object,
headersParam: HeadersInit
): Promise<any> => {
put = async (url: string, data: Object, headersParam: HeadersInit): Promise<any> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,
@@ -55,14 +36,10 @@ class AppService {
this?.appMain?.appLoader?.start?.();
const response = await this.httpClient.put(url, data, headersParam);
this?.appMain?.appLoader?.stop?.();
if (
response?.statusCode == 400 ||
response?.statusCode == 500 ||
response?.statusCode == 401
) {
if (response?.statusCode == 400 || response?.statusCode == 500 || response?.statusCode == 401) {
if (response?.statusCode == 401) {
this.appMain.authStore.token = null;
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
}
throw response;
}
@@ -73,31 +50,19 @@ class AppService {
}
};
delete = async (
url: string,
data: Object,
headersParam: HeadersInit
): Promise<any> => {
delete = async (url: string, data: Object, headersParam: HeadersInit): Promise<any> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,
};
try {
this?.appMain?.appLoader?.start?.();
const response = await this.httpClient.delete(
url,
data,
headersParam
);
const response = await this.httpClient.delete(url, data, headersParam);
this?.appMain?.appLoader?.stop?.();
if (
response?.statusCode == 400 ||
response?.statusCode == 500 ||
response?.statusCode == 401
) {
if (response?.statusCode == 400 || response?.statusCode == 500 || response?.statusCode == 401) {
if (response?.statusCode == 401) {
this.appMain.authStore.token = null;
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
}
throw response;
}
@@ -108,30 +73,18 @@ class AppService {
}
};
get = async (
url: string,
params: Object,
headersParam: HeadersInit
): Promise<any> => {
get = async (url: string, params: Object, headersParam: HeadersInit): Promise<any> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,
};
try {
this?.appMain?.appLoader?.start?.();
const response = await this.httpClient.get(
url,
params,
headersParam
);
const response = await this.httpClient.get(url, params, headersParam);
this?.appMain?.appLoader?.stop?.();
if (
response?.statusCode == 400 ||
response?.statusCode == 500 ||
response?.statusCode == 401
) {
if (response?.statusCode == 400 || response?.statusCode == 500 || response?.statusCode == 401) {
if (response?.statusCode == 401) {
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
this.appMain.authStore.token = null;
}
throw response;

View File

@@ -1,4 +1,4 @@
import { AppService } from "core/services";
import { AppService } from 'core/services';
class BaseService {
constructor(public endpoint: string, public appService: AppService) {}

View File

@@ -1,9 +1,7 @@
class HttpClient {
private url: string;
constructor() {
this.url = `${__CONFIG__.ssl ? "https" : "http"}://${
__CONFIG__.apiUrl
}/${__CONFIG__.apiVersion}`;
this.url = `${__CONFIG__.ssl ? 'https' : 'http'}://${__CONFIG__.apiUrl}/${__CONFIG__.apiVersion}`;
}
post(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
@@ -13,10 +11,10 @@ class HttpClient {
body = data;
} else {
body = JSON.stringify(data);
headers.append("Content-Type", "application/json");
headers.append('Content-Type', 'application/json');
}
let options: OptionsType = {
method: "POST",
method: 'POST',
headers: headers,
body: body,
};
@@ -27,9 +25,9 @@ class HttpClient {
put(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append("Content-Type", "application/json");
headers.append('Content-Type', 'application/json');
let options: OptionsType = {
method: "PUT",
method: 'PUT',
headers: headers,
body: JSON.stringify(data),
};
@@ -40,9 +38,9 @@ class HttpClient {
delete(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append("Content-Type", "application/json");
headers.append('Content-Type', 'application/json');
let options: OptionsType = {
method: "DELETE",
method: 'DELETE',
headers: headers,
body: JSON.stringify(data),
};
@@ -54,18 +52,15 @@ class HttpClient {
get(url: string, params: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
let options: OptionsType = {
method: "GET",
method: 'GET',
headers: headers,
};
let paramsPath: string = "";
let paramsPath: string = '';
if (params) {
let urlParams = new URLSearchParams(Object.entries(params));
paramsPath = "?" + urlParams;
paramsPath = '?' + urlParams;
}
const req: Request = new Request(
resolveUrl(this.url, url + paramsPath),
options
);
const req: Request = new Request(resolveUrl(this.url, url + paramsPath), options);
return createRequest(req);
}
@@ -84,7 +79,7 @@ async function createRequest(request: Request): Promise<Response> {
) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
if (response.headers.get("Content-Type") !== null) {
if (response.headers.get('Content-Type') !== null) {
let newResponse: Response = await createResponse(response);
return newResponse;
}
@@ -93,9 +88,9 @@ async function createRequest(request: Request): Promise<Response> {
}
async function createResponse(response: Response): Promise<any> {
const type: string = response.headers.get("Content-Type");
const type: string = response.headers.get('Content-Type');
const body = (): Promise<any> => {
if (type.indexOf("application/json") !== -1) {
if (type.indexOf('application/json') !== -1) {
return response.json();
}
return response.text();
@@ -105,14 +100,14 @@ async function createResponse(response: Response): Promise<any> {
}
function resolveUrl(url: string, path: string): string {
if (path.includes("http") || path.includes("://")) {
if (path.includes('http') || path.includes('://')) {
return path;
}
const fixedPath = path
.split("/")
.split('/')
.filter((i) => i)
.join("/");
const urlWithPath = `${url.endsWith("/") ? url : `${url}/`}${fixedPath}`;
.join('/');
const urlWithPath = `${url.endsWith('/') ? url : `${url}/`}${fixedPath}`;
return urlWithPath;
}

View File

@@ -1,4 +1,4 @@
export { default as HttpClient } from "./http-service/HttpClient";
export { default as BaseService } from "./base-service/BaseService";
export { default as RouterService } from "./router-service/RouterService";
export { default as AppService } from "./app-service/AppService";
export { default as HttpClient } from './http-service/HttpClient';
export { default as BaseService } from './base-service/BaseService';
export { default as RouterService } from './router-service/RouterService';
export { default as AppService } from './app-service/AppService';

View File

@@ -1,13 +1,10 @@
import { BaseLayoutElement } from "common/layouts";
import { AppMainElement } from "components/";
import { BaseLayoutElement } from 'common/layouts';
import { AppMainElement } from 'components/';
class RouterService {
private historyStack: Array<RouteState> = [];
private _routes: Array<RouteState> = [];
constructor(
private appMain: AppMainElement,
private mainRoot: ShadowRoot | HTMLElement
) {}
constructor(private appMain: AppMainElement, private mainRoot: ShadowRoot | HTMLElement) {}
get routerState(): RouteState {
const historyLen = this.historyStack?.length;
@@ -29,24 +26,14 @@ class RouterService {
public setRoutes = (routes: Array<any>): void => {
if (!Array.isArray(this._routes)) this._routes = [];
routes.forEach((route) => {
const { path, component, data, layout, middleware, children } =
route;
const _pathArr = path?.split?.("/").filter((a) => a);
let newPath = ["", ..._pathArr].join("/");
if (newPath == "") newPath = "/";
const _routeState: RouteState = new RouteState(
newPath,
component,
data,
layout,
middleware
);
const { path, component, data, layout, middleware, children } = route;
const _pathArr = path?.split?.('/').filter((a) => a);
let newPath = ['', ..._pathArr].join('/');
if (newPath == '') newPath = '/';
const _routeState: RouteState = new RouteState(newPath, component, data, layout, middleware);
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child) => {
const _childState: RouteState = this.createChildState(
child,
route
);
const _childState: RouteState = this.createChildState(child, route);
this._routes?.push(_childState);
});
}
@@ -61,18 +48,13 @@ class RouterService {
const _mainRoot = this.mainRoot;
let route: RouteState = this.routerState;
if (route?.middleware) {
if (
!(
typeof route?.middleware == "function" && route.middleware()
) ||
route.middleware === false
) {
return this.goTo("/unauthorized");
if (!(typeof route?.middleware == 'function' && route.middleware()) || route.middleware === false) {
return this.goTo('/unauthorized');
}
}
if (
path == route?.path ||
route?.path == "/not-found" ||
route?.path == '/not-found' ||
(hasDynamic && this?._routes?.[_dynamicIndex]?.path == route?.path)
) {
let changed: boolean = false;
@@ -85,33 +67,15 @@ class RouterService {
) {
changed = true;
child.setElement(route.component);
} else if (
route.layout &&
route.layout.toUpperCase() !== child.tagName
) {
} else if (route.layout && route.layout.toUpperCase() !== child.tagName) {
changed = true;
const _newElement = document.createElement(
route.layout
);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
const _newElement = document.createElement(route.layout);
_newElement.setAttribute('data-target', 'app-root.rootElement');
_mainRoot.replaceChild(_newElement, child);
(_newElement as BaseLayoutElement).setElement(
route.component
);
} else if (
!route.layout &&
child.tagName !== route.component
) {
const _newElement = document.createElement(
route.component
);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
(_newElement as BaseLayoutElement).setElement(route.component);
} else if (!route.layout && child.tagName !== route.component) {
const _newElement = document.createElement(route.component);
_newElement.setAttribute('data-target', 'app-root.rootElement');
changed = true;
_mainRoot.replaceChild(_newElement, child);
}
@@ -120,27 +84,18 @@ class RouterService {
if (route.layout) {
changed = true;
const _newElement = document.createElement(route.layout);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
_newElement.setAttribute('data-target', 'app-root.rootElement');
_mainRoot.appendChild(_newElement);
(_newElement as BaseLayoutElement).setElement(
route.component
);
(_newElement as BaseLayoutElement).setElement(route.component);
} else {
const _newElement = document.createElement(route.component);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
_newElement.setAttribute('data-target', 'app-root.rootElement');
changed = true;
_mainRoot.appendChild(_newElement);
}
}
} else {
const [isDynamic, _dynamicIndex, dynamicProps] =
this.hasDynamicPath(path);
const [isDynamic, _dynamicIndex, dynamicProps] = this.hasDynamicPath(path);
let newRoute: RouteState;
if (isDynamic && _dynamicIndex !== -1) {
newRoute = this._routes[_dynamicIndex];
@@ -158,18 +113,14 @@ class RouterService {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const currentPath = window.location.pathname;
if (path == currentPath) return;
if (path.includes(":") && data) {
if (path.includes(':') && data) {
path = resolvePath(path, data);
}
const _index = this._routes.findIndex((route) => route.path === path);
const _indexOfEmpty = this._routes.findIndex(
(route) => route.path === "/not-found"
);
const [isDynamic, _dynamicIndex, dynamicProps] =
this.hasDynamicPath(path);
const _indexOfEmpty = this._routes.findIndex((route) => route.path === '/not-found');
const [isDynamic, _dynamicIndex, dynamicProps] = this.hasDynamicPath(path);
if (isDynamic) {
const [isCurrentDynamic, currIndex] =
this.hasDynamicPath(currentPath);
const [isCurrentDynamic, currIndex] = this.hasDynamicPath(currentPath);
if (path == currentPath) return;
}
let newRoute: RouteState;
@@ -179,7 +130,7 @@ class RouterService {
} else if (_index === -1 && _indexOfEmpty !== -1) {
newRoute = this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
newRoute = new RouteState("/not-found", "not-found");
newRoute = new RouteState('/not-found', 'not-found');
} else {
newRoute = this._routes[_index];
}
@@ -187,7 +138,7 @@ class RouterService {
this.historyStack.push(newRoute);
const url = new URL(window.location.toString());
url.pathname = path;
window.history.pushState({}, "", url.toString());
window.history.pushState({}, '', url.toString());
this.update();
};
@@ -198,7 +149,7 @@ class RouterService {
const nextRoute = this.historyStack[lenHistory - 2];
const url = new URL(window.location.toString());
url.pathname = nextRoute.path;
window.history.pushState({}, "", url.toString());
window.history.pushState({}, '', url.toString());
this.historyStack.pop();
}
this.update();
@@ -213,7 +164,7 @@ class RouterService {
}
public init = (): void => {
window.addEventListener("popstate", () => {
window.addEventListener('popstate', () => {
this.historyStack.pop();
this.update();
});
@@ -223,13 +174,11 @@ class RouterService {
public findByPath = (): RouteState => {
const path = window.location.pathname;
const _index = this._routes.findIndex((route) => route.path === path);
const _indexOfEmpty = this._routes.findIndex(
(route) => route.path === "/not-found"
);
const _indexOfEmpty = this._routes.findIndex((route) => route.path === '/not-found');
if (_index === -1 && _indexOfEmpty !== -1) {
return this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
return new RouteState("/not-found", "not-found");
return new RouteState('/not-found', 'not-found');
}
return this._routes[_index];
};
@@ -243,23 +192,14 @@ class RouterService {
private createChildState = (child: any, parent: any): RouteState => {
const { path, middleware, layout, component, data, children } = child;
const _pathArr = path?.split?.("/").filter((a) => a);
const _parentArr = parent?.path?.split?.("/").filter((a) => a);
const newPath = ["", ..._parentArr, ..._pathArr].join("/");
const _child = new RouteState(
newPath,
component,
data,
layout,
middleware ? middleware : parent?.middleware
);
const _pathArr = path?.split?.('/').filter((a) => a);
const _parentArr = parent?.path?.split?.('/').filter((a) => a);
const newPath = ['', ..._parentArr, ..._pathArr].join('/');
const _child = new RouteState(newPath, component, data, layout, middleware ? middleware : parent?.middleware);
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child2) => {
const _childState: RouteState = this.createChildState(
child2,
_child
);
const _childState: RouteState = this.createChildState(child2, _child);
this._routes?.push(_childState);
});
}
@@ -267,7 +207,7 @@ class RouterService {
};
private hasDynamicPath = (path: string): [boolean, number, any] => {
const _pathArr = path.split("/").filter((a) => a);
const _pathArr = path.split('/').filter((a) => a);
let matchedIndex: number = 0;
let matched: boolean = false;
let dynamicProps: any = {};
@@ -277,18 +217,18 @@ class RouterService {
return;
}
if (path == route.path) {
matched = path?.includes(":") ? true : false;
matched = path?.includes(':') ? true : false;
matchedIndex = _routeId;
shouldSkip = true;
}
const _routeArr = route.path.split("/").filter((a) => a);
const _routeArr = route.path.split('/').filter((a) => a);
if (_pathArr.length === _routeArr.length) {
let pathMatches: number = 0;
let hasDynamic: boolean = false;
_pathArr.forEach((pathr, i) => {
if (pathr == _routeArr[i]) {
pathMatches++;
} else if (_routeArr[i].startsWith?.(":")) {
} else if (_routeArr[i].startsWith?.(':')) {
pathMatches++;
hasDynamic = true;
dynamicProps[_routeArr[i].substr(1)] = pathr;
@@ -326,17 +266,17 @@ type DynamicProp = {
function resolvePath(path: string, data: any): string {
const _pathArr = path
.split("/")
.split('/')
.filter((a) => a)
.map((pathPart) => {
if (pathPart.startsWith(":")) {
if (pathPart.startsWith(':')) {
pathPart = data?.[pathPart.substr(1)];
}
return pathPart;
});
let _return = ["", ..._pathArr].join("/");
if (_return == "") {
_return = "/";
let _return = ['', ..._pathArr].join('/');
if (_return == '') {
_return = '/';
}
return _return;
}

View File

@@ -1,25 +1,22 @@
import { AppMainElement } from "components/";
import { AppService } from "core/services";
import { isTrue } from "core/utils";
import { AuthService } from "services/";
import { AppMainElement } from 'components/';
import { AppService } from 'core/services';
import { isTrue } from 'core/utils';
import { AuthService } from 'services/';
class AuthStore {
private _token: string;
private _userDetails: UserDetails;
private authService: AuthService;
constructor(
private appMain: AppMainElement,
private appService: AppService
) {
const _token = localStorage.getItem("token");
constructor(private appMain: AppMainElement, private appService: AppService) {
const _token = localStorage.getItem('token');
if (_token) this.token = _token;
this.authService = new AuthService(this.appService);
this.checkToken(_token);
}
get token(): string {
if (this._token == "null") return null;
if (this._token == "undefined") return undefined;
if (this._token == 'null') return null;
if (this._token == 'undefined') return undefined;
return this._token;
}
@@ -29,7 +26,7 @@ class AuthStore {
console.log(token);
if (_changed) {
this._token = token;
localStorage.setItem("token", token);
localStorage.setItem('token', token);
this.appMain.dispatchEvent(this.appMain?.domEvents.tokenchange);
}
}
@@ -44,16 +41,16 @@ class AuthStore {
checkToken = async (token: string) => {
try {
if (token && token !== "null") {
if (token && token !== 'null') {
const response = await this.authService.checkToken({ token });
if (!(response && response.valid)) {
this.token = null;
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
}
}
} catch (err) {
this.token = null;
this.appMain.routerService.goTo("/token-expired");
this.appMain.routerService.goTo('/token-expired');
}
};
@@ -64,7 +61,7 @@ class AuthStore {
this.token = response.token;
} else {
this.token = null;
localStorage.removeItem("token");
localStorage.removeItem('token');
}
return response;
} catch (err) {
@@ -83,7 +80,7 @@ class AuthStore {
userLogout = (): void => {
this.token = null;
localStorage.removeItem("token");
localStorage.removeItem('token');
};
}

View File

@@ -1 +1 @@
export { default as AuthStore } from "./AuthStore";
export { default as AuthStore } from './AuthStore';

View File

@@ -1,4 +1,4 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function closest(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);

View File

@@ -1,11 +1,8 @@
import { AppMainElement } from "components/";
import { AppMainElement } from 'components/';
export default function findMethod(
actionString: string,
appMain: AppMainElement
): Function {
export default function findMethod(actionString: string, appMain: AppMainElement): Function {
if (actionString) {
const methodSep = actionString.lastIndexOf("#");
const methodSep = actionString.lastIndexOf('#');
const tag = actionString.slice(0, methodSep);
const method = actionString.slice(methodSep + 1);

View File

@@ -1,4 +1,4 @@
export default function firstUpper(s: string): string {
if (typeof s !== "string") return "";
if (typeof s !== 'string') return '';
return s.charAt(0).toUpperCase() + s.slice(1);
}

View File

@@ -1,9 +1,9 @@
export { default as toKebabCase } from "./toKebabCase";
export { default as update } from "./update-deco";
export { default as index } from "./index-deco";
export { default as closest } from "./closest-deco";
export { default as isTrue } from "./isTrue";
export { default as firstUpper } from "./first-upper";
export { default as query } from "./query-deco";
export { default as querys } from "./querys-deco";
export { default as findMethod } from "./find-method";
export { default as toKebabCase } from './toKebabCase';
export { default as update } from './update-deco';
export { default as index } from './index-deco';
export { default as closest } from './closest-deco';
export { default as isTrue } from './isTrue';
export { default as firstUpper } from './first-upper';
export { default as query } from './query-deco';
export { default as querys } from './querys-deco';
export { default as findMethod } from './find-method';

View File

@@ -1,3 +1,3 @@
export default function isTrue(text: string): boolean {
return text === "true";
return text === 'true';
}

View File

@@ -1,4 +1,4 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function query(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);

View File

@@ -1,4 +1,4 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function querys(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);
@@ -10,9 +10,6 @@ export default function querys(proto: Object, key: string): any {
});
}
function findQuerys(
element: HTMLElement,
key: string
): NodeListOf<HTMLElement> {
function findQuerys(element: HTMLElement, key: string): NodeListOf<HTMLElement> {
return element.querySelectorAll(key);
}

View File

@@ -1,3 +1,3 @@
export default function randomId(): string {
return "_" + Math.random().toString(36).substr(2, 5);
return '_' + Math.random().toString(36).substr(2, 5);
}

View File

@@ -1,6 +1,6 @@
export default function toKebabCase(text: string): string {
return text
.replace(/([a-z])([A-Z])/g, "$1-$2")
.replace(/\s+/g, "-")
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.toLowerCase();
}

View File

@@ -1,9 +1,9 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Wallet Web</title>
</head>
<body>

View File

@@ -1,3 +1,3 @@
import "layouts";
import "components";
import "pages";
import 'layouts';
import 'components';
import 'pages';

View File

@@ -1,2 +1,2 @@
export * from "./menu-layout/MenuLayoutElement";
export * from "./initial-layout/InitialLayoutElement";
export * from './menu-layout/MenuLayoutElement';
export * from './initial-layout/InitialLayoutElement';

View File

@@ -1,8 +1,8 @@
import { controller, target } from "@github/catalyst";
import { closest } from "core/utils";
import { html, TemplateResult } from "lit-html";
import { BaseLayoutElement } from "common/layouts";
import { AppMainElement } from "components/";
import { controller, target } from '@github/catalyst';
import { closest } from 'core/utils';
import { html, TemplateResult } from 'lit-html';
import { BaseLayoutElement } from 'common/layouts';
import { AppMainElement } from 'components/';
@controller
class InitialLayoutElement extends BaseLayoutElement {

View File

@@ -1,8 +1,8 @@
import { controller, target } from "@github/catalyst";
import { closest } from "core/utils";
import { html, TemplateResult } from "lit-html";
import { BaseLayoutElement } from "common/layouts";
import { AppMainElement } from "components/";
import { controller, target } from '@github/catalyst';
import { closest } from 'core/utils';
import { html, TemplateResult } from 'lit-html';
import { BaseLayoutElement } from 'common/layouts';
import { AppMainElement } from 'components/';
@controller
class MenuLayoutElement extends BaseLayoutElement {
@@ -15,18 +15,18 @@ class MenuLayoutElement extends BaseLayoutElement {
elementConnected = (): void => {
this.update();
this.appMain.addEventListener("tokenchange", this.updateAuth);
this.appMain.addEventListener("routechanged", this.updateAuth);
this.appMain.addEventListener('tokenchange', this.updateAuth);
this.appMain.addEventListener('routechanged', this.updateAuth);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.updateAuth);
appMain?.removeEventListener("routechanged", this.updateAuth);
appMain?.removeEventListener('tokenchange', this.updateAuth);
appMain?.removeEventListener('routechanged', this.updateAuth);
};
get isAuth(): boolean {
const _is = this.appMain?.routerService?.routerState?.middleware;
if (typeof _is == "function") {
if (typeof _is == 'function') {
return _is();
}
return !!_is;

View File

@@ -1,8 +1,8 @@
import { controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { TransactionsService } from "services/";
import { AppMainElement, AppPaginationElement } from "components/";
import { BasePageElement } from "common/";
import { controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { TransactionsService } from 'services/';
import { AppMainElement, AppPaginationElement } from 'components/';
import { BasePageElement } from 'common/';
@controller
class HistoryPageElement extends BasePageElement {
@@ -10,21 +10,19 @@ class HistoryPageElement extends BasePageElement {
@target pagination: AppPaginationElement;
constructor() {
super({
title: "Transaction History",
title: 'Transaction History',
});
}
elementConnected = (): void => {
this.transactionsService = new TransactionsService(
this.appMain?.appService
);
this.transactionsService = new TransactionsService(this.appMain?.appService);
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener("tokenchange", this.update);
this.appMain.addEventListener('tokenchange', this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
appMain?.removeEventListener('tokenchange', this.update);
};
getTransactions = async (options): Promise<any> => {
@@ -32,7 +30,7 @@ class HistoryPageElement extends BasePageElement {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options["walletId"] = walletId;
options['walletId'] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
@@ -45,17 +43,13 @@ class HistoryPageElement extends BasePageElement {
render = (): TemplateResult => {
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
return html`<span
>${this.routerService?.routerState?.data?.walletId}</span
>`;
return html`<span>${this.routerService?.routerState?.data?.walletId}</span>`;
}
return html``;
};
return html`<div>
${renderWallet()}
<app-pagination
data-target="history-page.pagination"
></app-pagination>
<app-pagination data-target="history-page.pagination"></app-pagination>
</div>`;
};
}

View File

@@ -1,8 +1,8 @@
import { controller, target } from "@github/catalyst";
import { html, TemplateResult, until } from "lit-html";
import { WalletService } from "services/";
import { AppMainElement, WalletHeaderElement } from "components/";
import { BasePageElement } from "common/";
import { controller, target } from '@github/catalyst';
import { html, TemplateResult, until } from 'lit-html';
import { WalletService } from 'services/';
import { AppMainElement, WalletHeaderElement } from 'components/';
import { BasePageElement } from 'common/';
@controller
class HomePageElement extends BasePageElement {
@@ -10,19 +10,19 @@ class HomePageElement extends BasePageElement {
private walletService: WalletService;
constructor() {
super({
title: "Home",
title: 'Home',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.update();
this.appMain.addEventListener("tokenchange", this.update);
this.appMain.addEventListener('tokenchange', this.update);
this.getBalance();
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
appMain?.removeEventListener('tokenchange', this.update);
};
getBalance = async (): Promise<void> => {
@@ -37,9 +37,9 @@ class HomePageElement extends BasePageElement {
setBalance = (header) => {
if (!this.walletHeader) return;
this.walletHeader.currency = header.currency;
this.walletHeader.currentBalance = header.currentBalance || "0";
this.walletHeader.lastMonth = header.lastMonth || "0";
this.walletHeader.nextMonth = header.nextMonth || "0";
this.walletHeader.currentBalance = header.currentBalance || '0';
this.walletHeader.lastMonth = header.lastMonth || '0';
this.walletHeader.nextMonth = header.nextMonth || '0';
};
openModal = (): void => {
@@ -47,7 +47,7 @@ class HomePageElement extends BasePageElement {
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("wallet-create");
this.appMain.createModal('wallet-create');
}
};

View File

@@ -1,10 +1,10 @@
export * from "./logout-page/LogoutPageElement";
export * from "./home-page/HomePageElement";
export * from "./register-page/RegisterPageElement";
export * from "./login-page/LoginPageElement";
export * from "./not-found/NotFoundElement";
export * from "./history-page/HistoryPageElement";
export * from "./wallet-list/WalletListElement";
export * from "./wallet-create/WalletCreateElement";
export * from "./transaction-create/TransactionCreateElement";
export * from "./wallet-page/WalletPageElement";
export * from './logout-page/LogoutPageElement';
export * from './home-page/HomePageElement';
export * from './register-page/RegisterPageElement';
export * from './login-page/LoginPageElement';
export * from './not-found/NotFoundElement';
export * from './history-page/HistoryPageElement';
export * from './wallet-list/WalletListElement';
export * from './wallet-create/WalletCreateElement';
export * from './transaction-create/TransactionCreateElement';
export * from './wallet-page/WalletPageElement';

View File

@@ -1,10 +1,10 @@
import { targets, controller, target } from "@github/catalyst";
import { targets, controller, target } from '@github/catalyst';
//import { html, TemplateResult } from "lit-html";
import { html, render, TemplateResult } from "lit-html";
import { AuthService } from "services/";
import { AppFormElement, InputFieldElement } from "components/";
import { RouterService } from "core/services";
import { BasePageElement } from "common/";
import { html, render, TemplateResult } from 'lit-html';
import { AuthService } from 'services/';
import { AppFormElement, InputFieldElement } from 'components/';
import { RouterService } from 'core/services';
import { BasePageElement } from 'common/';
@controller
class LoginPageElement extends BasePageElement {
@@ -13,7 +13,7 @@ class LoginPageElement extends BasePageElement {
authService: AuthService;
constructor() {
super({
title: "Login",
title: 'Login',
});
}
elementConnected = (): void => {
@@ -23,7 +23,7 @@ class LoginPageElement extends BasePageElement {
get emailInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "email") {
if (this.inputs[i]?.name == 'email') {
return this.inputs[i];
}
}
@@ -31,7 +31,7 @@ class LoginPageElement extends BasePageElement {
get passwordInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "password") {
if (this.inputs[i]?.name == 'password') {
return this.inputs[i];
}
}
@@ -51,12 +51,10 @@ class LoginPageElement extends BasePageElement {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userLogin(
this.values
);
const response = await this.appMain.authStore.userLogin(this.values);
if (response?.token) {
this.routerService.goTo("/");
this.routerService.goTo('/');
}
} catch (err) {
if (err?.errorCode == 400103) {
@@ -66,7 +64,7 @@ class LoginPageElement extends BasePageElement {
this.passwordInput.error = err?.message;
this.passwordInput.update();
} else {
this.appForm?.setError("Unable to log in!");
this.appForm?.setError('Unable to log in!');
}
}
};
@@ -82,10 +80,7 @@ class LoginPageElement extends BasePageElement {
render = (): TemplateResult => {
return html`
<app-form
data-custom="login-page#onSubmit"
data-target="login-page.appForm"
>
<app-form data-custom="login-page#onSubmit" data-target="login-page.appForm">
<input-field
data-type="email"
data-name="email"
@@ -103,10 +98,7 @@ class LoginPageElement extends BasePageElement {
</input-field>
</app-form>
<div>
<app-link
data-to="/register"
data-title="Create new account"
></app-link>
<app-link data-to="/register" data-title="Create new account"></app-link>
</div>
`;
};

View File

@@ -1,19 +1,19 @@
import { controller } from "@github/catalyst";
import { AuthService } from "services/";
import { BasePageElement } from "common/";
import { controller } from '@github/catalyst';
import { AuthService } from 'services/';
import { BasePageElement } from 'common/';
@controller
class LogoutPageElement extends BasePageElement {
authService: AuthService;
constructor() {
super({
title: "Logout",
title: 'Logout',
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.appMain?.authStore?.userLogout();
this.appMain?.routerService.goTo("/login");
this.appMain?.routerService.goTo('/login');
};
}

View File

@@ -1,12 +1,12 @@
import { controller } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { BasePageElement } from "common/";
import { controller } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { BasePageElement } from 'common/';
@controller
class NotFoundElement extends BasePageElement {
constructor() {
super({
title: "404 - Not Found",
title: '404 - Not Found',
});
}
elementConnected = (): void => {

View File

@@ -1,8 +1,8 @@
import { targets, controller } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { AuthService } from "services/";
import { InputFieldElement } from "components/";
import { BasePageElement } from "common/";
import { targets, controller } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { AuthService } from 'services/';
import { InputFieldElement } from 'components/';
import { BasePageElement } from 'common/';
@controller
class RegisterPageElement extends BasePageElement {
@@ -10,7 +10,7 @@ class RegisterPageElement extends BasePageElement {
authService: AuthService;
constructor() {
super({
title: "Register",
title: 'Register',
});
}
elementConnected = (): void => {
@@ -32,12 +32,10 @@ class RegisterPageElement extends BasePageElement {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userRegister(
this.values
);
const response = await this.appMain.authStore.userRegister(this.values);
if (response?.id) {
this.appMain.routerService.goTo("/login");
this.appMain.routerService.goTo('/login');
}
} catch (err) {}
};
@@ -53,10 +51,7 @@ class RegisterPageElement extends BasePageElement {
render = (): TemplateResult => {
return html`
<app-form
data-custom="register-page#onSubmit"
data-has-cancel="true"
>
<app-form data-custom="register-page#onSubmit" data-has-cancel="true">
<input-field
data-type="text"
data-name="username"

View File

@@ -1,10 +1,10 @@
import { targets, controller } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { AuthService, TransactionsService, WalletService } from "services/";
import { InputFieldElement } from "components/";
import { RouterService } from "core/services";
import { BasePageElement } from "common/";
import { AppDropdownElement } from "components/app-dropdown/AppDropdownElement";
import { targets, controller } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { AuthService, TransactionsService, WalletService } from 'services/';
import { InputFieldElement } from 'components/';
import { RouterService } from 'core/services';
import { BasePageElement } from 'common/';
import { AppDropdownElement } from 'components/app-dropdown/AppDropdownElement';
@controller
class TransactionCreateElement extends BasePageElement {
@@ -15,21 +15,19 @@ class TransactionCreateElement extends BasePageElement {
errorMessage: string;
constructor() {
super({
title: "New Transaction",
title: 'New Transaction',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.transactionService = new TransactionsService(
this.appMain?.appService
);
this.transactionService = new TransactionsService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.update();
};
get nameInput(): InputFieldElement | AppDropdownElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "name") {
if (this.inputs[i]?.name == 'name') {
return this.inputs[i];
}
}
@@ -57,11 +55,7 @@ class TransactionCreateElement extends BasePageElement {
return;
}
const {
description: description,
wallet: walletId,
amount,
} = values;
const { description: description, wallet: walletId, amount } = values;
const response = await this.transactionService.post({
description,
@@ -71,12 +65,12 @@ class TransactionCreateElement extends BasePageElement {
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo("/history", {
this.routerService.goTo('/history', {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = "Unable to create transaction!";
this.errorMessage = 'Unable to create transaction!';
this.update();
}
};
@@ -93,10 +87,7 @@ class TransactionCreateElement extends BasePageElement {
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form
data-custom="transaction-create#onSubmit"
data-has-cancel="true"
>
<app-form data-custom="transaction-create#onSubmit" data-has-cancel="true">
<input-field
data-type="number"
data-name="amount"
@@ -119,9 +110,7 @@ class TransactionCreateElement extends BasePageElement {
data-fetch="transaction-create#getWallets"
>
</app-dropdown>
${this.errorMessage
? html`<div>${this.errorMessage}</div>`
: html``}
${this.errorMessage ? html`<div>${this.errorMessage}</div>` : html``}
</app-form>
`;
};

View File

@@ -1,9 +1,9 @@
import { targets, controller } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { AuthService, WalletService } from "services/";
import { InputFieldElement } from "components/";
import { RouterService } from "core/services";
import { BasePageElement } from "common/";
import { targets, controller } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { AuthService, WalletService } from 'services/';
import { InputFieldElement } from 'components/';
import { RouterService } from 'core/services';
import { BasePageElement } from 'common/';
@controller
class WalletCreateElement extends BasePageElement {
@@ -13,7 +13,7 @@ class WalletCreateElement extends BasePageElement {
errorMessage: string;
constructor() {
super({
title: "New Wallet",
title: 'New Wallet',
});
}
elementConnected = (): void => {
@@ -24,7 +24,7 @@ class WalletCreateElement extends BasePageElement {
get nameInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "name") {
if (this.inputs[i]?.name == 'name') {
return this.inputs[i];
}
}
@@ -48,12 +48,12 @@ class WalletCreateElement extends BasePageElement {
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo("/wallet/:walletId", {
this.routerService.goTo('/wallet/:walletId', {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = "Unable to create wallet!";
this.errorMessage = 'Unable to create wallet!';
this.update();
}
};
@@ -70,10 +70,7 @@ class WalletCreateElement extends BasePageElement {
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form
data-custom="wallet-create#onSubmit"
data-has-cancel="true"
>
<app-form data-custom="wallet-create#onSubmit" data-has-cancel="true">
<input-field
data-type="text"
data-name="name"
@@ -81,9 +78,7 @@ class WalletCreateElement extends BasePageElement {
data-targets="wallet-create.inputs"
data-rules="required"
></input-field>
${this.errorMessage
? html`<div>${this.errorMessage}</div>`
: html``}
${this.errorMessage ? html`<div>${this.errorMessage}</div>` : html``}
</app-form>
`;
};

View File

@@ -1,8 +1,8 @@
import { targets, controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { AuthService, WalletService } from "services/";
import { AppPaginationElement, InputFieldElement } from "components/";
import { BasePageElement } from "common/";
import { targets, controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { AuthService, WalletService } from 'services/';
import { AppPaginationElement, InputFieldElement } from 'components/';
import { BasePageElement } from 'common/';
@controller
class WalletListElement extends BasePageElement {
@@ -13,7 +13,7 @@ class WalletListElement extends BasePageElement {
errorMessage: string;
constructor() {
super({
title: "Wallet List",
title: 'Wallet List',
});
}
elementConnected = (): void => {
@@ -40,9 +40,7 @@ class WalletListElement extends BasePageElement {
render = (): TemplateResult => {
return html`
<div>Wallets</div>
<app-pagination
data-target="wallet-list.pagination"
></app-pagination>
<app-pagination data-target="wallet-list.pagination"></app-pagination>
`;
};
}

View File

@@ -1,12 +1,8 @@
import { controller, target } from "@github/catalyst";
import { html, TemplateResult } from "lit-html";
import { TransactionsService, WalletService } from "services/";
import {
AppMainElement,
AppPaginationElement,
WalletHeaderElement,
} from "components/";
import { BasePageElement } from "common/";
import { controller, target } from '@github/catalyst';
import { html, TemplateResult } from 'lit-html';
import { TransactionsService, WalletService } from 'services/';
import { AppMainElement, AppPaginationElement, WalletHeaderElement } from 'components/';
import { BasePageElement } from 'common/';
@controller
class WalletPageElement extends BasePageElement {
@@ -17,15 +13,13 @@ class WalletPageElement extends BasePageElement {
walletId: string;
constructor() {
super({
title: "Wallet",
title: 'Wallet',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.transactionsService = new TransactionsService(
this.appMain?.appService
);
this.transactionsService = new TransactionsService(this.appMain?.appService);
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
@@ -34,11 +28,11 @@ class WalletPageElement extends BasePageElement {
}
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener("tokenchange", this.update);
this.appMain.addEventListener('tokenchange', this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
appMain?.removeEventListener('tokenchange', this.update);
};
getTransactions = async (options): Promise<any> => {
@@ -46,7 +40,7 @@ class WalletPageElement extends BasePageElement {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options["walletId"] = walletId;
options['walletId'] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
@@ -70,9 +64,9 @@ class WalletPageElement extends BasePageElement {
setBalance = (header) => {
if (!this.walletHeader) return;
this.walletHeader.currency = header.currency;
this.walletHeader.currentBalance = header.currentBalance || "0";
this.walletHeader.lastMonth = header.lastMonth || "0";
this.walletHeader.nextMonth = header.nextMonth || "0";
this.walletHeader.currentBalance = header.currentBalance || '0';
this.walletHeader.lastMonth = header.lastMonth || '0';
this.walletHeader.nextMonth = header.nextMonth || '0';
};
render = (): TemplateResult => {
@@ -87,17 +81,13 @@ class WalletPageElement extends BasePageElement {
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
return html`<span
>${this.routerService?.routerState?.data?.walletId}</span
>`;
return html`<span>${this.routerService?.routerState?.data?.walletId}</span>`;
}
return html``;
};
return html`<div>
${renderHeader()} ${renderWallet()}
<app-pagination
data-target="wallet-page.pagination"
></app-pagination>
<app-pagination data-target="wallet-page.pagination"></app-pagination>
</div>`;
};
}

View File

@@ -1,21 +1,17 @@
import { AppService, BaseService } from "core/services";
import { AppService, BaseService } from 'core/services';
class PingService extends BaseService {
constructor(appService: AppService) {
super("/auth", appService);
super('/auth', appService);
}
login = (data?: Object, headers?: HeadersInit) => {
return this.appService.post(this.endpoint + "/login", data, headers);
return this.appService.post(this.endpoint + '/login', data, headers);
};
register = (data?: Object, headers?: HeadersInit) => {
return this.appService.post(this.endpoint + "/register", data, headers);
return this.appService.post(this.endpoint + '/register', data, headers);
};
checkToken = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(
this.endpoint + "/check-token",
params,
headers
);
return this.appService.get(this.endpoint + '/check-token', params, headers);
};
}

View File

@@ -1,8 +1,8 @@
import { AppService, BaseService } from "core/services";
import { AppService, BaseService } from 'core/services';
class PingService extends BaseService {
constructor(appService: AppService) {
super("/wallet", appService);
super('/wallet', appService);
}
}

View File

@@ -1,8 +1,8 @@
import { AppService, BaseService } from "core/services";
import { AppService, BaseService } from 'core/services';
class TransactionsService extends BaseService {
constructor(appService: AppService) {
super("/transaction", appService);
super('/transaction', appService);
}
}

View File

@@ -1,16 +1,12 @@
import { AppService, BaseService } from "core/services";
import { AppService, BaseService } from 'core/services';
class WalletService extends BaseService {
constructor(appService: AppService) {
super("/wallet", appService);
super('/wallet', appService);
}
getBalance = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(
this.endpoint + "/wallet-header",
params,
headers
);
return this.appService.get(this.endpoint + '/wallet-header', params, headers);
};
}

View File

@@ -1,4 +1,4 @@
export { default as PingService } from "./PingService";
export { default as AuthService } from "./AuthService";
export { default as WalletService } from "./WalletService";
export { default as TransactionsService } from "./TransactionsService";
export { default as PingService } from './PingService';
export { default as AuthService } from './AuthService';
export { default as WalletService } from './WalletService';
export { default as TransactionsService } from './TransactionsService';

732
yarn.lock

File diff suppressed because it is too large Load Diff