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,142 +1,133 @@
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;
private _appMain: AppMainElement;
public loader: Loader;
private elementDisconnectCallbacks: Array<Function> = [];
constructor() {
super();
this.connectedCallback = this.connectedCallback.bind(this);
this.disconnectedCallback = this.disconnectedCallback.bind(this);
this.loader = new Loader(this);
}
@closest appMain: AppMainElement;
private _appMain: AppMainElement;
public loader: Loader;
private elementDisconnectCallbacks: Array<Function> = [];
constructor() {
super();
this.connectedCallback = this.connectedCallback.bind(this);
this.disconnectedCallback = this.disconnectedCallback.bind(this);
this.loader = new Loader(this);
}
public get routerService(): RouterService {
return this.appMain?.routerService;
}
public get routerService(): RouterService {
return this.appMain?.routerService;
}
public get authStore(): AuthStore {
return this.appMain?.authStore;
}
public get authStore(): AuthStore {
return this.appMain?.authStore;
}
public get appService(): AppService {
return this.appMain?.appService;
}
public get appService(): AppService {
return this.appMain?.appService;
}
public get appModal(): AppModalElement {
return this.appMain?.appModal;
}
public get appModal(): AppModalElement {
return this.appMain?.appModal;
}
public get mainRoot(): AppRootElement {
return this.appMain?.mainRoot;
}
public get appLoader(): AppLoaderElement {
return this.appMain?.appLoader;
}
public get mainRoot(): AppRootElement {
return this.appMain?.mainRoot;
}
public get appLoader(): AppLoaderElement {
return this.appMain?.appLoader;
}
public get isAuth(): boolean {
return this.appMain?.isAuth();
}
public get isAuth(): boolean {
return this.appMain?.isAuth();
}
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("#");
const tag = action.slice(eventSep + 1, methodSep);
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('#');
const tag = action.slice(eventSep + 1, methodSep);
const type = action.slice(0, eventSep);
const method = action.slice(methodSep + 1);
const type = action.slice(0, eventSep);
const method = action.slice(methodSep + 1);
if (tag.toUpperCase() === this.tagName) {
el.addEventListener(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]);
this.elementDisconnectCallbacks.push(_callback);
}
});
}
}
});
};
if (tag.toUpperCase() === this.tagName) {
el.addEventListener(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]);
this.elementDisconnectCallbacks.push(_callback);
}
});
}
}
});
};
render = (): TemplateResult | Temp => {
return html``;
};
render = (): TemplateResult | Temp => {
return html``;
};
updateCallback = (): void => {};
updateCallback = (): void => {};
update = (): void => {
render(this.render(), this);
this.bindEvents("data-action");
this.bindEvents("app-action");
this.updateCallback();
};
update = (): void => {
render(this.render(), this);
this.bindEvents('data-action');
this.bindEvents('app-action');
this.updateCallback();
};
connectedCallback(): void {
this.elementConnected();
this._appMain = this.appMain;
}
connectedCallback(): void {
this.elementConnected();
this._appMain = this.appMain;
}
disconnectedCallback(): void {
const { _appMain } = this;
this.elementDisconnected(_appMain);
if (Array.isArray(this.elementDisconnectCallbacks)) {
this.elementDisconnectCallbacks.forEach((callback: Function) => {
if (typeof callback == "function") {
callback(_appMain);
}
});
}
}
disconnectedCallback(): void {
const { _appMain } = this;
this.elementDisconnected(_appMain);
if (Array.isArray(this.elementDisconnectCallbacks)) {
this.elementDisconnectCallbacks.forEach((callback: Function) => {
if (typeof callback == 'function') {
callback(_appMain);
}
});
}
}
elementConnected = (): void => {
this.update();
};
elementConnected = (): void => {
this.update();
};
elementDisconnected = (appMain: AppMainElement): void => {};
elementDisconnected = (appMain: AppMainElement): void => {};
}
export default BaseElement;
class Loader {
private _loading: number = 0;
private _loading: number = 0;
constructor(private _main: BaseElement) {}
constructor(private _main: BaseElement) {}
public start = () => {
this._loading++;
this._main?.update?.();
};
public start = () => {
this._loading++;
this._main?.update?.();
};
public stop = () => {
if (this._loading > 0) {
this._loading--;
this._main?.update?.();
}
};
public stop = () => {
if (this._loading > 0) {
this._loading--;
this._main?.update?.();
}
};
public get loading() {
return this._loading > 0;
}
public get loading() {
return this._loading > 0;
}
}

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,30 +1,30 @@
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;
public isLayout: boolean = true;
public _appSlot: string;
constructor() {
super();
}
@target appSlot: HTMLElement;
public isLayout: boolean = true;
public _appSlot: string;
constructor() {
super();
}
get slotTag(): string {
return this.appSlot?.firstElementChild?.tagName;
}
get slotTag(): string {
return this.appSlot?.firstElementChild?.tagName;
}
compareTags = (tag: string | HTMLElement): boolean => {
if (typeof tag === "string") {
return this.slotTag === tag;
}
return tag?.tagName === this.slotTag;
};
compareTags = (tag: string | HTMLElement): boolean => {
if (typeof tag === 'string') {
return this.slotTag === tag;
}
return tag?.tagName === this.slotTag;
};
setElement = (newTag: string): void => {
const _appSlot = `<div data-target="base-layout.content"><${newTag}></${newTag}></div>`;
this._appSlot = _appSlot;
this.appSlot.innerHTML = _appSlot;
};
setElement = (newTag: string): void => {
const _appSlot = `<div data-target="base-layout.content"><${newTag}></${newTag}></div>`;
this._appSlot = _appSlot;
this.appSlot.innerHTML = _appSlot;
};
}
export default BaseLayoutElement;

View File

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

View File

@@ -1,45 +1,43 @@
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 = "";
@attr hidetitle: string;
@attr customtitle: string;
constructor(options: OptionType) {
super();
if (options?.title) {
this.pageTitle = options?.title;
}
this.connectedCallback = this.connectedCallback.bind(this);
this.disconnectedCallback = this.disconnectedCallback.bind(this);
}
public pageTitle: string = '';
@attr hidetitle: string;
@attr customtitle: string;
constructor(options: OptionType) {
super();
if (options?.title) {
this.pageTitle = options?.title;
}
this.connectedCallback = this.connectedCallback.bind(this);
this.disconnectedCallback = this.disconnectedCallback.bind(this);
}
public renderTitle = () => {
if (!isTrue(this.hidetitle)) {
return html`<div class="page --title">
${this.customtitle ? this.customtitle : this.pageTitle}
</div>`;
}
return html``;
};
public renderTitle = () => {
if (!isTrue(this.hidetitle)) {
return html`<div class="page --title">${this.customtitle ? this.customtitle : this.pageTitle}</div>`;
}
return html``;
};
update = (): void => {
const _render = () => html` ${this.renderTitle()} ${this.render()} `;
render(_render(), this);
this.bindEvents("app-action");
this.updateCallback();
};
update = (): void => {
const _render = () => html` ${this.renderTitle()} ${this.render()} `;
render(_render(), this);
this.bindEvents('app-action');
this.updateCallback();
};
connectedCallback() {
this.appMain.setTitle(this.pageTitle);
super.connectedCallback();
}
connectedCallback() {
this.appMain.setTitle(this.pageTitle);
super.connectedCallback();
}
}
export default BasePageElement;
export type OptionType = {
title?: string;
title?: string;
};

View File

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

View File

@@ -1,241 +1,213 @@
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 {
@attr name: string;
@attr label: string;
@attr rules: string;
@target main: HTMLElement;
@target inp: HTMLElement;
@attr displaykey: string = "name";
@attr valuekey: string = "id";
@attr fetch: string;
fetchFunc: any;
@attr name: string;
@attr label: string;
@attr rules: string;
@target main: HTMLElement;
@target inp: HTMLElement;
@attr displaykey: string = 'name';
@attr valuekey: string = 'id';
@attr fetch: string;
fetchFunc: any;
error: boolean;
errorMessage: string;
error: boolean;
errorMessage: string;
searchPhrase: string;
searchPhrase: string;
randId: string;
value: string;
randId: string;
value: string;
@attr isOpen: boolean = false;
@attr isOpen: boolean = false;
items: Array<any>;
totalItems: number;
page: number = 1;
rpp: number = 30;
items: Array<any>;
totalItems: number;
page: number = 1;
rpp: number = 30;
constructor() {
super();
}
getItems = async (options?: any): Promise<void> => {
if (typeof this.fetchFunc !== "function") return;
try {
const response = await this.fetchFunc(options);
this.setItems(response);
} catch (err) {
this.update();
}
};
constructor() {
super();
}
getItems = async (options?: any): Promise<void> => {
if (typeof this.fetchFunc !== 'function') return;
try {
const response = await this.fetchFunc(options);
this.setItems(response);
} catch (err) {
this.update();
}
};
setItems = (response): void => {
if (response) {
let items = [];
if (Array.isArray(response)) {
items = response;
} else if (Array.isArray(response.items)) {
items = response.items;
this.totalItems = response?.totalRecords;
} else {
items = [];
}
this.items = items;
this.update();
}
};
setItems = (response): void => {
if (response) {
let items = [];
if (Array.isArray(response)) {
items = response;
} else if (Array.isArray(response.items)) {
items = response.items;
this.totalItems = response?.totalRecords;
} else {
items = [];
}
this.items = items;
this.update();
}
};
get selectedItem() {
const { value, valuekey, items } = this;
const item = items?.find((item) => {
return value == item[valuekey];
});
get selectedItem() {
const { value, valuekey, items } = this;
const item = items?.find((item) => {
return value == item[valuekey];
});
console.log(item, value, valuekey);
console.log(item, value, valuekey);
return item;
}
return item;
}
get optionValues() {
let values = [];
this.inp.childNodes.forEach((item: HTMLElement) => {
const value = item.getAttribute("value");
const name = item.innerText;
values.push({ name, value });
});
return values;
}
get optionValues() {
let values = [];
this.inp.childNodes.forEach((item: HTMLElement) => {
const value = item.getAttribute('value');
const name = item.innerText;
values.push({ name, value });
});
return values;
}
public elementConnected = (): void => {
this.randId = `${name}${randomId()}`;
this.fetchFunc = findMethod(this.fetch, this.appMain);
this.update();
public elementConnected = (): void => {
this.randId = `${name}${randomId()}`;
this.fetchFunc = findMethod(this.fetch, this.appMain);
this.update();
const options = {
rpp: this.rpp,
page: this.page,
};
this.getItems(options);
};
const options = {
rpp: this.rpp,
page: this.page,
};
this.getItems(options);
};
attributeChangedCallback(): void {
this.update();
}
attributeChangedCallback(): void {
this.update();
}
get valid(): boolean {
return !!this.error;
}
get valid(): boolean {
return !!this.error;
}
get required(): boolean {
return this.rules.includes("required");
}
get required(): boolean {
return this.rules.includes('required');
}
validate(): boolean {
let _return = true;
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;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll(
"{- name}",
firstUpper(this.name?.toString())
);
_return = false;
this.error = error;
}
});
if (_return) {
this.error = null;
}
this.update();
return _return;
}
validate(): boolean {
let _return = true;
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;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll('{- name}', firstUpper(this.name?.toString()));
_return = false;
this.error = error;
}
});
if (_return) {
this.error = null;
}
this.update();
return _return;
}
openDropdown = () => {
this.isOpen = true;
};
openDropdown = () => {
this.isOpen = true;
};
stopPropagation = (e) => {
e.stopPropagation();
};
stopPropagation = (e) => {
e.stopPropagation();
};
toggleDropdown = () => {
const isOpen = this.isOpen;
this.isOpen = !isOpen;
};
toggleDropdown = () => {
const isOpen = this.isOpen;
this.isOpen = !isOpen;
};
itemSelected = (e) => {
const value = (e.target as HTMLSpanElement).getAttribute("data-value");
this.value = value;
this.isOpen = false;
};
itemSelected = (e) => {
const value = (e.target as HTMLSpanElement).getAttribute('data-value');
this.value = value;
this.isOpen = false;
};
get _value() {
return this.value;
}
get _value() {
return this.value;
}
render = () => {
const {
label,
error,
errorMessage,
isOpen,
searchPhrase,
items,
selectedItem,
displaykey,
valuekey,
} = this;
render = () => {
const { label, error, errorMessage, isOpen, searchPhrase, items, selectedItem, displaykey, valuekey } = this;
console.log(isOpen);
console.log(isOpen);
const renderItem = (item) => {
return html` <li
class="dropdown-custom-listitem ${selectedItem?.[valuekey] ==
item[valuekey]
? "--selected"
: ""}"
app-action="click:app-dropdown#itemSelected"
data-value="${item[valuekey]}"
>
${item[displaykey]}
</li>`;
};
const renderItem = (item) => {
return html` <li
class="dropdown-custom-listitem ${selectedItem?.[valuekey] == item[valuekey] ? '--selected' : ''}"
app-action="click:app-dropdown#itemSelected"
data-value="${item[valuekey]}"
>
${item[displaykey]}
</li>`;
};
const renderItems = (_items) => {
return _items.map((item) => renderItem(item));
};
const renderItems = (_items) => {
return _items.map((item) => renderItem(item));
};
return html`
<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>
${isOpen
? html`
<div class="dropdown-custom-open">
<input
class="dropdown-custom-search"
type="text"
value="${searchPhrase}"
app-action="input:app-dropdown#phraseChange"
autofocus
/>
<ul class="dropdown-custom-list">
${renderItems(items)}
</ul>
</div>
`
: html``}
</div>
${error
? html` <div class="h5 text-red">${errorMessage}</div>`
: html``}
</label>
</div>
`;
};
return html`
<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>
${isOpen
? html`
<div class="dropdown-custom-open">
<input
class="dropdown-custom-search"
type="text"
value="${searchPhrase}"
app-action="input:app-dropdown#phraseChange"
autofocus
/>
<ul class="dropdown-custom-list">
${renderItems(items)}
</ul>
</div>
`
: html``}
</div>
${error ? html` <div class="h5 text-red">${errorMessage}</div>` : html``}
</label>
</div>
`;
};
}
export type { AppDropdownElement };

View File

@@ -1,135 +1,125 @@
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 {
@target formElement: HTMLElement;
@target innerSlot: HTMLElement;
@querys inputField: NodeListOf<InputFieldElement>;
@querys appDropdown: NodeListOf<AppDropdownElement>;
@attr custom: string;
@attr hasCancel: string;
slotted: any;
isValid: boolean = false;
error: string;
constructor() {
super();
}
@target formElement: HTMLElement;
@target innerSlot: HTMLElement;
@querys inputField: NodeListOf<InputFieldElement>;
@querys appDropdown: NodeListOf<AppDropdownElement>;
@attr custom: string;
@attr hasCancel: string;
slotted: any;
isValid: boolean = false;
error: string;
constructor() {
super();
}
public inputChange = (e) => {
this.validate();
this.update();
};
public inputChange = (e) => {
this.validate();
this.update();
};
public onSubmit = (e) => {
e.preventDefault();
if (!this.valid) {
return;
}
const actionString = this.custom;
const submitFunc = findMethod(actionString, this.appMain);
submitFunc?.(this.values);
return false;
};
public onSubmit = (e) => {
e.preventDefault();
if (!this.valid) {
return;
}
const actionString = this.custom;
const submitFunc = findMethod(actionString, this.appMain);
submitFunc?.(this.values);
return false;
};
public validate = () => {
this.isValid = true;
this.inputField?.forEach((input) => {
if (input?.error) {
this.isValid = false;
}
});
};
public validate = () => {
this.isValid = true;
this.inputField?.forEach((input) => {
if (input?.error) {
this.isValid = false;
}
});
};
public setError = (error) => {
this.error = error;
this.update();
};
public setError = (error) => {
this.error = error;
this.update();
};
public goBack = (e) => {
e.preventDefault();
public goBack = (e) => {
e.preventDefault();
if (this.appMain?.appModal) {
this.appMain?.closeModal?.();
} else if (this.routerService?.canGoBack) {
this.routerService?.goBack();
} else {
this.routerService?.goTo("/");
}
};
if (this.appMain?.appModal) {
this.appMain?.closeModal?.();
} else if (this.routerService?.canGoBack) {
this.routerService?.goBack();
} else {
this.routerService?.goTo('/');
}
};
get values(): any {
const formObject: any = {};
this.inputField.forEach((input: InputFieldElement) => {
formObject[input.name] = input._value;
});
this.appDropdown?.forEach((input: AppDropdownElement) => {
if (input.required && input.value) {
formObject[input.name] = input._value;
}
});
return formObject;
}
get values(): any {
const formObject: any = {};
this.inputField.forEach((input: InputFieldElement) => {
formObject[input.name] = input._value;
});
this.appDropdown?.forEach((input: AppDropdownElement) => {
if (input.required && input.value) {
formObject[input.name] = input._value;
}
});
return formObject;
}
get valid() {
let _valid = 0;
this.inputField?.forEach((input) => {
if (input.required && (input.inp as HTMLSelectElement).value) {
_valid++;
}
});
return _valid == this.inputField?.length;
}
get valid() {
let _valid = 0;
this.inputField?.forEach((input) => {
if (input.required && (input.inp as HTMLSelectElement).value) {
_valid++;
}
});
return _valid == this.inputField?.length;
}
elementConnected = (): void => {
const _template = document.createElement("template");
const _slot = this.innerHTML;
_template.innerHTML = _slot;
this.innerHTML = null;
this.update();
elementConnected = (): void => {
const _template = document.createElement('template');
const _slot = this.innerHTML;
_template.innerHTML = _slot;
this.innerHTML = null;
this.update();
this.formElement.replaceChild(_template.content, this.innerSlot);
};
this.formElement.replaceChild(_template.content, this.innerSlot);
};
render = (): TemplateResult => {
const renderSubmit = (valid: boolean) => {
if (!valid) {
return html` <button type="submit" disabled>Submit</button> `;
}
return html` <button type="submit">Submit</button> `;
};
const renderError = (error: string) => {
if (error) {
return html`<span>${error}</span>`;
}
return html``;
};
const renderCancel = (hasCancel: boolean) => {
if (hasCancel) {
return html`<button
type="button"
app-action="click:app-form#goBack"
>
Cancel
</button>`;
}
return html``;
};
render = (): TemplateResult => {
const renderSubmit = (valid: boolean) => {
if (!valid) {
return html` <button type="submit" disabled>Submit</button> `;
}
return html` <button type="submit">Submit</button> `;
};
const renderError = (error: string) => {
if (error) {
return html`<span>${error}</span>`;
}
return html``;
};
const renderCancel = (hasCancel: boolean) => {
if (hasCancel) {
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"
>
<slot data-target="app-form.innerSlot"></slot>
${renderError(this.error)}${renderSubmit(
this.isValid
)}${renderCancel(isTrue(this.hasCancel))}
</form>`;
};
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))}
</form>`;
};
}
export type { AppFormElement };

View File

@@ -1,72 +1,67 @@
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 {
@attr to: string;
@attr goBack: string;
@attr title: string;
@target main: Element;
constructor() {
super();
}
@attr to: string;
@attr goBack: string;
@attr title: string;
@target main: Element;
constructor() {
super();
}
elementConnected = (): void => {
if (!this.title && this.innerText) {
const _slottedText = this.innerText;
this.innerText = null;
this.title = _slottedText;
}
this.update();
if (isTrue(this.goBack)) {
this.appMain.addEventListener("routechanged", this.update);
}
};
elementConnected = (): void => {
if (!this.title && this.innerText) {
const _slottedText = this.innerText;
this.innerText = null;
this.title = _slottedText;
}
this.update();
if (isTrue(this.goBack)) {
this.appMain.addEventListener('routechanged', this.update);
}
};
elementDisconnected = (appMain: AppMainElement): void => {
if (isTrue(this.goBack)) {
appMain?.removeEventListener("routechanged", this.update);
}
};
elementDisconnected = (appMain: AppMainElement): void => {
if (isTrue(this.goBack)) {
appMain?.removeEventListener('routechanged', this.update);
}
};
goTo = (e: Event): void => {
e.preventDefault();
if (!isTrue(this.goBack) && this.to) {
this.routerService.goTo(this.to);
} else {
this.routerService.goBack();
}
this.update();
};
goTo = (e: Event): void => {
e.preventDefault();
if (!isTrue(this.goBack) && this.to) {
this.routerService.goTo(this.to);
} else {
this.routerService.goBack();
}
this.update();
};
get disabled(): boolean {
if (isTrue(this.goBack)) {
return this.routerService.emptyState;
}
return false;
}
get disabled(): boolean {
if (isTrue(this.goBack)) {
return this.routerService.emptyState;
}
return false;
}
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"
data-target="app-link.main"
app-action="click:app-link#goTo"
href="${this.to}"
style="text-decoration: underline; cursor: pointer;"
>${this.title}</a
>`}`;
};
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"
data-target="app-link.main"
app-action="click:app-link#goTo"
href="${this.to}"
style="text-decoration: underline; cursor: pointer;"
>${this.title}</a
>`}`;
};
}
export type { AppLinkElement };

View File

@@ -1,58 +1,58 @@
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 {
private finished: boolean = true;
private _loading: number = 0;
private finished: boolean = true;
private _loading: number = 0;
constructor() {
super();
}
constructor() {
super();
}
public start = () => {
this.finished = false;
this._loading++;
this.update();
};
public start = () => {
this.finished = false;
this._loading++;
this.update();
};
public stop = () => {
if (this._loading > 0) {
this._loading--;
}
if (this._loading == 0) {
this.finishInitiate();
}
this.update();
};
public stop = () => {
if (this._loading > 0) {
this._loading--;
}
if (this._loading == 0) {
this.finishInitiate();
}
this.update();
};
public get loading() {
return this._loading > 0;
}
public get loading() {
return this._loading > 0;
}
private finishInitiate = () => {
setTimeout(() => {
this.finished = true;
this.update();
}, 300);
};
private finishInitiate = () => {
setTimeout(() => {
this.finished = true;
this.update();
}, 300);
};
elementConnected = (): void => {
this.update();
};
elementConnected = (): void => {
this.update();
};
render = () => {
const renderLoader = (finished: boolean, loading: boolean) => {
if (!finished && !loading) {
return html`<div class="loader --removing"></div>`;
} else if (loading) {
return html`<div class="loader --loading"></div>`;
}
return html``;
};
return html`${renderLoader(this.finished, this.loading)}`;
};
render = () => {
const renderLoader = (finished: boolean, loading: boolean) => {
if (!finished && !loading) {
return html`<div class="loader --removing"></div>`;
} else if (loading) {
return html`<div class="loader --loading"></div>`;
}
return html``;
};
return html`${renderLoader(this.finished, this.loading)}`;
};
}
export type { AppLoaderElement };

View File

@@ -1,185 +1,185 @@
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 {
public routerService: RouterService;
public authStore: AuthStore;
private httpClient: HttpClient;
public appService: AppService;
@target appModal: AppModalElement;
@target mainRoot: AppRootElement;
@target appLoader: AppLoaderElement;
@closest appMain: AppMainElement;
public domEvents: any = {
routechanged: new Event("routechanged"),
tokenchange: new Event("tokenchange"),
walletupdate: new Event("walletupdate"),
};
public routerService: RouterService;
public authStore: AuthStore;
private httpClient: HttpClient;
public appService: AppService;
@target appModal: AppModalElement;
@target mainRoot: AppRootElement;
@target appLoader: AppLoaderElement;
@closest appMain: AppMainElement;
public domEvents: any = {
routechanged: new Event('routechanged'),
tokenchange: new Event('tokenchange'),
walletupdate: new Event('walletupdate'),
};
constructor() {
super();
}
connectedCallback() {
if (this.appMain !== this) return;
this.createLoader();
const mainRoot = this.createMainRoot();
this.httpClient = new HttpClient();
this.appService = new AppService(this, this.httpClient);
this.routerService = new RouterService(this, mainRoot);
this.authStore = new AuthStore(this, this.appService);
this.routerService.setRoutes([
{
path: "/",
component: "home-page",
layout: "menu-layout",
middleware: this.isAuth,
},
{
path: "/home",
component: "home-page",
layout: "menu-layout",
middleware: this.isAuth,
},
{
path: "/history",
component: "history-page",
layout: "menu-layout",
middleware: this.isAuth,
},
{
path: "/wallet",
component: "history-page",
layout: "menu-layout",
middleware: this.isAuth,
children: [
{
path: "/all",
component: "wallet-list",
layout: "menu-layout",
},
{
path: "/:walletId",
component: "wallet-page",
layout: "menu-layout",
},
],
},
{
path: "/register",
component: "register-page",
layout: "initial-layout",
},
{
path: "/login",
component: "login-page",
layout: "initial-layout",
},
{
path: "/unauthorized",
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: "/logout",
component: "logout-page",
},
]);
this.routerService.init();
}
constructor() {
super();
}
connectedCallback() {
if (this.appMain !== this) return;
this.createLoader();
const mainRoot = this.createMainRoot();
this.httpClient = new HttpClient();
this.appService = new AppService(this, this.httpClient);
this.routerService = new RouterService(this, mainRoot);
this.authStore = new AuthStore(this, this.appService);
this.routerService.setRoutes([
{
path: '/',
component: 'home-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: '/home',
component: 'home-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: '/history',
component: 'history-page',
layout: 'menu-layout',
middleware: this.isAuth,
},
{
path: '/wallet',
component: 'history-page',
layout: 'menu-layout',
middleware: this.isAuth,
children: [
{
path: '/all',
component: 'wallet-list',
layout: 'menu-layout',
},
{
path: '/:walletId',
component: 'wallet-page',
layout: 'menu-layout',
},
],
},
{
path: '/register',
component: 'register-page',
layout: 'initial-layout',
},
{
path: '/login',
component: 'login-page',
layout: 'initial-layout',
},
{
path: '/unauthorized',
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: '/logout',
component: 'logout-page',
},
]);
this.routerService.init();
}
middleAuth = () => {
if (!this.isAuth) {
this.routerService.goTo("/unauthorized");
return true;
}
};
middleAuth = () => {
if (!this.isAuth) {
this.routerService.goTo('/unauthorized');
return true;
}
};
createModal = (element: string) => {
this.closeModal();
this.appMain.addEventListener("routechanged", this.closeModal);
createModal = (element: string) => {
this.closeModal();
this.appMain.addEventListener('routechanged', this.closeModal);
const _appModal = this.createAppModal();
const _modalContent = this.createModalContent(element);
const _modalOverlay = this.createModalOverlay();
const _appModal = this.createAppModal();
const _modalContent = this.createModalContent(element);
const _modalOverlay = this.createModalOverlay();
_modalOverlay.appendChild(_modalContent);
_appModal.appendChild(_modalOverlay);
this.appendChild(_appModal);
};
_modalOverlay.appendChild(_modalContent);
_appModal.appendChild(_modalOverlay);
this.appendChild(_appModal);
};
public triggerWalletUpdate = () => {
this.dispatchEvent(this.domEvents.walletupdate);
};
public triggerWalletUpdate = () => {
this.dispatchEvent(this.domEvents.walletupdate);
};
public setTitle = (title: string): void => {
if (!title) title = __CONFIG__.appName;
window.document.title = title;
};
public setTitle = (title: string): void => {
if (!title) title = __CONFIG__.appName;
window.document.title = title;
};
private createAppModal = () => {
const _appModal = document.createElement("app-modal");
_appModal.setAttribute("data-target", "app-main.appModal");
return _appModal;
};
private createAppModal = () => {
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");
this.appendChild(_loader);
};
private createLoader = () => {
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");
_divEl.appendChild(_modalElement);
return _divEl;
};
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');
_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");
return _divOverlay;
};
private createModalOverlay = () => {
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");
this.appendChild(_mainRoot);
return _mainRoot;
};
private createMainRoot = () => {
if (this.mainRoot) this.removeChild(this.mainRoot);
const _mainRoot = document.createElement('app-root');
_mainRoot.setAttribute('data-target', 'app-main.mainRoot');
this.appendChild(_mainRoot);
return _mainRoot;
};
preventClosing = (e: Event) => {
e.stopPropagation();
};
preventClosing = (e: Event) => {
e.stopPropagation();
};
closeModal = () => {
if (this.appModal) this.removeChild(this.appModal);
this.appMain.removeEventListener("routechanged", this.closeModal);
};
closeModal = () => {
if (this.appModal) this.removeChild(this.appModal);
this.appMain.removeEventListener('routechanged', this.closeModal);
};
isAuth = (): boolean => {
return this.authStore && !!this.authStore.token;
};
isAuth = (): boolean => {
return this.authStore && !!this.authStore.token;
};
}
export type { AppMainElement };

View File

@@ -1,164 +1,132 @@
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 {
private walletService: WalletService;
private walletData: Array<any>;
private totalWallets: number;
@target walletlist: MenuItemElement;
constructor() {
super();
}
private walletService: WalletService;
private walletData: Array<any>;
private totalWallets: number;
@target walletlist: MenuItemElement;
constructor() {
super();
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
if (this.appMain.isAuth) {
this.getWallets();
}
this.update();
this.appMain.addEventListener("tokenchange", this.updateToken);
this.appMain.addEventListener("walletupdate", this.updateToken);
};
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
if (this.appMain.isAuth) {
this.getWallets();
}
this.update();
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);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('tokenchange', this.updateToken);
appMain?.removeEventListener('walletupdate', this.updateToken);
};
getWallets = async (): Promise<void> => {
try {
const response = await this.walletService.getAll({ rpp: 3 });
this.setWallets(response.items, response.totalRecords);
} catch (err) {
this.update();
}
};
getWallets = async (): Promise<void> => {
try {
const response = await this.walletService.getAll({ rpp: 3 });
this.setWallets(response.items, response.totalRecords);
} catch (err) {
this.update();
}
};
setWallets = (wallets: Array<any>, totalWallets: number): void => {
this.walletData = wallets;
this.totalWallets = totalWallets;
this.update();
};
setWallets = (wallets: Array<any>, totalWallets: number): void => {
this.walletData = wallets;
this.totalWallets = totalWallets;
this.update();
};
updateToken = (): void => {
if (this.isAuth) {
this.getWallets();
} else {
this.update();
}
};
updateToken = (): void => {
if (this.isAuth) {
this.getWallets();
} else {
this.update();
}
};
get isAuth(): boolean {
if (this.appMain?.isAuth) {
return true;
}
return false;
}
get isAuth(): boolean {
if (this.appMain?.isAuth) {
return true;
}
return false;
}
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
>`
);
}
return null;
};
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>`
);
}
return null;
};
modalWallet = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("wallet-create");
}
};
modalWallet = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal('wallet-create');
}
};
modalTransaction = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("transaction-create");
}
};
modalTransaction = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal('transaction-create');
}
};
render = (): TemplateResult => {
const { isAuth, totalWallets, walletData } = this;
render = (): TemplateResult => {
const { isAuth, totalWallets, walletData } = this;
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}">${title}</menu-item>`;
};
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 => {
if (!isAuth) {
return regularMenu(path, title, action);
}
return html``;
};
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)
)}`;
}
return html``;
};
const menuHeader = (title) =>
html`<div class="menu-item menu-header">${title}</div>`;
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}">${title}</menu-item>`;
};
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 => {
if (!isAuth) {
return regularMenu(path, title, action);
}
return html``;
};
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))}`;
}
return html``;
};
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)}
<span class="menu-item divider"></span>
${authMenu("/logout", "Logout")}
${notAuthMenu("/login", "Login")}
${notAuthMenu("/register", "Register")}
</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)}
<span class="menu-item divider"></span>
${authMenu('/logout', 'Logout')} ${notAuthMenu('/login', 'Login')} ${notAuthMenu('/register', 'Register')}
</div>
`;
};
}
export type { AppMenuElement };

View File

@@ -1,14 +1,14 @@
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 {
@target modalElement: HTMLElement;
constructor() {
super();
}
@target modalElement: HTMLElement;
constructor() {
super();
}
elementConnected = (): void => {};
elementConnected = (): void => {};
}
export type { AppModalElement };

View File

@@ -1,148 +1,143 @@
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 {
public items: Array<any>;
@attr page: number;
@attr rpp: number;
@attr totalItems: number;
@attr autoInit: string;
public items: Array<any>;
@attr page: number;
@attr rpp: number;
@attr totalItems: number;
@attr autoInit: string;
private customRenderItems: () => TemplateResult;
private customRenderItem: (item: any) => TemplateResult;
fetchFunc: Function = () => {};
constructor() {
super();
}
private customRenderItems: () => TemplateResult;
private customRenderItem: (item: any) => TemplateResult;
fetchFunc: Function = () => {};
constructor() {
super();
}
elementConnected = (): void => {};
elementConnected = (): void => {};
attributeChangedCallback(): void {
this.update();
}
attributeChangedCallback(): void {
this.update();
}
setItems = (items): void => {
this.items = items;
this.update();
};
setItems = (items): void => {
this.items = items;
this.update();
};
setFetchFunc = async (fetchFunc: Function, autoInit?): Promise<void> => {
this.fetchFunc = fetchFunc;
if (autoInit) {
const options = {
rpp: this.rpp || 5,
page: this.page || 1,
};
this.executeFetch(options);
}
};
setFetchFunc = async (fetchFunc: Function, autoInit?): Promise<void> => {
this.fetchFunc = fetchFunc;
if (autoInit) {
const options = {
rpp: this.rpp || 5,
page: this.page || 1,
};
this.executeFetch(options);
}
};
setCustomRenderItems = (customRenderItems: () => TemplateResult) => {
this.customRenderItems = customRenderItems;
this.update();
};
setCustomRenderItems = (customRenderItems: () => TemplateResult) => {
this.customRenderItems = customRenderItems;
this.update();
};
setCustomRenderItem = (customRenderItem: (item: any) => TemplateResult) => {
this.customRenderItem = customRenderItem;
this.update();
};
setCustomRenderItem = (customRenderItem: (item: any) => TemplateResult) => {
this.customRenderItem = customRenderItem;
this.update();
};
executeFetch = async (options?): Promise<void> => {
if (!options) {
options = {
rpp: this.rpp || 5,
page: this.page || 1,
};
}
executeFetch = async (options?): Promise<void> => {
if (!options) {
options = {
rpp: this.rpp || 5,
page: this.page || 1,
};
}
try {
this.loader?.start?.();
const response = await this.fetchFunc(options);
this.loader?.stop?.();
this.setItems(response?.items);
this.totalItems = response?.totalRecords;
this.page = response?.page;
this.rpp = response?.rpp;
} catch (err) {
this.loader?.stop?.();
console.error(err);
}
};
try {
this.loader?.start?.();
const response = await this.fetchFunc(options);
this.loader?.stop?.();
this.setItems(response?.items);
this.totalItems = response?.totalRecords;
this.page = response?.page;
this.rpp = response?.rpp;
} catch (err) {
this.loader?.stop?.();
console.error(err);
}
};
pageBack = (): void => {
const { page } = this;
if (page > 1) {
this.page--;
this.executeFetch();
}
};
pageBack = (): void => {
const { page } = this;
if (page > 1) {
this.page--;
this.executeFetch();
}
};
pageNext = (): void => {
const { rpp, totalItems, page } = this;
const pageRange = Math.ceil(totalItems / rpp);
if (page < pageRange) {
this.page++;
this.executeFetch();
}
};
pageNext = (): void => {
const { rpp, totalItems, page } = this;
const pageRange = Math.ceil(totalItems / rpp);
if (page < pageRange) {
this.page++;
this.executeFetch();
}
};
render = (): TemplateResult => {
const { rpp, totalItems, page, items } = this;
render = (): TemplateResult => {
const { rpp, totalItems, page, items } = this;
const renderItem = this.customRenderItem
? this.customRenderItem
: (item) => html`<tr>
<td>${item.description}</td>
<td>${item.amount}</td>
</tr>`;
const renderItem = this.customRenderItem
? this.customRenderItem
: (item) => html`<tr>
<td>${item.description}</td>
<td>${item.amount}</td>
</tr>`;
const renderItems = this.customRenderItems
? this.customRenderItems
: () => {
if (this.loader && this.loader.loading) {
return html`<circle-loader></circle-loader>`;
} else {
if (items?.length > 0) {
return html`<div class="table">
${items?.map((item) => renderItem(item))}
</div>`;
}
return html``;
}
};
const renderItems = this.customRenderItems
? this.customRenderItems
: () => {
if (this.loader && this.loader.loading) {
return html`<circle-loader></circle-loader>`;
} else {
if (items?.length > 0) {
return html`<table>
${items?.map((item) => renderItem(item))}
</table>`;
}
return html``;
}
};
const renderPagination = () => {
if (totalItems > items?.length) {
const pageRange = Math.ceil(totalItems / rpp);
return html`
<div>
<button
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"
: ""}"
app-action="click:app-pagination#pageNext"
>
Next
</button>
</div>
`;
}
};
const renderPagination = () => {
if (totalItems > items?.length) {
const pageRange = Math.ceil(totalItems / rpp);
return html`
<div>
<button
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' : ''}"
app-action="click:app-pagination#pageNext"
>
Next
</button>
</div>
`;
}
};
return html`<div>${renderItems()} ${renderPagination()}</div>`;
};
return html`<div>${renderItems()} ${renderPagination()}</div>`;
};
}
export type { AppPaginationElement };

View File

@@ -1,14 +1,14 @@
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 {
@target rootElement: HTMLElement;
constructor() {
super();
}
@target rootElement: HTMLElement;
constructor() {
super();
}
elementConnected = (): void => {};
elementConnected = (): void => {};
}
export type { AppRootElement };

View File

@@ -1,24 +1,24 @@
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();
const _shadow = new WeakMap();
@controller
class AppShadowElement extends HTMLElement {
constructor() {
super();
_shadow.set(this, this.attachShadow({ mode: "closed" }));
}
@controller
class AppShadowElement extends HTMLElement {
constructor() {
super();
_shadow.set(this, this.attachShadow({ mode: 'closed' }));
}
connectedCallback() {
const _root = _shadow.get(this);
const _appMain = document.createElement("app-main");
const _style = document.createElement("style");
_style.innerHTML = style;
connectedCallback() {
const _root = _shadow.get(this);
const _appMain = document.createElement('app-main');
const _style = document.createElement('style');
_style.innerHTML = style;
_root.appendChild(_style);
_root.appendChild(_appMain);
}
}
_root.appendChild(_style);
_root.appendChild(_appMain);
}
}
})();

View File

@@ -1,14 +1,14 @@
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 {
@target slotElement: HTMLElement;
constructor() {
super();
}
@target slotElement: HTMLElement;
constructor() {
super();
}
elementConnected = (): void => {};
elementConnected = (): void => {};
}
export type { AppSlotElement };

View File

@@ -1,23 +1,21 @@
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 {
@attr size: string;
constructor() {
super();
}
@attr size: string;
constructor() {
super();
}
elementConnected = (): void => {
this.update();
};
elementConnected = (): void => {
this.update();
};
render = () => {
return html`<div
class="circle-loader ${this.size ? `-${this.size}` : ""}"
></div>`;
};
render = () => {
return html`<div class="circle-loader ${this.size ? `-${this.size}` : ''}"></div>`;
};
}
export type { CircleLoaderElement };

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,125 +1,119 @@
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 {
@attr name: string;
@attr type: string;
@attr label: string;
@attr rules: string;
@target main: HTMLElement;
@target inp: HTMLElement;
@closest appForm: AppFormElement;
error: string;
displayError: boolean;
randId: string;
constructor() {
super();
}
@attr name: string;
@attr type: string;
@attr label: string;
@attr rules: string;
@target main: HTMLElement;
@target inp: HTMLElement;
@closest appForm: AppFormElement;
error: string;
displayError: boolean;
randId: string;
constructor() {
super();
}
public elementConnected = (): void => {
this.randId = `${name}${randomId()}`;
this.update();
this.validate();
};
public elementConnected = (): void => {
this.randId = `${name}${randomId()}`;
this.update();
this.validate();
};
get valid(): boolean {
return !!this.error;
}
get valid(): boolean {
return !!this.error;
}
get required(): boolean {
return this.rules.includes("required");
}
get required(): boolean {
return this.rules.includes('required');
}
get _value() {
return (this.inp as HTMLInputElement)?.value;
}
get _value() {
return (this.inp as HTMLInputElement)?.value;
}
validate = (): boolean => {
let _return = true;
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;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll(
"{- name}",
firstUpper(this.name?.toString())
);
_return = false;
this.error = error;
}
});
if (_return) {
this.error = null;
}
return _return;
};
validate = (): boolean => {
let _return = true;
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;
} else {
if (validator.hasOwnProperty(rule)) {
valid = validator?.[rule]?.(value);
}
}
if (!valid) {
const error = validatorErrors[rule]?.replaceAll('{- name}', firstUpper(this.name?.toString()));
_return = false;
this.error = error;
}
});
if (_return) {
this.error = null;
}
return _return;
};
validateDisplay = () => {
if (!this.validate()) {
this.displayError = true;
} else {
this.displayError = false;
}
this.update();
};
validateDisplay = () => {
if (!this.validate()) {
this.displayError = true;
} else {
this.displayError = false;
}
this.update();
};
inputChange = (e) => {
this.validate();
this.appForm?.inputChange(e);
};
inputChange = (e) => {
this.validate();
this.appForm?.inputChange(e);
};
render = (): TemplateResult => {
const renderMessage = (label: string) => {
if (this.label) {
return html`<label for="${this.randId}"
>${this.label}${this.required ? " (*)" : ""}</label
>`;
}
return html``;
};
render = (): TemplateResult => {
const renderMessage = (label: string) => {
if (this.label) {
return html`<label for="${this.randId}">${this.label}${this.required ? ' (*)' : ''}</label>`;
}
return html``;
};
const renderError = (displayError: boolean, error: string) => {
if (displayError) {
return html`<span>${error}</span>`;
}
return html``;
};
const renderError = (displayError: boolean, error: string) => {
if (displayError) {
return html`<span>${error}</span>`;
}
return html``;
};
const renderInput = (type) => {
return html` <input
type="${this.type}"
data-target="input-field.inp"
app-action="
const renderInput = (type) => {
return html` <input
type="${this.type}"
data-target="input-field.inp"
app-action="
input:input-field#inputChange
blur:input-field#validateDisplay
"
/>`;
};
/>`;
};
return html`<div class="input-main" data-target="input-field.main">
${renderMessage(this.label)} ${renderInput(this.type)}
${renderError(this.displayError, this.error)}
</div>`;
};
return html`<div class="input-main" data-target="input-field.main">
${renderMessage(this.label)} ${renderInput(this.type)} ${renderError(this.displayError, this.error)}
</div>`;
};
}
export type { InputFieldElement };

View File

@@ -1,55 +1,47 @@
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 {
@attr path: string;
@attr title: string;
@attr customaction: string;
@target itemEl: HTMLElement;
@target customButton: HTMLDivElement;
constructor() {
super();
}
@attr path: string;
@attr title: string;
@attr customaction: string;
@target itemEl: HTMLElement;
@target customButton: HTMLDivElement;
constructor() {
super();
}
public elementConnected = (): void => {
if (!this.title && this.innerText) {
const _slottedText = this.innerText;
this.innerText = null;
this.title = _slottedText;
}
this.update();
this.appMain.addEventListener("routechanged", this.update);
};
public elementConnected = (): void => {
if (!this.title && this.innerText) {
const _slottedText = this.innerText;
this.innerText = null;
this.title = _slottedText;
}
this.update();
this.appMain.addEventListener('routechanged', this.update);
};
public elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("routechanged", this.update);
};
public elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('routechanged', this.update);
};
get current(): boolean {
return this.routerService.comparePath(this.path);
}
get current(): boolean {
return this.routerService.comparePath(this.path);
}
render = (): TemplateResult => {
return html`
<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>
`;
};
render = (): TemplateResult => {
return html`
<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>
`;
};
}
export type { MenuItemElement };

View File

@@ -1,70 +1,66 @@
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 {
@attr currentBalance: number;
@attr lastMonth: number;
@attr nextMonth: number;
@attr currency: string;
@attr custom: string;
@attr currentBalance: number;
@attr lastMonth: number;
@attr nextMonth: number;
@attr currency: string;
@attr custom: string;
fetchFunc: Function = () => {};
constructor() {
super();
}
fetchFunc: Function = () => {};
constructor() {
super();
}
elementConnected = (): void => {
this.executeFetch();
this.update();
};
elementConnected = (): void => {
this.executeFetch();
this.update();
};
attributeChangedCallback(): void {
this.update();
}
attributeChangedCallback(): void {
this.update();
}
executeFetch = async (options?): Promise<void> => {
const actionString = this.custom;
const submitFunc = findMethod(actionString, this.appMain);
executeFetch = async (options?): Promise<void> => {
const actionString = this.custom;
const submitFunc = findMethod(actionString, this.appMain);
try {
this.loader?.start?.();
await submitFunc(options);
this.loader?.stop?.();
} catch (err) {
this.loader?.stop?.();
console.error(err);
}
};
try {
this.loader?.start?.();
await submitFunc(options);
this.loader?.stop?.();
} catch (err) {
this.loader?.stop?.();
console.error(err);
}
};
render = (): TemplateResult => {
const { currentBalance, currency, lastMonth, nextMonth } = this;
render = (): TemplateResult => {
const { currentBalance, currency, lastMonth, nextMonth } = this;
const renderItem = (header, balance, currency) => html`<div>
<div>${header}</div>
<div><span>${balance}</span><span>${currency}</span></div>
</div>`;
const renderItem = (header, balance, currency) => html`<div>
<div>${header}</div>
<div><span>${balance}</span><span>${currency}</span></div>
</div>`;
const renderHeader = () => {
if (this.loader && this.loader.loading) {
return html`<circle-loader></circle-loader>`;
}
return html`${renderItem(
"Last Month",
lastMonth,
currency
)}${renderItem(
"Current Balance",
currentBalance,
currency
)}${renderItem("Next Month", nextMonth, currency)}`;
};
const renderHeader = () => {
if (this.loader && this.loader.loading) {
return html`<circle-loader></circle-loader>`;
}
return html`${renderItem('Last Month', lastMonth, currency)}${renderItem(
'Current Balance',
currentBalance,
currency
)}${renderItem('Next Month', nextMonth, currency)}`;
};
return html`<div>${renderHeader()}</div>`;
};
return html`<div>${renderHeader()}</div>`;
};
}
export type { WalletHeaderElement };

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,147 +1,100 @@
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> => {
headersParam = {
...headersParam,
Authorization: `BEARER ${this.appMain?.authStore?.token}`,
};
try {
this?.appMain?.appLoader?.start?.();
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 == 401) {
this.appMain.authStore.token = null;
this.appMain.routerService.goTo("/token-expired");
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
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);
this?.appMain?.appLoader?.stop?.();
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');
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
put = 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.put(url, data, headersParam);
this?.appMain?.appLoader?.stop?.();
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");
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
put = 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.put(url, data, headersParam);
this?.appMain?.appLoader?.stop?.();
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');
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
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
);
this?.appMain?.appLoader?.stop?.();
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");
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
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);
this?.appMain?.appLoader?.stop?.();
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');
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
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
);
this?.appMain?.appLoader?.stop?.();
if (
response?.statusCode == 400 ||
response?.statusCode == 500 ||
response?.statusCode == 401
) {
if (response?.statusCode == 401) {
this.appMain.routerService.goTo("/token-expired");
this.appMain.authStore.token = null;
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
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);
this?.appMain?.appLoader?.stop?.();
if (response?.statusCode == 400 || response?.statusCode == 500 || response?.statusCode == 401) {
if (response?.statusCode == 401) {
this.appMain.routerService.goTo('/token-expired');
this.appMain.authStore.token = null;
}
throw response;
}
return response;
} catch (err) {
this?.appMain?.appLoader?.stop?.();
throw err;
}
};
}
export default AppService;

View File

@@ -1,27 +1,27 @@
import { AppService } from "core/services";
import { AppService } from 'core/services';
class BaseService {
constructor(public endpoint: string, public appService: AppService) {}
constructor(public endpoint: string, public appService: AppService) {}
getAll = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint, params, headers);
};
getAll = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint, params, headers);
};
get = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint, params, headers);
};
get = (params?: Object, headers?: HeadersInit) => {
return this.appService.get(this.endpoint, params, headers);
};
put = (data?: Object, headers?: HeadersInit) => {
return this.appService.put(this.endpoint, data, headers);
};
put = (data?: Object, headers?: HeadersInit) => {
return this.appService.put(this.endpoint, data, headers);
};
post = (data?: Object, headers?: HeadersInit) => {
return this.appService.post(this.endpoint, data, headers);
};
post = (data?: Object, headers?: HeadersInit) => {
return this.appService.post(this.endpoint, data, headers);
};
delete = (data?: Object, headers?: HeadersInit) => {
return this.appService.delete(this.endpoint, data, headers);
};
delete = (data?: Object, headers?: HeadersInit) => {
return this.appService.delete(this.endpoint, data, headers);
};
}
export default BaseService;

View File

@@ -1,124 +1,119 @@
class HttpClient {
private url: string;
constructor() {
this.url = `${__CONFIG__.ssl ? "https" : "http"}://${
__CONFIG__.apiUrl
}/${__CONFIG__.apiVersion}`;
}
private url: string;
constructor() {
this.url = `${__CONFIG__.ssl ? 'https' : 'http'}://${__CONFIG__.apiUrl}/${__CONFIG__.apiVersion}`;
}
post(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
let body: BodyType = null;
if (data instanceof FormData) {
body = data;
} else {
body = JSON.stringify(data);
headers.append("Content-Type", "application/json");
}
let options: OptionsType = {
method: "POST",
headers: headers,
body: body,
};
const req: Request = new Request(resolveUrl(this.url, url), options);
post(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
let body: BodyType = null;
if (data instanceof FormData) {
body = data;
} else {
body = JSON.stringify(data);
headers.append('Content-Type', 'application/json');
}
let options: OptionsType = {
method: 'POST',
headers: headers,
body: body,
};
const req: Request = new Request(resolveUrl(this.url, url), options);
return createRequest(req);
}
return createRequest(req);
}
put(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append("Content-Type", "application/json");
let options: OptionsType = {
method: "PUT",
headers: headers,
body: JSON.stringify(data),
};
const req: Request = new Request(resolveUrl(this.url, url), options);
put(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append('Content-Type', 'application/json');
let options: OptionsType = {
method: 'PUT',
headers: headers,
body: JSON.stringify(data),
};
const req: Request = new Request(resolveUrl(this.url, url), options);
return createRequest(req);
}
return createRequest(req);
}
delete(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append("Content-Type", "application/json");
let options: OptionsType = {
method: "DELETE",
headers: headers,
body: JSON.stringify(data),
};
const req: Request = new Request(resolveUrl(this.url, url), options);
delete(url: string, data: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
headers.append('Content-Type', 'application/json');
let options: OptionsType = {
method: 'DELETE',
headers: headers,
body: JSON.stringify(data),
};
const req: Request = new Request(resolveUrl(this.url, url), options);
return createRequest(req);
}
return createRequest(req);
}
get(url: string, params: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
let options: OptionsType = {
method: "GET",
headers: headers,
};
let paramsPath: string = "";
if (params) {
let urlParams = new URLSearchParams(Object.entries(params));
paramsPath = "?" + urlParams;
}
const req: Request = new Request(
resolveUrl(this.url, url + paramsPath),
options
);
get(url: string, params: Object, headersParam: HeadersInit): Promise<any> {
let headers: Headers = new Headers(headersParam);
let options: OptionsType = {
method: 'GET',
headers: headers,
};
let paramsPath: string = '';
if (params) {
let urlParams = new URLSearchParams(Object.entries(params));
paramsPath = '?' + urlParams;
}
const req: Request = new Request(resolveUrl(this.url, url + paramsPath), options);
return createRequest(req);
}
return createRequest(req);
}
}
export default HttpClient;
async function createRequest(request: Request): Promise<Response> {
let response: Response = await fetch(request);
if (
!response.ok &&
response.status !== 403 &&
response.status !== 400 &&
response.status !== 401 &&
response.status !== 500
) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
if (response.headers.get("Content-Type") !== null) {
let newResponse: Response = await createResponse(response);
return newResponse;
}
return response;
}
let response: Response = await fetch(request);
if (
!response.ok &&
response.status !== 403 &&
response.status !== 400 &&
response.status !== 401 &&
response.status !== 500
) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
if (response.headers.get('Content-Type') !== null) {
let newResponse: Response = await createResponse(response);
return newResponse;
}
return response;
}
}
async function createResponse(response: Response): Promise<any> {
const type: string = response.headers.get("Content-Type");
const body = (): Promise<any> => {
if (type.indexOf("application/json") !== -1) {
return response.json();
}
return response.text();
};
const type: string = response.headers.get('Content-Type');
const body = (): Promise<any> => {
if (type.indexOf('application/json') !== -1) {
return response.json();
}
return response.text();
};
return body();
return body();
}
function resolveUrl(url: string, path: string): string {
if (path.includes("http") || path.includes("://")) {
return path;
}
const fixedPath = path
.split("/")
.filter((i) => i)
.join("/");
const urlWithPath = `${url.endsWith("/") ? url : `${url}/`}${fixedPath}`;
return urlWithPath;
if (path.includes('http') || path.includes('://')) {
return path;
}
const fixedPath = path
.split('/')
.filter((i) => i)
.join('/');
const urlWithPath = `${url.endsWith('/') ? url : `${url}/`}${fixedPath}`;
return urlWithPath;
}
type BodyType = string | FormData;
type OptionsType = {
method: string;
headers?: Headers;
body?: BodyType;
method: string;
headers?: Headers;
body?: BodyType;
};

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,344 +1,284 @@
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
) {}
private historyStack: Array<RouteState> = [];
private _routes: Array<RouteState> = [];
constructor(private appMain: AppMainElement, private mainRoot: ShadowRoot | HTMLElement) {}
get routerState(): RouteState {
const historyLen = this.historyStack?.length;
if (historyLen < 1) {
return null;
}
return this.historyStack[historyLen - 1];
}
get routerState(): RouteState {
const historyLen = this.historyStack?.length;
if (historyLen < 1) {
return null;
}
return this.historyStack[historyLen - 1];
}
get emptyState(): boolean {
const historyLen = this.historyStack?.length;
if (historyLen < 2) {
return true;
} else {
return false;
}
}
get emptyState(): boolean {
const historyLen = this.historyStack?.length;
if (historyLen < 2) {
return true;
} else {
return false;
}
}
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
);
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child) => {
const _childState: RouteState = this.createChildState(
child,
route
);
this._routes?.push(_childState);
});
}
this._routes?.push(_routeState);
});
};
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);
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child) => {
const _childState: RouteState = this.createChildState(child, route);
this._routes?.push(_childState);
});
}
this._routes?.push(_routeState);
});
};
public update = (): void => {
if (!this._routes) return;
const path = window.location.pathname;
const [hasDynamic, _dynamicIndex] = this.hasDynamicPath(path);
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 (
path == route?.path ||
route?.path == "/not-found" ||
(hasDynamic && this?._routes?.[_dynamicIndex]?.path == route?.path)
) {
let changed: boolean = false;
if (_mainRoot?.childNodes.length > 0) {
_mainRoot?.childNodes?.forEach?.((child: BaseLayoutElement) => {
if (
route.layout &&
route.layout.toUpperCase() === child.tagName &&
!child.compareTags(route.component.toUpperCase())
) {
changed = true;
child.setElement(route.component);
} else if (
route.layout &&
route.layout.toUpperCase() !== child.tagName
) {
changed = true;
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"
);
changed = true;
_mainRoot.replaceChild(_newElement, child);
}
});
} else {
if (route.layout) {
changed = true;
const _newElement = document.createElement(route.layout);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
_mainRoot.appendChild(_newElement);
(_newElement as BaseLayoutElement).setElement(
route.component
);
} else {
const _newElement = document.createElement(route.component);
_newElement.setAttribute(
"data-target",
"app-root.rootElement"
);
changed = true;
_mainRoot.appendChild(_newElement);
}
}
} else {
const [isDynamic, _dynamicIndex, dynamicProps] =
this.hasDynamicPath(path);
let newRoute: RouteState;
if (isDynamic && _dynamicIndex !== -1) {
newRoute = this._routes[_dynamicIndex];
newRoute.data = dynamicProps;
} else {
newRoute = this.findByPath();
}
this.historyStack.push(newRoute);
this.update();
}
this.appMain.dispatchEvent(this.appMain?.domEvents.routechanged);
};
public update = (): void => {
if (!this._routes) return;
const path = window.location.pathname;
const [hasDynamic, _dynamicIndex] = this.hasDynamicPath(path);
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 (
path == route?.path ||
route?.path == '/not-found' ||
(hasDynamic && this?._routes?.[_dynamicIndex]?.path == route?.path)
) {
let changed: boolean = false;
if (_mainRoot?.childNodes.length > 0) {
_mainRoot?.childNodes?.forEach?.((child: BaseLayoutElement) => {
if (
route.layout &&
route.layout.toUpperCase() === child.tagName &&
!child.compareTags(route.component.toUpperCase())
) {
changed = true;
child.setElement(route.component);
} else if (route.layout && route.layout.toUpperCase() !== child.tagName) {
changed = true;
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');
changed = true;
_mainRoot.replaceChild(_newElement, child);
}
});
} else {
if (route.layout) {
changed = true;
const _newElement = document.createElement(route.layout);
_newElement.setAttribute('data-target', 'app-root.rootElement');
_mainRoot.appendChild(_newElement);
(_newElement as BaseLayoutElement).setElement(route.component);
} else {
const _newElement = document.createElement(route.component);
_newElement.setAttribute('data-target', 'app-root.rootElement');
changed = true;
_mainRoot.appendChild(_newElement);
}
}
} else {
const [isDynamic, _dynamicIndex, dynamicProps] = this.hasDynamicPath(path);
let newRoute: RouteState;
if (isDynamic && _dynamicIndex !== -1) {
newRoute = this._routes[_dynamicIndex];
newRoute.data = dynamicProps;
} else {
newRoute = this.findByPath();
}
this.historyStack.push(newRoute);
this.update();
}
this.appMain.dispatchEvent(this.appMain?.domEvents.routechanged);
};
public goTo = (path: string, data?: any): void => {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const currentPath = window.location.pathname;
if (path == currentPath) return;
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);
if (isDynamic) {
const [isCurrentDynamic, currIndex] =
this.hasDynamicPath(currentPath);
if (path == currentPath) return;
}
let newRoute: RouteState;
if (isDynamic && _dynamicIndex !== -1) {
newRoute = this._routes[_dynamicIndex];
newRoute.data = dynamicProps;
} else if (_index === -1 && _indexOfEmpty !== -1) {
newRoute = this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
newRoute = new RouteState("/not-found", "not-found");
} else {
newRoute = this._routes[_index];
}
public goTo = (path: string, data?: any): void => {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const currentPath = window.location.pathname;
if (path == currentPath) return;
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);
if (isDynamic) {
const [isCurrentDynamic, currIndex] = this.hasDynamicPath(currentPath);
if (path == currentPath) return;
}
let newRoute: RouteState;
if (isDynamic && _dynamicIndex !== -1) {
newRoute = this._routes[_dynamicIndex];
newRoute.data = dynamicProps;
} else if (_index === -1 && _indexOfEmpty !== -1) {
newRoute = this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
newRoute = new RouteState('/not-found', 'not-found');
} else {
newRoute = this._routes[_index];
}
this.historyStack.push(newRoute);
const url = new URL(window.location.toString());
url.pathname = path;
window.history.pushState({}, "", url.toString());
this.update();
};
this.historyStack.push(newRoute);
const url = new URL(window.location.toString());
url.pathname = path;
window.history.pushState({}, '', url.toString());
this.update();
};
public goBack = (): void => {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const lenHistory = this.historyStack.length;
if (this.canGoBack) {
const nextRoute = this.historyStack[lenHistory - 2];
const url = new URL(window.location.toString());
url.pathname = nextRoute.path;
window.history.pushState({}, "", url.toString());
this.historyStack.pop();
}
this.update();
};
public goBack = (): void => {
if (!Array.isArray(this.historyStack)) this.historyStack = [];
const lenHistory = this.historyStack.length;
if (this.canGoBack) {
const nextRoute = this.historyStack[lenHistory - 2];
const url = new URL(window.location.toString());
url.pathname = nextRoute.path;
window.history.pushState({}, '', url.toString());
this.historyStack.pop();
}
this.update();
};
public get canGoBack(): boolean {
const lenHistory = this.historyStack.length;
if (lenHistory > 2) {
return true;
}
return false;
}
public get canGoBack(): boolean {
const lenHistory = this.historyStack.length;
if (lenHistory > 2) {
return true;
}
return false;
}
public init = (): void => {
window.addEventListener("popstate", () => {
this.historyStack.pop();
this.update();
});
this.update();
};
public init = (): void => {
window.addEventListener('popstate', () => {
this.historyStack.pop();
this.update();
});
this.update();
};
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"
);
if (_index === -1 && _indexOfEmpty !== -1) {
return this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
return new RouteState("/not-found", "not-found");
}
return this._routes[_index];
};
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');
if (_index === -1 && _indexOfEmpty !== -1) {
return this._routes[_indexOfEmpty];
} else if (_index === -1 && _indexOfEmpty === -1) {
return new RouteState('/not-found', 'not-found');
}
return this._routes[_index];
};
public comparePath = (path: string): boolean => {
if (this.routerState?.fullPath === path) {
return true;
}
return false;
};
public comparePath = (path: string): boolean => {
if (this.routerState?.fullPath === path) {
return true;
}
return false;
};
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
);
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);
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child2) => {
const _childState: RouteState = this.createChildState(
child2,
_child
);
this._routes?.push(_childState);
});
}
return _child;
};
if (Array.isArray(children) && children?.length > 0) {
children.forEach((child2) => {
const _childState: RouteState = this.createChildState(child2, _child);
this._routes?.push(_childState);
});
}
return _child;
};
private hasDynamicPath = (path: string): [boolean, number, any] => {
const _pathArr = path.split("/").filter((a) => a);
let matchedIndex: number = 0;
let matched: boolean = false;
let dynamicProps: any = {};
let shouldSkip = false;
this._routes.forEach((route, _routeId) => {
if (shouldSkip) {
return;
}
if (path == route.path) {
matched = path?.includes(":") ? true : false;
matchedIndex = _routeId;
shouldSkip = true;
}
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?.(":")) {
pathMatches++;
hasDynamic = true;
dynamicProps[_routeArr[i].substr(1)] = pathr;
}
});
if (pathMatches === _pathArr.length && hasDynamic) {
matchedIndex = _routeId;
matched = true;
shouldSkip = true;
}
}
});
return [matched, matchedIndex, dynamicProps];
};
private hasDynamicPath = (path: string): [boolean, number, any] => {
const _pathArr = path.split('/').filter((a) => a);
let matchedIndex: number = 0;
let matched: boolean = false;
let dynamicProps: any = {};
let shouldSkip = false;
this._routes.forEach((route, _routeId) => {
if (shouldSkip) {
return;
}
if (path == route.path) {
matched = path?.includes(':') ? true : false;
matchedIndex = _routeId;
shouldSkip = true;
}
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?.(':')) {
pathMatches++;
hasDynamic = true;
dynamicProps[_routeArr[i].substr(1)] = pathr;
}
});
if (pathMatches === _pathArr.length && hasDynamic) {
matchedIndex = _routeId;
matched = true;
shouldSkip = true;
}
}
});
return [matched, matchedIndex, dynamicProps];
};
}
class RouteState {
constructor(
public path: string,
public component: string,
public data?: any,
public layout?: string,
public middleware?: any
) {}
constructor(
public path: string,
public component: string,
public data?: any,
public layout?: string,
public middleware?: any
) {}
get fullPath(): string {
return resolvePath(this.path, this.data);
}
get fullPath(): string {
return resolvePath(this.path, this.data);
}
}
type DynamicProp = {
index: string;
path: string;
index: string;
path: string;
};
function resolvePath(path: string, data: any): string {
const _pathArr = path
.split("/")
.filter((a) => a)
.map((pathPart) => {
if (pathPart.startsWith(":")) {
pathPart = data?.[pathPart.substr(1)];
}
return pathPart;
});
let _return = ["", ..._pathArr].join("/");
if (_return == "") {
_return = "/";
}
return _return;
const _pathArr = path
.split('/')
.filter((a) => a)
.map((pathPart) => {
if (pathPart.startsWith(':')) {
pathPart = data?.[pathPart.substr(1)];
}
return pathPart;
});
let _return = ['', ..._pathArr].join('/');
if (_return == '') {
_return = '/';
}
return _return;
}
export default RouterService;

View File

@@ -1,98 +1,95 @@
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");
if (_token) this.token = _token;
this.authService = new AuthService(this.appService);
this.checkToken(_token);
}
private _token: string;
private _userDetails: UserDetails;
private authService: AuthService;
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;
return this._token;
}
get token(): string {
if (this._token == 'null') return null;
if (this._token == 'undefined') return undefined;
return this._token;
}
set token(token: string) {
const { _token } = this;
const _changed = token != _token;
console.log(token);
if (_changed) {
this._token = token;
localStorage.setItem("token", token);
this.appMain.dispatchEvent(this.appMain?.domEvents.tokenchange);
}
}
set token(token: string) {
const { _token } = this;
const _changed = token != _token;
console.log(token);
if (_changed) {
this._token = token;
localStorage.setItem('token', token);
this.appMain.dispatchEvent(this.appMain?.domEvents.tokenchange);
}
}
get user(): UserDetails {
return this._userDetails;
}
get user(): UserDetails {
return this._userDetails;
}
set user(userDetails: UserDetails) {
this._userDetails = userDetails;
}
set user(userDetails: UserDetails) {
this._userDetails = userDetails;
}
checkToken = async (token: string) => {
try {
if (token && token !== "null") {
const response = await this.authService.checkToken({ token });
if (!(response && response.valid)) {
this.token = null;
this.appMain.routerService.goTo("/token-expired");
}
}
} catch (err) {
this.token = null;
this.appMain.routerService.goTo("/token-expired");
}
};
checkToken = async (token: string) => {
try {
if (token && token !== 'null') {
const response = await this.authService.checkToken({ token });
if (!(response && response.valid)) {
this.token = null;
this.appMain.routerService.goTo('/token-expired');
}
}
} catch (err) {
this.token = null;
this.appMain.routerService.goTo('/token-expired');
}
};
userLogin = async (formObject) => {
try {
const response = await this.authService.login(formObject);
if (response?.token) {
this.token = response.token;
} else {
this.token = null;
localStorage.removeItem("token");
}
return response;
} catch (err) {
throw err;
}
};
userLogin = async (formObject) => {
try {
const response = await this.authService.login(formObject);
if (response?.token) {
this.token = response.token;
} else {
this.token = null;
localStorage.removeItem('token');
}
return response;
} catch (err) {
throw err;
}
};
userRegister = async (formObject) => {
try {
const response = await this.authService.register(formObject);
return response;
} catch (err) {
throw err;
}
};
userRegister = async (formObject) => {
try {
const response = await this.authService.register(formObject);
return response;
} catch (err) {
throw err;
}
};
userLogout = (): void => {
this.token = null;
localStorage.removeItem("token");
};
userLogout = (): void => {
this.token = null;
localStorage.removeItem('token');
};
}
export default AuthStore;
export type UserDetails = {
id: string;
username: string;
email: string;
dateCreated: string;
dateUpdated: string;
id: string;
username: string;
email: string;
dateCreated: string;
dateUpdated: string;
};

View File

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

View File

@@ -1,15 +1,15 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function closest(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findClosest(this, kebab);
},
});
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findClosest(this, kebab);
},
});
}
function findClosest(element: HTMLElement, key: string): HTMLElement {
return element.closest(key);
return element.closest(key);
}

View File

@@ -1,18 +1,15 @@
import { AppMainElement } from "components/";
import { AppMainElement } from 'components/';
export default function findMethod(
actionString: string,
appMain: AppMainElement
): Function {
if (actionString) {
const methodSep = actionString.lastIndexOf("#");
const tag = actionString.slice(0, methodSep);
const method = actionString.slice(methodSep + 1);
export default function findMethod(actionString: string, appMain: AppMainElement): Function {
if (actionString) {
const methodSep = actionString.lastIndexOf('#');
const tag = actionString.slice(0, methodSep);
const method = actionString.slice(methodSep + 1);
const element = appMain.querySelector(tag);
if (element) {
return element?.[method];
}
}
return () => {};
const element = appMain.querySelector(tag);
if (element) {
return element?.[method];
}
}
return () => {};
}

View File

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

View File

@@ -1,8 +1,8 @@
export default function index(proto: Object, key: string): Object {
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return Array.from(this.parentNode.children).indexOf(this);
},
});
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return Array.from(this.parentNode.children).indexOf(this);
},
});
}

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,15 +1,15 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function query(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findQuery(this, kebab);
},
});
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findQuery(this, kebab);
},
});
}
function findQuery(element: HTMLElement, key: string): HTMLElement {
return element.querySelector(key);
return element.querySelector(key);
}

View File

@@ -1,18 +1,15 @@
import { toKebabCase } from "core/utils";
import { toKebabCase } from 'core/utils';
export default function querys(proto: Object, key: string): any {
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findQuerys(this, kebab);
},
});
const kebab: string = toKebabCase(key);
return Object.defineProperty(proto, key, {
configurable: true,
get() {
return findQuerys(this, kebab);
},
});
}
function findQuerys(
element: HTMLElement,
key: string
): NodeListOf<HTMLElement> {
return element.querySelectorAll(key);
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, "-")
.toLowerCase();
return text
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/\s+/g, '-')
.toLowerCase();
}

View File

@@ -1,8 +1,8 @@
export default function update(proto: any, key?: string, dir?: any): any {
const method: Function = dir.value!;
dir.value = function () {
const _return = method.apply(this, arguments);
if (proto.update) proto.update.call(this);
return _return;
};
const method: Function = dir.value!;
dir.value = function () {
const _return = method.apply(this, arguments);
if (proto.update) proto.update.call(this);
return _return;
};
}

View File

@@ -1,21 +1,21 @@
<!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">
<title>Wallet Web</title>
</head>
<body>
<style>
body {
box-sizing: border-box;
margin: 0;
padding: 0;
background-color: #303030;
color: #ffffff;
}
</style>
<app-shadow></app-shadow>
</body>
</html>
<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" />
<title>Wallet Web</title>
</head>
<body>
<style>
body {
box-sizing: border-box;
margin: 0;
padding: 0;
background-color: #303030;
color: #ffffff;
}
</style>
<app-shadow></app-shadow>
</body>
</html>

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,31 +1,31 @@
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 {
@closest appMain: AppMainElement;
@target appPage: HTMLDivElement;
@closest appMain: AppMainElement;
@target appPage: HTMLDivElement;
constructor() {
super();
}
constructor() {
super();
}
elementConnected = (): void => {
this.update();
};
elementConnected = (): void => {
this.update();
};
elementDisconnected = (appMain: AppMainElement): void => {};
elementDisconnected = (appMain: AppMainElement): void => {};
render = (): TemplateResult => {
return html`
<div data-target="initial-layout.appPage">
<app-slot data-target="initial-layout.appSlot"></app-slot>
</div>
`;
};
render = (): TemplateResult => {
return html`
<div data-target="initial-layout.appPage">
<app-slot data-target="initial-layout.appSlot"></app-slot>
</div>
`;
};
}
export type { InitialLayoutElement };

View File

@@ -1,50 +1,50 @@
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 {
@closest appMain: AppMainElement;
@target appPage: HTMLDivElement;
@closest appMain: AppMainElement;
@target appPage: HTMLDivElement;
constructor() {
super();
}
constructor() {
super();
}
elementConnected = (): void => {
this.update();
this.appMain.addEventListener("tokenchange", this.updateAuth);
this.appMain.addEventListener("routechanged", this.updateAuth);
};
elementConnected = (): void => {
this.update();
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);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('tokenchange', this.updateAuth);
appMain?.removeEventListener('routechanged', this.updateAuth);
};
get isAuth(): boolean {
const _is = this.appMain?.routerService?.routerState?.middleware;
if (typeof _is == "function") {
return _is();
}
return !!_is;
}
get isAuth(): boolean {
const _is = this.appMain?.routerService?.routerState?.middleware;
if (typeof _is == 'function') {
return _is();
}
return !!_is;
}
updateAuth = (): void => {
this.update();
};
updateAuth = (): void => {
this.update();
};
render = (): TemplateResult => {
const _isAuth = this.isAuth;
return html`
<div data-target="menu-layout.appPage">
${_isAuth ? html`<app-menu></app-menu>` : html``}
<app-slot data-target="menu-layout.appSlot"></app-slot>
</div>
`;
};
render = (): TemplateResult => {
const _isAuth = this.isAuth;
return html`
<div data-target="menu-layout.appPage">
${_isAuth ? html`<app-menu></app-menu>` : html``}
<app-slot data-target="menu-layout.appSlot"></app-slot>
</div>
`;
};
}
export type { MenuLayoutElement };

View File

@@ -1,63 +1,57 @@
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 {
private transactionsService: TransactionsService;
@target pagination: AppPaginationElement;
constructor() {
super({
title: "Transaction History",
});
}
private transactionsService: TransactionsService;
@target pagination: AppPaginationElement;
constructor() {
super({
title: 'Transaction History',
});
}
elementConnected = (): void => {
this.transactionsService = new TransactionsService(
this.appMain?.appService
);
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener("tokenchange", this.update);
};
elementConnected = (): void => {
this.transactionsService = new TransactionsService(this.appMain?.appService);
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener('tokenchange', this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('tokenchange', this.update);
};
getTransactions = async (options): Promise<any> => {
try {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options["walletId"] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
getTransactions = async (options): Promise<any> => {
try {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options['walletId'] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
render = (): TemplateResult => {
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
return html`<span
>${this.routerService?.routerState?.data?.walletId}</span
>`;
}
return html``;
};
return html`<div>
${renderWallet()}
<app-pagination
data-target="history-page.pagination"
></app-pagination>
</div>`;
};
render = (): TemplateResult => {
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
return html`<span>${this.routerService?.routerState?.data?.walletId}</span>`;
}
return html``;
};
return html`<div>
${renderWallet()}
<app-pagination data-target="history-page.pagination"></app-pagination>
</div>`;
};
}
export type { HistoryPageElement };

View File

@@ -1,69 +1,69 @@
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 {
@target walletHeader: WalletHeaderElement;
private walletService: WalletService;
constructor() {
super({
title: "Home",
});
}
@target walletHeader: WalletHeaderElement;
private walletService: WalletService;
constructor() {
super({
title: 'Home',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.update();
this.appMain.addEventListener("tokenchange", this.update);
this.getBalance();
};
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.update();
this.appMain.addEventListener('tokenchange', this.update);
this.getBalance();
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('tokenchange', this.update);
};
getBalance = async (): Promise<void> => {
try {
const response = await this.walletService.getBalance();
this.setBalance(response);
} catch (err) {
throw err;
}
};
getBalance = async (): Promise<void> => {
try {
const response = await this.walletService.getBalance();
this.setBalance(response);
} catch (err) {
throw err;
}
};
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";
};
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';
};
openModal = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal("wallet-create");
}
};
openModal = (): void => {
const _modal = this.appMain.appModal;
if (_modal) {
this.appMain.closeModal();
} else {
this.appMain.createModal('wallet-create');
}
};
render = (): TemplateResult => {
return html`
<button app-action="click:home-page#openModal">New Wallet</button>
<wallet-header
data-target="home-page.walletHeader"
data-current-balance="0"
data-last-month="0"
data-next-month="0"
data-currency="0"
data-custom="home-page#getBalance"
></wallet-header>
`;
};
render = (): TemplateResult => {
return html`
<button app-action="click:home-page#openModal">New Wallet</button>
<wallet-header
data-target="home-page.walletHeader"
data-current-balance="0"
data-last-month="0"
data-next-month="0"
data-currency="0"
data-custom="home-page#getBalance"
></wallet-header>
`;
};
}
export { HomePageElement };

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,115 +1,107 @@
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 {
@targets inputs: Array<InputFieldElement>;
@target appForm: AppFormElement;
authService: AuthService;
constructor() {
super({
title: "Login",
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.update();
};
@targets inputs: Array<InputFieldElement>;
@target appForm: AppFormElement;
authService: AuthService;
constructor() {
super({
title: 'Login',
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.update();
};
get emailInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "email") {
return this.inputs[i];
}
}
}
get emailInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'email') {
return this.inputs[i];
}
}
}
get passwordInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "password") {
return this.inputs[i];
}
}
}
get passwordInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'password') {
return this.inputs[i];
}
}
}
get values(): Object {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
get values(): Object {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userLogin(
this.values
);
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userLogin(this.values);
if (response?.token) {
this.routerService.goTo("/");
}
} catch (err) {
if (err?.errorCode == 400103) {
this.emailInput.error = err?.message;
this.emailInput.update();
} else if (err?.errorCode == 400104) {
this.passwordInput.error = err?.message;
this.passwordInput.update();
} else {
this.appForm?.setError("Unable to log in!");
}
}
};
if (response?.token) {
this.routerService.goTo('/');
}
} catch (err) {
if (err?.errorCode == 400103) {
this.emailInput.error = err?.message;
this.emailInput.update();
} else if (err?.errorCode == 400104) {
this.passwordInput.error = err?.message;
this.passwordInput.update();
} else {
this.appForm?.setError('Unable to log in!');
}
}
};
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
render = (): TemplateResult => {
return html`
<app-form
data-custom="login-page#onSubmit"
data-target="login-page.appForm"
>
<input-field
data-type="email"
data-name="email"
data-label="E-mail"
data-targets="login-page.inputs"
data-rules="required|isEmail"
></input-field>
<input-field
data-type="password"
data-name="password"
data-label="Password"
data-targets="login-page.inputs"
data-rules="required"
>
</input-field>
</app-form>
<div>
<app-link
data-to="/register"
data-title="Create new account"
></app-link>
</div>
`;
};
render = (): TemplateResult => {
return html`
<app-form data-custom="login-page#onSubmit" data-target="login-page.appForm">
<input-field
data-type="email"
data-name="email"
data-label="E-mail"
data-targets="login-page.inputs"
data-rules="required|isEmail"
></input-field>
<input-field
data-type="password"
data-name="password"
data-label="Password"
data-targets="login-page.inputs"
data-rules="required"
>
</input-field>
</app-form>
<div>
<app-link data-to="/register" data-title="Create new account"></app-link>
</div>
`;
};
}
export type { LoginPageElement };

View File

@@ -1,20 +1,20 @@
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",
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.appMain?.authStore?.userLogout();
this.appMain?.routerService.goTo("/login");
};
authService: AuthService;
constructor() {
super({
title: 'Logout',
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.appMain?.authStore?.userLogout();
this.appMain?.routerService.goTo('/login');
};
}
export type { LogoutPageElement };

View File

@@ -1,24 +1,24 @@
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",
});
}
elementConnected = (): void => {
this.update();
};
constructor() {
super({
title: '404 - Not Found',
});
}
elementConnected = (): void => {
this.update();
};
render = (): TemplateResult => {
return html`
<div>404 - Page not found</div>
<div><app-link data-to="/" data-title="Homepage"></app-link></div>
`;
};
render = (): TemplateResult => {
return html`
<div>404 - Page not found</div>
<div><app-link data-to="/" data-title="Homepage"></app-link></div>
`;
};
}
export type { NotFoundElement };

View File

@@ -1,87 +1,82 @@
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 {
@targets inputs: Array<InputFieldElement>;
authService: AuthService;
constructor() {
super({
title: "Register",
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.update();
};
@targets inputs: Array<InputFieldElement>;
authService: AuthService;
constructor() {
super({
title: 'Register',
});
}
elementConnected = (): void => {
this.authService = new AuthService(this.appMain.appService);
this.update();
};
get values(): Object {
const formObject = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
get values(): Object {
const formObject = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userRegister(
this.values
);
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.appMain.authStore.userRegister(this.values);
if (response?.id) {
this.appMain.routerService.goTo("/login");
}
} catch (err) {}
};
if (response?.id) {
this.appMain.routerService.goTo('/login');
}
} catch (err) {}
};
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
render = (): TemplateResult => {
return html`
<app-form
data-custom="register-page#onSubmit"
data-has-cancel="true"
>
<input-field
data-type="text"
data-name="username"
data-label="Username"
data-targets="register-page.inputs"
data-rules="required"
></input-field>
<input-field
data-type="email"
data-name="email"
data-label="E-mail"
data-targets="register-page.inputs"
data-rules="required|isEmail"
></input-field>
<input-field
data-type="password"
data-name="password"
data-label="Password"
data-targets="register-page.inputs"
data-rules="required"
>
</input-field>
</app-form>
`;
};
render = (): TemplateResult => {
return html`
<app-form data-custom="register-page#onSubmit" data-has-cancel="true">
<input-field
data-type="text"
data-name="username"
data-label="Username"
data-targets="register-page.inputs"
data-rules="required"
></input-field>
<input-field
data-type="email"
data-name="email"
data-label="E-mail"
data-targets="register-page.inputs"
data-rules="required|isEmail"
></input-field>
<input-field
data-type="password"
data-name="password"
data-label="Password"
data-targets="register-page.inputs"
data-rules="required"
>
</input-field>
</app-form>
`;
};
}
export type { RegisterPageElement };

View File

@@ -1,130 +1,119 @@
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 {
@targets inputs: Array<InputFieldElement | AppDropdownElement>;
private transactionService: TransactionsService;
private walletService: WalletService;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: "New Transaction",
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.transactionService = new TransactionsService(
this.appMain?.appService
);
this.authService = new AuthService(this.appMain.appService);
this.update();
};
@targets inputs: Array<InputFieldElement | AppDropdownElement>;
private transactionService: TransactionsService;
private walletService: WalletService;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: 'New Transaction',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(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") {
return this.inputs[i];
}
}
}
get nameInput(): InputFieldElement | AppDropdownElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'name') {
return this.inputs[i];
}
}
}
get values(): any {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
get values(): any {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
getWallets = async (options): Promise<void> => {
try {
const response = await this.walletService.getAll(options);
return response;
} catch (err) {}
};
getWallets = async (options): Promise<void> => {
try {
const response = await this.walletService.getAll(options);
return response;
} catch (err) {}
};
onSubmit = async (values): Promise<void> => {
try {
if (!this.validate()) {
return;
}
onSubmit = async (values): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const {
description: description,
wallet: walletId,
amount,
} = values;
const { description: description, wallet: walletId, amount } = values;
const response = await this.transactionService.post({
description,
walletId,
amount,
});
const response = await this.transactionService.post({
description,
walletId,
amount,
});
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo("/history", {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = "Unable to create transaction!";
this.update();
}
};
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo('/history', {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = 'Unable to create transaction!';
this.update();
}
};
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form
data-custom="transaction-create#onSubmit"
data-has-cancel="true"
>
<input-field
data-type="number"
data-name="amount"
data-label="Amount"
data-targets="transaction-create.inputs"
data-rules="required"
></input-field>
<input-field
data-type="text"
data-name="description"
data-label="Description"
data-targets="transaction-create.inputs"
data-rules="required"
></input-field>
<app-dropdown
data-name="wallet"
data-label="Wallet"
data-targets="transaction-create.inputs"
data-rules="required"
data-fetch="transaction-create#getWallets"
>
</app-dropdown>
${this.errorMessage
? html`<div>${this.errorMessage}</div>`
: html``}
</app-form>
`;
};
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form data-custom="transaction-create#onSubmit" data-has-cancel="true">
<input-field
data-type="number"
data-name="amount"
data-label="Amount"
data-targets="transaction-create.inputs"
data-rules="required"
></input-field>
<input-field
data-type="text"
data-name="description"
data-label="Description"
data-targets="transaction-create.inputs"
data-rules="required"
></input-field>
<app-dropdown
data-name="wallet"
data-label="Wallet"
data-targets="transaction-create.inputs"
data-rules="required"
data-fetch="transaction-create#getWallets"
>
</app-dropdown>
${this.errorMessage ? html`<div>${this.errorMessage}</div>` : html``}
</app-form>
`;
};
}
export type { TransactionCreateElement };

View File

@@ -1,92 +1,87 @@
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 {
@targets inputs: Array<InputFieldElement>;
private walletService: WalletService;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: "New Wallet",
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.update();
};
@targets inputs: Array<InputFieldElement>;
private walletService: WalletService;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: 'New Wallet',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.update();
};
get nameInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == "name") {
return this.inputs[i];
}
}
}
get nameInput(): InputFieldElement {
for (const i in this.inputs) {
if (this.inputs[i]?.name == 'name') {
return this.inputs[i];
}
}
}
get values(): Object {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
get values(): Object {
const formObject: any = {};
this.inputs.forEach((input: InputFieldElement) => {
const inputType = input.inp;
formObject[input.name] = (inputType as HTMLInputElement).value;
});
return formObject;
}
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.walletService.post(this.values);
onSubmit = async (): Promise<void> => {
try {
if (!this.validate()) {
return;
}
const response = await this.walletService.post(this.values);
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo("/wallet/:walletId", {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = "Unable to create wallet!";
this.update();
}
};
if (response?.id) {
this.appMain.triggerWalletUpdate();
this.routerService.goTo('/wallet/:walletId', {
walletId: response.id,
});
}
} catch (err) {
this.errorMessage = 'Unable to create wallet!';
this.update();
}
};
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
validate(): boolean {
let _return = true;
this.inputs.forEach((input: InputFieldElement) => {
const valid: boolean = input.validate();
if (!valid) _return = false;
});
return _return;
}
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form
data-custom="wallet-create#onSubmit"
data-has-cancel="true"
>
<input-field
data-type="text"
data-name="name"
data-label="Name"
data-targets="wallet-create.inputs"
data-rules="required"
></input-field>
${this.errorMessage
? html`<div>${this.errorMessage}</div>`
: html``}
</app-form>
`;
};
render = (): TemplateResult => {
return html`
<div>Create wallet</div>
<app-form data-custom="wallet-create#onSubmit" data-has-cancel="true">
<input-field
data-type="text"
data-name="name"
data-label="Name"
data-targets="wallet-create.inputs"
data-rules="required"
></input-field>
${this.errorMessage ? html`<div>${this.errorMessage}</div>` : html``}
</app-form>
`;
};
}
export type { WalletCreateElement };

View File

@@ -1,50 +1,48 @@
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 {
@targets inputs: Array<InputFieldElement>;
private walletService: WalletService;
@target pagination: AppPaginationElement;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: "Wallet List",
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.update();
this.pagination?.setCustomRenderItem(this.renderItem);
this.pagination?.setFetchFunc?.(this.getWallets, true)!;
};
@targets inputs: Array<InputFieldElement>;
private walletService: WalletService;
@target pagination: AppPaginationElement;
authService: AuthService;
errorMessage: string;
constructor() {
super({
title: 'Wallet List',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.authService = new AuthService(this.appMain.appService);
this.update();
this.pagination?.setCustomRenderItem(this.renderItem);
this.pagination?.setFetchFunc?.(this.getWallets, true)!;
};
getWallets = async (options): Promise<any> => {
try {
const response = await this.walletService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
getWallets = async (options): Promise<any> => {
try {
const response = await this.walletService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
renderItem = (item): TemplateResult => html`<tr>
<td><app-link data-to="/wallet/${item.id}">${item.name}</app-link></td>
</tr>`;
renderItem = (item): TemplateResult => html`<tr>
<td><app-link data-to="/wallet/${item.id}">${item.name}</app-link></td>
</tr>`;
render = (): TemplateResult => {
return html`
<div>Wallets</div>
<app-pagination
data-target="wallet-list.pagination"
></app-pagination>
`;
};
render = (): TemplateResult => {
return html`
<div>Wallets</div>
<app-pagination data-target="wallet-list.pagination"></app-pagination>
`;
};
}
export type { WalletListElement };

View File

@@ -1,105 +1,95 @@
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 {
private transactionsService: TransactionsService;
private walletService: WalletService;
@target pagination: AppPaginationElement;
@target walletHeader: WalletHeaderElement;
walletId: string;
constructor() {
super({
title: "Wallet",
});
}
private transactionsService: TransactionsService;
private walletService: WalletService;
@target pagination: AppPaginationElement;
@target walletHeader: WalletHeaderElement;
walletId: string;
constructor() {
super({
title: 'Wallet',
});
}
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.transactionsService = new TransactionsService(
this.appMain?.appService
);
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
this.walletId = walletId;
}
}
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener("tokenchange", this.update);
};
elementConnected = (): void => {
this.walletService = new WalletService(this.appMain?.appService);
this.transactionsService = new TransactionsService(this.appMain?.appService);
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
this.walletId = walletId;
}
}
this.update();
this.pagination?.setFetchFunc?.(this.getTransactions, true)!;
this.appMain.addEventListener('tokenchange', this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener("tokenchange", this.update);
};
elementDisconnected = (appMain: AppMainElement): void => {
appMain?.removeEventListener('tokenchange', this.update);
};
getTransactions = async (options): Promise<any> => {
try {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options["walletId"] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
getTransactions = async (options): Promise<any> => {
try {
if (this?.routerService?.routerState?.data) {
const { walletId } = this?.routerService?.routerState?.data;
if (walletId) {
options['walletId'] = walletId;
}
}
const response = await this.transactionsService.getAll(options);
return response;
} catch (err) {
throw err;
}
};
getBalance = async (): Promise<void> => {
try {
const response = await this.walletService.getBalance({
walletId: this.walletId,
});
this.setBalance(response);
} catch (err) {
throw err;
}
};
getBalance = async (): Promise<void> => {
try {
const response = await this.walletService.getBalance({
walletId: this.walletId,
});
this.setBalance(response);
} catch (err) {
throw err;
}
};
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";
};
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';
};
render = (): TemplateResult => {
const renderHeader = () => html`<wallet-header
data-target="wallet-page.walletHeader"
data-current-balance="0"
data-last-month="0"
data-next-month="0"
data-currency="0"
data-custom="wallet-page#getBalance"
></wallet-header>`;
render = (): TemplateResult => {
const renderHeader = () => html`<wallet-header
data-target="wallet-page.walletHeader"
data-current-balance="0"
data-last-month="0"
data-next-month="0"
data-currency="0"
data-custom="wallet-page#getBalance"
></wallet-header>`;
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
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>
</div>`;
};
const renderWallet = () => {
if (this.routerService?.routerState?.data?.walletId) {
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>
</div>`;
};
}
export type { WalletPageElement };

View File

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

View File

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

View File

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

View File

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

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