repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
ES-UFABC/UFABCplanner
|
ufabc_planner-frontend/src/components/IconButton/index.ts
|
<reponame>ES-UFABC/UFABCplanner
export { default as IconButton } from './IconButton.component';
export type { IconBtnType } from './IconButton.component';
|
ES-UFABC/UFABCplanner
|
ufabc_planner-backend/src/modules/quarters/services/GetQuarterByAcademicYearIdService.ts
|
import { Quarter } from '@prisma/client';
import { IDateProvider } from 'infra/container/providers/DateProvider/IDateProvider';
import { AppError } from 'infra/http/errors/AppError';
import { IAcademicYearRepository } from 'modules/academicYears/repositories/IAcademicYearRepository';
import { injectable, inject } from 'tsyringe';
import { createQuarterDTO } from '../dtos/CreateQuarter.dto.';
import { GetQuarterByAcademicYearIdDTO } from '../dtos/GetQuarterByAcademicYearId.dto';
import { IQuarterRepository } from '../repositories/IQuarterRepository';
@injectable()
export class GetQuarterByAcademicYearIdService {
constructor(
@inject('PrismaAcademicYearRepository')
private academicYearRepository: IAcademicYearRepository,
@inject('PrismaQuarterRepository')
private QuarterRepository: IQuarterRepository
) {}
async execute(params: GetQuarterByAcademicYearIdDTO): Promise<Quarter[]> {
if (!(await this.academicYearRepository.exists(params.academicYearId))) {
throw new AppError('Ano acadêmico não existe');
}
const quarters = await this.QuarterRepository.getQuarterByAcademicYearId(params.academicYearId);
return quarters;
}
}
|
ES-UFABC/UFABCplanner
|
ufabc_planner-frontend/src/pages/dashboard/index.ts
|
<reponame>ES-UFABC/UFABCplanner
export { default as DashboardPage } from './DashboardPage.component';
|
ES-UFABC/UFABCplanner
|
ufabc_planner-frontend/src/components/MainLogo/MainLogo.component.tsx
|
import styles from './MainLogo.module.scss';
const MainLogo = () => {
return (
<div className={styles.logo}>
<img
src="/UFABCplanner_logo.svg"
alt="UFABCplanner_logo"
width="200px"
/>
</div>
);
}
export default MainLogo;
|
ES-UFABC/UFABCplanner
|
ufabc_planner-frontend/src/components/InitialPageLayout/index.ts
|
export { default as InitialPageLayout } from './InitialPageLayout.component';
|
ES-UFABC/UFABCplanner
|
ufabc_planner-backend/src/modules/exams/controllers/GetExamsBySubjectIdController.ts
|
<gh_stars>1-10
import { Request, Response } from 'express';
import { validateInput } from 'infra/http/errors/validation';
import { container } from 'tsyringe';
import { GetExamsBySubjectIdDTO } from '../dtos/GetExamsBySubjectId.dto';
import { GetExamsBySubjectIdService } from '../services/GetExamsBySubjectIdService';
export class GetExamsBySubjectIdController {
async execute(request: Request, response: Response) {
const { id } = request.params;
const getExamsBySubjectIdDTO = await validateInput(GetExamsBySubjectIdDTO, { id });
const exams = await container.resolve(GetExamsBySubjectIdService).handle(getExamsBySubjectIdDTO);
return response.json(exams).send();
}
}
|
ES-UFABC/UFABCplanner
|
ufabc_planner-backend/src/modules/quarters/services/UpdateQuarterService.ts
|
import { IDateProvider } from 'infra/container/providers/DateProvider/IDateProvider';
import { AppError } from 'infra/http/errors/AppError';
import { injectable, inject } from 'tsyringe';
import { createQuarterDTO } from '../dtos/CreateQuarter.dto.';
import { UpdateQuarterDTO } from '../dtos/UpdateQuarter.dto';
import { IQuarterRepository } from '../repositories/IQuarterRepository';
@injectable()
export class UpdateQuarterService {
constructor(
@inject('PrismaQuarterRepository')
private QuarterRepository: IQuarterRepository,
@inject('DayjsDateProvider')
private dateProvider: IDateProvider
) {}
async execute(params: UpdateQuarterDTO) {
const { id, startDate, endDate } = params;
const startDateUTC = this.dateProvider.toDate(startDate);
const endDateUTC = this.dateProvider.toDate(endDate);
if (this.dateProvider.compareIfBefore(startDateUTC, endDateUTC)) {
throw new AppError('Data final é antes da data inicial');
}
await this.QuarterRepository.updateQuarter({
id,
startDate: startDateUTC,
endDate: endDateUTC,
});
}
}
|
madhudskumar/ng2-music-app
|
app/music/albumbs.component.ts
|
import { Component } from '@angular/core';
@Component({
selector:'albumbs-component',
template:`
<h1>albumbs html</h1>
`
})
export class albumbsComponent { }
|
madhudskumar/ng2-music-app
|
app/test/test.component.ts
|
<reponame>madhudskumar/ng2-music-app<filename>app/test/test.component.ts
import { Component } from '@angular/core';
@Component({
selector:'test-component',
template:`
<h1>Test html</h1>
`
})
export class testComponent { }
|
madhudskumar/ng2-music-app
|
app/models/country/country.interface.ts
|
export interface iCountry{
alpha2code : string;
name : string;
}
|
madhudskumar/ng2-music-app
|
app/common/header.component.ts
|
import { Component } from '@angular/core';
@Component({
selector:'header-component',
template:`
<h1>header component what ?</h1>
`
})
export class headerComponent { }
|
madhudskumar/ng2-music-app
|
app/directives/forRange.directives.ts
|
<reponame>madhudskumar/ng2-music-app<gh_stars>0
import {Directive, Input, EmbeddedViewRef, TemplateRef, ViewContainerRef} from "@angular/core";
@Directive({
selector: '[forRange]'
})
export class ForRangeDirective{
constructor(
private _templateRef:TemplateRef,
private _viewContainer:ViewContainerRef
){}
@Input() set forRange(value:number){
this.render(value);
}
render(range:number){
for(let i = 0; i < range; i++){
var view:EmbeddedViewRef = this._viewContainer.createEmbeddedView(this._templateRef, i);
//view.setLocal("index", i);
//view.context.$implicit
}
}
}
|
madhudskumar/ng2-music-app
|
app/models/music/song.class.ts
|
<reponame>madhudskumar/ng2-music-app
import { iSong } from './music.interface';
export class Song implements iSong {
constructor(public name:string){
}
}
|
madhudskumar/ng2-music-app
|
app/common/country.service.ts
|
<reponame>madhudskumar/ng2-music-app
import { iCountry } from '../models/country/country.interface'
import { Country } from '../models/country/country.class'
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import {Observable} from "rxjs/Rx";
@Injectable()
export class counttryService{
constructor(
private _http:Http
){}
getCountries():Observable{
return new Observable(observable => {
this._http.get("https://restcountries.eu/rest/v1/all")
.map(res => {
res.json();
var countries:Array<iCountry> = [];
res.forEach(data => {
countries.push(new Country(data.name, data.alpha2Code));
})
return countries
})
.subscribe(res => {
observable.next(res);
})
})
}
}
|
madhudskumar/ng2-music-app
|
app/models/country/country.class.ts
|
import { iCountry } from './country.interface';
export class Country implements iCountry {
constructor(
public alpha2code : string,
public name : string
){}
}
|
madhudskumar/ng2-music-app
|
app/user/regestration.component.ts
|
import { Component } from '@angular/core';
@Component({
selector:'reg-component',
template:`
<h1>registration</h1>
`
})
export class regestrationComponent { }
|
madhudskumar/ng2-music-app
|
app/models/pagination/pager.interface.ts
|
<reponame>madhudskumar/ng2-music-app
export interface iPage{
itemsPerPage: number;
startIndex: number;
totalResults: number;
maxPages : number;
}
|
madhudskumar/ng2-music-app
|
app/app.route.ts
|
<reponame>madhudskumar/ng2-music-app
import { RouterConfig, provideRouter } from '@angular/router';
import { testComponent } from './test/test.component';
import { albumbComponent } from './music/albumb.component';
import { albumbsComponent } from './music/albumbs.component';
import { loginComponent } from './user/login.component';
import { regestrationComponent } from './user/regestration.component';
import { welcomeComponent } from './common/welcome.component';
const routes:RouterConfig = [
{path:'albumb', component:albumbComponent},
{path:'albumbs', component:albumbsComponent},
{path:'login', component:loginComponent},
{path:'registration', component:regestrationComponent},
{path:'test', component:testComponent},
{path:'', component:welcomeComponent},
{path:'**', redirectTo:'/test', pathMatch:'full'}
];
export const appRouterProvider = [
provideRouter(routes)
];
|
madhudskumar/ng2-music-app
|
app/common/welcome.component.ts
|
import { Component } from '@angular/core';
@Component({
selector:'welcome-component',
template:`
<h1 class="bg-success">welcome to the music app</h1>
`
})
export class welcomeComponent { }
|
madhudskumar/ng2-music-app
|
app/models/user/user.class.ts
|
import { iUser } from './user.interface';
export class User implements iUser {
username: string;
email: string;
password: string;
country: string;
birthday: Date;
constructor(authData:any){
this.email = authData.password.email;
}
}
|
madhudskumar/ng2-music-app
|
app/main.ts
|
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http'
import { appRouterProvider } from './app.route'
import { AppComponent } from './app.component';
bootstrap(AppComponent,[
HTTP_PROVIDERS,
appRouterProvider
]);
|
madhudskumar/ng2-music-app
|
app/music/music.service.ts
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http } from '@angular/http';
import { iSong, iAlbumb } from './../models/music/music.interface';
import { Song } from './../models/music/song.class';
import { Albumb } from './../models/music/albumb.class';
import { iPage } from './../models/pagination/pager.interface';
import { Pager } from './../models/pagination/pager.class';
@Injectable()
export class musicService{
private appId = "5ab4e37f6ddb7981825f118352e63f19";
constructor(
private _http:Http
){}
albumbSearch(query:string, page:number = 0) : Observable{
return new Observable(observable => {
let pageParam:string = page + 1;
let url = "http://ws.audioscrobbler.com/2.0/?method=album.search&album=" + query + "&page" + pageParam + "&format=json&api_key=" + this.appId;
this._http.get(url)
.map(res => {
res = res.json();
var albumbs:Array<Albumb> = [];
let results = res.results;
results.albumbmatches.albumb.forEach(data => {
albumbs.push(new Albumb(data["mbid"], data["name"], data["artist"], data["url"], data["image"]));
});
let pager:iPage = new Pager(<number>results["openserch:itemsParPage"], <number>results["opensearch:startIndex"], <number>results["opensearch:totalResults"]);
return{
albumbs : albumbs,
pager : pager
}
})
.subscribe(res => {
observable.next(res);
});
});
}
albumbInfo(id:string) : Observable{
return new Observable(observable => {
let url:string = "http://ws.audioscrobbler.com/2.0/?method=album.getInfo&mbid" + id + "&format=json&api_key=" + this.appId;
this._http.get(url)
.map(res => {
res = res.json();
let data = res.album;
var songs:Array<iSong> = [];
data.tracks.track.forEach(data => {
songs.push(new Song(data.name));
});
return new Albumb(data["mbid"], data["name"], data["artist"], data["url"], data["image"]);
})
.subscribe(res => {
observable.next(res);
});
})
}
}
|
madhudskumar/ng2-music-app
|
app/music/albumb.component.ts
|
<filename>app/music/albumb.component.ts
import { Component } from '@angular/core';
@Component({
selector:'albumb-component',
template:`
<h1>albumb</h1>
`
})
export class albumbComponent { }
|
madhudskumar/ng2-music-app
|
app/app.component.ts
|
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { headerComponent } from './common/header.component';
import { footerComponent } from './common/footer.component';
@Component({
selector: 'my-app',
template: `
<div class="container">
<header-component ></header-component>
</div>
<div class="container">
<router-outlet></router-outlet>
</div>
<div class="container">
<footer-component class="container"></footer-component>
</div>
`,
directives:[ ROUTER_DIRECTIVES, headerComponent, footerComponent]
})
export class AppComponent { }
|
madhudskumar/ng2-music-app
|
app/models/search/search.interface.ts
|
export interface iSearch{
query : string;
}
|
madhudskumar/ng2-music-app
|
app/models/music/music.interface.ts
|
<gh_stars>0
export interface iSong{
name:string;
}
export interface iAlbumb{
id: number,
name: string,
artist:string,
url: string,
images?: Array<string>,
songs?: Array<iSong>;
getImageSize(size:albumbImageSize);
}
export enum albumbImageSize{
LARGE = <any>"large",
MEDIUM = <any>"medium",
SMALL = <any>"small",
}
|
madhudskumar/ng2-music-app
|
app/models/music/albumb.class.ts
|
<filename>app/models/music/albumb.class.ts<gh_stars>0
import {iAlbumb, albumbImageSize} from './music.interface';
import { iSong } from './music.interface';
export class Albumb implements iAlbumb{
constructor(
public id: number,
public name: string,
public artist:string,
public url: string,
public images?: Array<string>,
public songs?: Array<iSong>
){};
getImageSize(size:albumbImageSize){
let image = this.images.find((image) => (image["size"] == size));
return image ? image["#text"]: undefined;
}
}
|
madhudskumar/ng2-music-app
|
app/user/login.component.ts
|
import { Component } from '@angular/core';
@Component({
selector:'login-component',
template:`
<h1>ogin</h1>
`
})
export class loginComponent { }
|
madhudskumar/ng2-music-app
|
app/models/user/user.interface.ts
|
export interface iUser{
username: string,
email: string,
password: <PASSWORD>,
country?: string,
birthday?: Date
}
|
madhudskumar/ng2-music-app
|
app/models/pagination/pager.class.ts
|
import { iPage } from './pager.interface';
export class Pager implements iPage{
public pages: number = 0;
constructor(
public itemsPerPage: number,
public startIndex: number,
public totalResults: number,
public maxPages : number = 10
){
let realMaxPages = Math.ceil(this.totalResults/this.itemsPerPage);
this.pages = realMaxPages <= this.maxPages ? realMaxPages : this.maxPages;
}
}
|
madhudskumar/ng2-music-app
|
app/user/user.service.ts
|
<reponame>madhudskumar/ng2-music-app
import { Observable } from 'rxjs/observable';
import { iUser } from '../models/user/user.interface';
import { User } from '../models/user/user.class';
import {error} from "util";
export class userServices{
firebaseUrl:string = "http://ng2-music.firebaseio.com";
firebaseRef:Firebase;
constructor(){
this.firebaseRef = new Firebase(this.firebaseUrl);
}
getUser() : Observable{
return new Observable(observable => {
this.firebaseRef.onAuth(() => {
let authData = this.firebaseRef.getAuth();
let user;
if(authData){
user = new User(authData);
}
observable.next(authData);
});
});
}
login(userName:string, password:string) : Observable {
return new Observable(observable => {
this.firebaseRef.authWithPassword({
email : userName,
password : password
}, (error, authData) => {
if(error){
observable.error(error);
}else{
observable.next(authData);
}
})
})
}
register(userName:string, email:string, password:string, country?:string, birthday?:Date) : Observable{
return new Observable(observable => {
this.firebaseRef.createUser({
userName:userName,
email:email,
password:password
}, (error, userData) => {
if(error) observable.error(error);
else observable.next(userData);
})
})
}
logout(): Observable{
return new Observable(observable => {
this.firebaseRef.unauth();
observable.next();
});
}
}
|
madhudskumar/ng2-music-app
|
app/directives/hilight.directive.ts
|
import {Directive, Input, ElementRef} from "@angular/core";
@Directive({
selector:'hilight',
host:{
'(mouseenter)':'onMouseEnter()',
'(mouseleave)':'onMouseLeave()'
}
})
export class HilightDirective{
private _activeColor = "red";
private _originalColor;
constructor(
private el:ElementRef
){
this._originalColor = el.nativeElement.style.backgroundColor;
}
@Input() hoverColor:string;
@Input() set activeColor(color:string){
this._activeColor = color || this._activeColor;
}
onMouseEnter(){
this.setBackgroundColor(this._activeColor);
}
onMouseLeave(){
this.setBackgroundColor(this._originalColor);
}
setBackgroundColor = (color:string) => this.el.nativeElement.style.backgroundColor = color;
}
|
madhudskumar/ng2-music-app
|
app/common/footer.component.ts
|
<gh_stars>0
import { Component } from '@angular/core';
@Component({
selector:'footer-component',
template:`
<h1>this is footer</h1>
`
})
export class footerComponent { }
|
madhudskumar/ng2-music-app
|
app/common/pagination.component.ts.ts
|
import { Component } from '@angular/core';
@Component({
selector:'pagination-component',
template:`
<h1>Test html</h1>
`
})
export class paginationComponent { }
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/meal.service.spec.ts
|
import { TestBed, inject } from '@angular/core/testing';
import { Meal.Service } from './meal.service';
describe('Meal.Service', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [Meal.ServiceService]
});
});
it('should be created', inject([Meal.Service], (service: Meal.Service) => {
expect(meal).toBeTruthy();
}));
});
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/update-client/update-client.component.ts
|
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ClientService } from '../client.service';
import { Client } from '../client.model';
import { Router } from '@angular/router';
import * as firebase from 'firebase';
@Component({
selector: 'app-update-client',
templateUrl: './update-client.component.html',
styleUrls: ['./update-client.component.css'],
providers: [ClientService]
})
export class UpdateClientComponent implements OnInit {
@Input() selectedClient;
@Input() clientId;
@Input() showEdit = false;
@Input() hideOpt = true;
@Output() clickSender = new EventEmitter();
@Output() clickSender2 = new EventEmitter();
message: string;
constructor(private clientService: ClientService, private router: Router) { }
ngOnInit() {
}
beginUpdatingClient(clientToUpdate, id) {
this.clientService.updateClient(clientToUpdate, id).then(() => {
this.message = 'Client Updated';
this.clickSender2.emit(this.message);
this.clickSender.emit(null);
})
.catch(function(error) {
this.message = 'error: ' + error;
this.clickSender2.emit(this.message);
});
this.showEdit = false;
this.hideOpt = true;
}
beginUpdatingOpt(clientToUpdate, id) {
this.clientService.updateOpt(clientToUpdate, id).then(() => {
this.message = 'Opt Status Updated.';
this.clickSender2.emit(this.message);
this.clickSender.emit(null);
})
.catch(function(error) {
this.message = 'error: ' + error;
this.clickSender2.emit(this.message);
});
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/client.service.ts
|
import { Injectable } from '@angular/core';
import { Client } from './client.model';
import { Observable } from 'rxjs/Observable';
import { AngularFirestore } from 'angularfire2/firestore';
import { masterCodConfig } from './api-keys';
@Injectable()
export class ClientService {
clients: Observable<any[]>;
message: string;
test: any;
constructor(private database: AngularFirestore ) {
this.clients = database.collection('clients').snapshotChanges()
.map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Client;
const id = a.payload.doc.id;
return{ id, data };
});
});
}
getClients() {
return this.clients;
}
getClientById(clientId: string) {
return this.database.doc('clients/' + clientId).valueChanges();
}
createClient(client) {
return this.database.collection('clients').add(client);
}
updateClient(localUpdateClient, id) {
const clientEntryInFirebase = this.database.collection('clients').doc(id);
return clientEntryInFirebase.update({name: localUpdateClient.name,
address: localUpdateClient.address,
zip: localUpdateClient.zip,
account: localUpdateClient.account,
statement: localUpdateClient.statement,
phone: localUpdateClient.phone,
carrier: localUpdateClient.carrier,
plan: localUpdateClient.plan,
email: localUpdateClient.email,
allergies: localUpdateClient.allergies,
delivery: localUpdateClient.delivery,
payment: localUpdateClient.payment,
opt: localUpdateClient.opt});
}
deleteClient(id) {
this.database.collection('clients').doc(id).delete();
}
updateOpt(clientToUpdate, id) {
let clientEntryInFirebase = this.database.collection('clients').doc(id);
return clientEntryInFirebase.update({opt: clientToUpdate.opt});
}
getClientCoordinates(coordinateArray) {
let clientAddressQueries = [];
this.clients.subscribe( (resClients) => {
let output = [];
(resClients).forEach(function(client) {
let street = client.data.address;
let zip = client.data.zip;
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + street + ' ' + zip + '&key=' + masterCodConfig.apiKey;
let name = client.data.name;
clientAddressQueries.push([name ,url]);
});
for(let i in clientAddressQueries){
this.getLatAndLng(clientAddressQueries[i][0], clientAddressQueries[i][1], coordinateArray);
}
});
}
getLatAndLng( name, url, coordinateArray ) {
let request = new XMLHttpRequest();
let output = [];
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
let response = JSON.parse(this.responseText);
let latitude = response.results[0].geometry.location.lat;
let longitude = response.results[0].geometry.location.lng;
output.push([latitude, longitude]);
coordinateArray.push([name, latitude, longitude]);
}
};
request.open("GET", url, true);
request.send();
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/admin-guard.service.ts
|
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import { AuthenticationService } from './authentication.service';
import * as firebase from 'firebase/app';
@Injectable()
export class AdminGuardService implements CanActivate {
user;
isLoggedIn;
userEmail;
constructor(private router: Router, public authService: AuthenticationService) {
this.authService.user.subscribe(user => {
if (user == null) {
this.isLoggedIn = false;
} else {
this.isLoggedIn = true;
this.userEmail = user.email;
}
});
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
if (this.check()){
if (this.authService.afAuth.auth.currentUser.uid === "k8dMvjdri2YqHgGmlIqXe8893s32") {
return Observable.of(true)
}else{
this.router.navigate(['']);
alert("Access Denied")
return Observable.of(false)
}
}else{
this.router.navigate(['']);
alert("Access Denied")
return Observable.of(false)
}
}
check(){
if (this.authService.afAuth.auth.currentUser) {
return true
}else{
return false
}
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/app.module.ts
|
<filename>src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routing } from './app.routing';
import { AngularFirestoreModule } from 'angularfire2/firestore';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { masterMapConfig, masterFirebaseConfig, masterCodConfig } from './api-keys';
import { LoginComponent } from './login/login.component';
import { ClientListComponent } from './client-list/client-list.component';
import { ClientDetailComponent } from './client-detail/client-detail.component';
import { MapComponent } from './map/map.component';
import { PaymentComponent } from './payment/payment.component';
import { AuthenticationService} from './authentication.service';
import { AuthGuardService} from './auth-guard.service';
import { AdminGuardService} from './admin-guard.service';
import { CreateClientComponent } from './create-client/create-client.component';
import { MealService} from './meal.service';
import { MealComponent} from './meal/meal.component';
import { AgmCoreModule } from '@agm/core';
import { AgmSnazzyInfoWindowModule } from '@agm/snazzy-info-window';
import { UpdateClientComponent } from './update-client/update-client.component';
import { OptnessPipe } from './optness.pipe';
export const firebaseConfig = {
apiKey: masterFirebaseConfig.apiKey,
authDomain: masterFirebaseConfig.authDomain,
databaseURL: masterFirebaseConfig.databaseURL,
storageBucket: masterFirebaseConfig.storageBucket,
messagingSenderId: masterFirebaseConfig.messagingSenderId,
projectId: masterFirebaseConfig.projectId
};
@NgModule({
declarations: [
AppComponent,
LoginComponent,
ClientListComponent,
ClientDetailComponent,
MealComponent,
MapComponent,
PaymentComponent,
CreateClientComponent,
UpdateClientComponent,
OptnessPipe
],
imports: [
AngularFirestoreModule,
BrowserModule,
CommonModule,
routing,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule,
AgmCoreModule.forRoot({
apiKey: masterMapConfig.apiKey
}),
AgmSnazzyInfoWindowModule
],
providers: [
AuthGuardService,
AuthenticationService,
AdminGuardService,
MealService
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/map/map.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { MapService } from '../map.service';
import { Client } from '../client.model';
import { Router } from '@angular/router';
import { ClientService } from '../client.service';
import * as firebase from 'firebase';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css'],
providers: [ ClientService ]
})
export class MapComponent implements OnInit {
clientCoordinates = [];
clients: Observable<any[]>;
clientsToDisplay;
constructor(private clientService: ClientService, private router: Router) { }
ngOnInit() {
this.clientService.getClientCoordinates(this.clientCoordinates);
this.clients = this.clientService.getClients();
this.clients.subscribe(dataLastEmittedFromObserver => {
this.clientsToDisplay = dataLastEmittedFromObserver;
});
}
testMethod() {
const addresses = [];
for (let client of this.clientsToDisplay) {
if (client.data.opt === "true") {
const address = '+' + (client.data.address).replace(/\s/g, '+') + '+';
const zip = (client.data.zip) + '/';
const link = (address + zip);
addresses.push(link);
}
}
const addressesString = addresses.toString();
const clientsURL = 'https://www.google.com/maps/dir/' + addressesString;
window.open(clientsURL);
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/optness.pipe.spec.ts
|
import { OptnessPipe } from './optness.pipe';
describe('OptnessPipe', () => {
it('create an instance', () => {
const pipe = new OptnessPipe();
expect(pipe).toBeTruthy();
});
});
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/map.service.ts
|
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MapService {
constructor() {}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/meal.model.ts
|
<gh_stars>1-10
export class Meal {
constructor(
public meal: string,
public date: string,
) {}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/client-detail/client-detail.component.ts
|
import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { Client } from '../client.model';
import { ClientService } from '../client.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import * as firebase from 'firebase';
@Component({
selector: 'app-client-detail',
templateUrl: './client-detail.component.html',
styleUrls: ['./client-detail.component.css'],
providers: [ ClientService ]
})
export class ClientDetailComponent implements OnInit {
clients: Observable<any[]>;
client;
clientObservable;
clientToDisplay;
clientFireObject;
clientId;
message;
optHide: boolean = true;
edit: boolean = false;
constructor(private route: ActivatedRoute, private location: Location, private clientService: ClientService, private router: Router) {}
ngOnInit() {
// this.client = this.clientService.getClientById()
this.route.params.forEach((urlParameters) => {
this.clientId = urlParameters['id'];
});
this.clientFireObject = this.clientService.getClientById(this.clientId);
this.clientService.getClientById(this.clientId).subscribe(dataLastEmittedFromObserver => {
this.clientToDisplay = dataLastEmittedFromObserver;
});
}
// this.clientToDisplay = this.clientService.getClientById(this.clientId);
// this.clientObservable =
// this.itemService.getClientById(this.clientId).subscribe(dataLastEmittedFromObserver=>{
// this.clientObservable = dataLastEmittedFromObserver;
// console.log(this.clientObservable);
// });
beginEditingClient() {
this.edit = true;
this.optHide = false;
}
finishEdit(status) {
this.edit = status;
}
setMessage(update) {
this.message = update;
}
messageColor(message) {
if (message === "Client Updated" || message === "Opt Status Updated.") {
return "success card";
} else {
return "error card";
}
}
beginDeletingClient(id) {
if (confirm("Are you sure you want to delete this Client?")) {
this.clientService.deleteClient(id);
this.router.navigate(['clients']);
}
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/optness.pipe.ts
|
import { Pipe, PipeTransform } from '@angular/core';
import { Client } from './client.model';
@Pipe({
name: "optness",
pure: false
})
export class OptnessPipe implements PipeTransform {
transform(input: Client[], optStatus) {
let output: Client[] = [];
for (let i = 0; i < input.length; ++i) {
if (input[i].opt === true) {
output.push(input[i]);
}
}
return output;
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/meal.service.ts
|
import { Injectable } from '@angular/core';
import { Meal } from './meal.model';
import { Observable } from 'rxjs/Observable';
import { AngularFirestore } from 'angularfire2/firestore';
@Injectable()
export class MealService {
meals: Observable<any[]>;
constructor(private database: AngularFirestore) {
this.meals = database.collection('meals').snapshotChanges()
.map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Meal;
const id = a.payload.doc.id;
return{ id, data };
});
});
}
getMealsByDate() {
return this.database.collection('meals', ref => ref.orderBy('date')).snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Meal;
const id = a.payload.doc.id;
return{ id, data };
});
});
}
getMeals() {
return this.meals;
}
getMealById(mealId: string) {
return this.database.doc('meals/' + mealId).valueChanges();
}
createMeal(meal) {
return this.database.collection('meals').add(meal);
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/client.model.ts
|
<reponame>MikeAlphaBravo/Food_Delivery_Manager<filename>src/app/client.model.ts
export class Client {
constructor(
public name: string,
public address: string,
public zip: number,
public account: number,
public statement: number,
public phone: string,
public carrier: string,
public plan: string,
public email: string,
public allergies: string,
public delivery: string,
public payment: string,
public opt: boolean
) {}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/meal/meal.component.ts
|
<reponame>MikeAlphaBravo/Food_Delivery_Manager
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { Meal } from '../meal.model';
import { MealService } from '../meal.service';
import { ClientService } from '../client.service';
import { Client } from '../client.model';
import * as firebase from 'firebase';
@Component({
selector: 'app-meal',
templateUrl: './meal.component.html',
styleUrls: ['./meal.component.css'],
providers: [ MealService, ClientService ]
})
export class MealComponent implements OnInit {
// meals: Observable<any[]>;
clients: Observable<any[]>;
mealsDate: Observable<any[]>;
clientsToDisplay;
selectedMeal;
showWeek = false;
showBiweek1 = false;
showBiweek2 = false;
mealCount = 0;
constructor(private router: Router, private mealService: MealService, private clientService: ClientService) { }
ngOnInit() {
// this.meals = this.mealService.getMeals();
this.clients = this.clientService.getClients();
this.mealsDate = this.mealService.getMealsByDate();
this.showMeal("weekly");
}
submitForm(meal: string, date: string) {
const newMeal: Object = ({meal: meal, date: date});
this.mealService.createMeal(newMeal);
}
showMeal(meal) {
if (meal === "weekly") {
this.showWeek = true;
this.showBiweek1 = false;
this.showBiweek2 = false;
} else if (meal === "biweekly1") {
this.showBiweek1 = true;
this.showWeek = false;
this.showBiweek2 = false;
} else if (meal === "biweekly2") {
this.showBiweek2 = true;
this.showWeek = false;
this.showBiweek1 = false;
}
}
}
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/app.routing.ts
|
<filename>src/app/app.routing.ts
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { PaymentComponent } from './payment/payment.component';
import { ClientListComponent } from './client-list/client-list.component';
import { ClientDetailComponent } from './client-detail/client-detail.component';
import { MealComponent } from './meal/meal.component';
import { MapComponent } from './map/map.component';
import { AuthGuardService } from './auth-guard.service';
import { AdminGuardService} from './admin-guard.service';
import { CreateClientComponent} from './create-client/create-client.component';
const appRoutes: Routes = [
{
path: '',
component: LoginComponent
},
{
path: 'clients',
component: ClientListComponent,
canActivate: [ AdminGuardService]
},
{
path: 'map',
component: MapComponent,
canActivate: [ AdminGuardService]
},
{
path: 'client/:id',
component: ClientDetailComponent,
canActivate: [ AdminGuardService]
},
{
path: 'create',
component: CreateClientComponent,
canActivate: [AuthGuardService, AdminGuardService]
},
{
path: 'meals',
component: MealComponent
}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
|
MikeAlphaBravo/Food_Delivery_Manager
|
src/app/create-client/create-client.component.ts
|
<reponame>MikeAlphaBravo/Food_Delivery_Manager
import { Component, OnInit } from '@angular/core';
import { ClientService } from '../client.service';
import { Client } from '../client.model';
import * as firebase from 'firebase';
@Component({
selector: 'app-create-client',
templateUrl: './create-client.component.html',
styleUrls: ['./create-client.component.css'],
providers: [ ClientService ]
})
export class CreateClientComponent implements OnInit {
message: string;
constructor(private clientService: ClientService) { }
submitForm(name: string, address: string, zip: number, phone: string, carrier: string, plan: string, email: string, allergies: string, delivery: string, payment: string, opt: boolean) {
let newClient: Object= ({name: name, address: address, zip: zip, account: 0, statement: 0, phone: phone, carrier: carrier, plan: plan, email: email, allergies: allergies, delivery: delivery, payment: payment, opt: opt});
this.clientService.createClient(newClient).then(() => {
this.message = 'Client Added';
})
.catch(function(error) {
this.message = 'error: ' + error;
});
}
messageColor(message) {
if (message === 'Client Added') {
return 'success card';
} else {
return 'error card';
}
}
ngOnInit() {
}
}
|
ContentPI/lib
|
src/object/index.ts
|
// Dependencies
import dot from 'dot-object'
// Utils
import { isBrowser, isObject, isDefined, isJson, isArray } from '../is'
interface iData {
_DEBUG: string
}
interface iNode {
key: string
value: string
}
export function cloneObject(o: any): any {
return { ...o }
}
export function getDebug(data: iData): any {
if (data._DEBUG) {
return JSON.parse(data._DEBUG)
}
return null
}
export function keys(obj: any): any[] {
if (isObject(obj)) {
return Object.keys(obj)
}
return []
}
export function forEach(items: any, callback: any): any {
if (!isDefined(items)) {
return false
}
if ((isDefined(items) && isDefined(items[0])) || isArray(items)) {
return items.forEach(callback)
}
return isObject(items) ? keys(items).forEach(callback) : false
}
export function pick(key: string, obj: any): string {
return dot.pick(key, obj) || key
}
export function buildContentJson(nodes: iNode[], raw?: boolean) {
const rows: any = {}
forEach(nodes, (node: iNode) => {
rows[node.key] = node.value
})
if (!raw) {
dot.object(rows)
}
return rows
}
export function objectToDot(nodes: any): any {
if (isObject(nodes)) {
return dot.dot(nodes)
}
return null
}
export function hasOwnProperty(obj: any, prop: string): boolean {
return Object.prototype.hasOwnProperty.call(obj, prop)
}
export function getStorageItem(key: string, returnJson = true): any {
if (!isBrowser() || !localStorage) {
return null
}
const item = localStorage.getItem(key) || ''
if (returnJson && isJson(item)) {
return JSON.parse(item)
}
return item
}
export function setStorageItem(key: string, value: any): any {
if (isBrowser() && key && value && localStorage) {
if (isObject(value)) {
value = JSON.stringify(value)
}
localStorage.setItem(key, value)
return true
}
return null
}
export function removeStorageItem(key: string): void {
if (isBrowser() && key && localStorage) {
localStorage.removeItem(key)
}
}
export function clearStorage(): void {
if (isBrowser() && localStorage) {
localStorage.clear()
}
}
|
ContentPI/lib
|
src/string/index.ts
|
<gh_stars>0
import { isString } from '../is'
import { words } from '../utils'
export function capitalize(str: string): string {
if (!isString(str)) {
return ''
}
return str.charAt(0).toUpperCase() + str.slice(1)
}
export function camelCase(str: string): string {
return words(str.replace(/['\u2019]/g, '')).reduce(
(result: string, word: string, index: number) => {
word = word.toLowerCase()
return result + (index ? capitalize(word) : word)
},
''
)
}
export function arrayIn(arr: string[], str: string): boolean {
let found = false
arr.forEach((item: string) => {
if (str.includes(item)) {
found = true
}
})
return found
}
export function pluralify(singular: string, plural: string, count: number): string {
return count === 1 ? singular : plural
}
|
ContentPI/lib
|
src/array/index.ts
|
export function chunk(arr: any[], size = 1): any[] {
return arr.length > size ? [arr.slice(0, size), ...chunk(arr.slice(size), size)] : [arr]
}
|
ContentPI/lib
|
src/utils/index.ts
|
const rsAstralRange = '\\ud800-\\udfff'
const rsComboMarksRange = '\\u0300-\\u036f'
const reComboHalfMarksRange = '\\ufe20-\\ufe2f'
const rsComboSymbolsRange = '\\u20d0-\\u20ff'
const rsComboMarksExtendedRange = '\\u1ab0-\\u1aff'
const rsComboMarksSupplementRange = '\\u1dc0-\\u1dff'
const rsComboRange =
rsComboMarksRange +
reComboHalfMarksRange +
rsComboSymbolsRange +
rsComboMarksExtendedRange +
rsComboMarksSupplementRange
const rsDingbatRange = '\\u2700-\\u27bf'
const rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff'
const rsMathOpRange = '\\xac\\xb1\\xd7\\xf7'
const rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf'
const rsPunctuationRange = '\\u2000-\\u206f'
const rsSpaceRange =
' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000' // eslint-disable-line max-len
const rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde'
const rsVarRange = '\\ufe0e\\ufe0f'
const rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange
const rsApos = "['\u2019]"
const rsBreak = `[${rsBreakRange}]`
const rsCombo = `[${rsComboRange}]`
const rsDigit = '\\d'
const rsDingbat = `[${rsDingbatRange}]`
const rsLower = `[${rsLowerRange}]`
const rsMisc = `[^${rsAstralRange}${
rsBreakRange + rsDigit + rsDingbatRange + rsLowerRange + rsUpperRange
}]`
const rsFitz = '\\ud83c[\\udffb-\\udfff]'
const rsModifier = `(?:${rsCombo}|${rsFitz})`
const rsNonAstral = `[^${rsAstralRange}]`
const rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'
const rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'
const rsUpper = `[${rsUpperRange}]`
const rsZWJ = '\\u200d'
const rsMiscLower = `(?:${rsLower}|${rsMisc})`
const rsMiscUpper = `(?:${rsUpper}|${rsMisc})`
const rsOptContrLower = `(?:${rsApos}(?:d|ll|m|re|s|t|ve))?`
const rsOptContrUpper = `(?:${rsApos}(?:D|LL|M|RE|S|T|VE))?`
const reOptMod = `${rsModifier}?`
const rsOptVar = `[${rsVarRange}]?`
const rsOptJoin = `(?:${rsZWJ}(?:${[rsNonAstral, rsRegional, rsSurrPair].join('|')})${
rsOptVar + reOptMod
})*`
const rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])'
const rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])'
const rsSeq = rsOptVar + reOptMod + rsOptJoin
const rsEmoji = `(?:${[rsDingbat, rsRegional, rsSurrPair].join('|')})${rsSeq}`
const reUnicodeWords = RegExp(
[
`${rsUpper}?${rsLower}+${rsOptContrLower}(?=${[rsBreak, rsUpper, '$'].join('|')})`,
`${rsMiscUpper}+${rsOptContrUpper}(?=${[rsBreak, rsUpper + rsMiscLower, '$'].join('|')})`,
`${rsUpper}?${rsMiscLower}+${rsOptContrLower}`,
`${rsUpper}+${rsOptContrUpper}`,
rsOrdUpper,
rsOrdLower,
`${rsDigit}+`,
rsEmoji
].join('|'),
'g'
)
const hasUnicodeWord = RegExp.prototype.test.bind(
/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/
)
// eslint-disable-next-line no-control-regex
const reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g
export function unicodeWords(string: string): any {
return string.match(reUnicodeWords)
}
export function asciiWords(string: string): any {
return string.match(reAsciiWord)
}
export function words(string: string, pattern?: any): string[] {
if (pattern === undefined) {
const result = hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string)
return result || []
}
return string.match(pattern) || []
}
|
ContentPI/lib
|
src/index.ts
|
<filename>src/index.ts
export * from './array'
export * from './core'
export * from './files'
export * from './frontend'
export * from './graphql'
export * from './i18n'
export * from './is'
export * from './object'
export * from './security'
export * from './string'
export * from './typescript'
export * from './url'
|
ContentPI/lib
|
src/@types/crypto/index.d.ts
|
<gh_stars>0
declare module 'crypto'
|
ContentPI/lib
|
src/is/__tests__/index.test.ts
|
import {
isArray,
isDefined,
isFunction,
isJson,
isNumber,
isObject,
isPassword,
isString,
isUndefined,
isEmptyObject,
isLanguage
} from '../index'
describe('#isArray', () => {
it('should return true if is an Array', () => {
expect(isArray([1, 2, 3])).toBe(true)
})
it('should return false if is not an Array', () => {
expect(
isArray({
bar: 'bar',
foo: 'foo'
})
).toBe(false)
})
})
describe('#isDefined', () => {
it('should return true if a variable is defined', () => {
const test = 'Foo'
expect(isDefined(test)).toBe(true)
})
it('should return false if a variable is undefined', () => {
let test
expect(isDefined(test)).toBe(false)
})
})
describe('#isFunction', () => {
it('should be true if a variable is a function', () => {
const test = (): string => 'bar'
expect(isFunction(test)).toBe(true)
})
it('should be false if a variable is not a function', () => {
const test = 'bar'
expect(isFunction(test)).toBe(false)
})
})
describe('#isJson', () => {
it('should be true if a variable is a valid json', () => {
const test = JSON.stringify({
foo: {
bar: true
}
})
expect(isJson(test)).toBe(true)
})
it('should be false if a variable is not a valid json', () => {
expect(isJson('')).toBe(false)
expect(isJson('bar')).toBe(false)
})
})
describe('#isNumber', () => {
it('should be true if a variable is a number', () => {
expect(isNumber(-1)).toBe(true)
expect(isNumber(0)).toBe(true)
expect(isNumber(1)).toBe(true)
})
it('should be false if a variable is not a number', () => {
expect(isNumber(true)).toBe(false)
expect(isNumber(false)).toBe(false)
expect(isNumber('O')).toBe(false)
})
})
describe('#isObject', () => {
it('should return true if a variable is object', () => {
const test = {
foo: 'Foo'
}
expect(isObject(test)).toBe(true)
})
it('should return false if a variable is not an object', () => {
const test = ['Foo']
expect(isObject(test)).toBe(false)
})
})
describe('#isPassword', () => {
it('should be true if a value is a valid password', () => {
expect(isPassword('<PASSWORD>')).toBe(true)
})
it('should be true if a value is not a valid password', () => {
expect(isPassword('<PASSWORD>')).toBe(false)
})
})
describe('#isString', () => {
it('should be true if a variable is a string', () => {
expect(isString('foo')).toBe(true)
expect(isString('123')).toBe(true)
expect(isString('true')).toBe(true)
})
it('should be false if a variable is not a string', () => {
expect(isString(true)).toBe(false)
expect(isString(false)).toBe(false)
expect(isString(0)).toBe(false)
expect(isString(1)).toBe(false)
})
})
describe('#isUndefined', () => {
it('should return true if a variable is undefined', () => {
let test
expect(isUndefined(test)).toBe(true)
})
it('should return false if a variable is not undefined', () => {
const test = 'foo'
expect(isUndefined(test)).toBe(false)
})
})
describe('#isEmptyObject', () => {
it('should return true if object is empty', () => {
const obj = {}
expect(isEmptyObject(obj)).toBe(true)
expect(isEmptyObject(undefined)).toBe(true)
})
it('should return false if object is not empty', () => {
const obj = {
foo: 'bar'
}
expect(isEmptyObject(obj)).toBe(false)
})
})
describe('#isLanguage', () => {
it('should return true if is a valid language', () => {
expect(isLanguage('en-US')).toBe(true)
})
it('should return false if is not a valid language', () => {
expect(isLanguage('bn-IN')).toBe(false)
})
})
|
ContentPI/lib
|
src/url/index.ts
|
<filename>src/url/index.ts
import { isBrowser } from '../is'
export function getLocation(req?: any): any {
return typeof window !== 'undefined' ? window.location : { pathname: req && req.url }
}
export function getParamsFromUrl(mapParams: string[], baseUrl?: string): any {
let pathname = ''
if (isBrowser() && !baseUrl) {
pathname = window.location.pathname
} else if (baseUrl) {
pathname = baseUrl.split('?')[0] // eslint-disable-line prefer-destructuring
if (pathname.substr(-1) === '/') {
pathname = pathname.slice(0, -1)
}
}
const chunks = pathname.split('/').filter(v => v)
const params: any = {}
mapParams.forEach((param, i) => {
params[param] = chunks[i] || null
})
return params
}
|
ContentPI/lib
|
src/typescript/__tests__/index.test.ts
|
<gh_stars>0
import { hasKey } from '../index'
describe('#hasKey', () => {
const obj = {
foo: 'bar'
}
it('should return true if an object has a key', () => {
expect(hasKey(obj, 'foo')).toBe(true)
})
it('should return false if an object does not has a key', () => {
expect(hasKey(obj, 'bar')).toBe(false)
})
})
|
ContentPI/lib
|
src/string/__tests__/index.test.ts
|
import { arrayIn, capitalize, camelCase, pluralify } from '../index'
describe('#arrayIn', () => {
it('should return true if a value from array exists on string', () => {
const whitelist = ['login']
const fakeWhitelist = ['getUsers']
const query = `
mutation {
login(input: {email: "<EMAIL>", password: "<PASSWORD>"}) {
token
}
}
`
expect(arrayIn(whitelist, query)).toBe(true)
expect(arrayIn(fakeWhitelist, query)).toBe(false)
})
})
describe('#capitalize', () => {
it('should return a capitalized string', () => {
expect(capitalize('fogg')).toBe('Fogg')
expect(capitalize('f')).toBe('F')
})
})
describe('#camelCase', () => {
it('should return a camelCased string', () => {
expect(camelCase('Foo Bar')).toBe('fooBar')
expect(camelCase('--foo-bar--')).toBe('fooBar')
expect(camelCase('__FOO_BAR__')).toBe('fooBar')
})
})
describe('#pluralify', () => {
it('should return singular value', () => {
expect(pluralify('Entry', 'Entries', 1)).toBe('Entry')
})
it('should return plural', () => {
expect(pluralify('Entry', 'Entries', 0)).toBe('Entries')
expect(pluralify('Entry', 'Entries', 2)).toBe('Entries')
})
})
|
ContentPI/lib
|
src/security/index.ts
|
<reponame>ContentPI/lib
// Dependencies
import crypto from 'crypto'
// Utils
import { isString, isJson, isObject } from '../is'
declare const Buffer: any
export function encrypt(str: string): string {
return crypto.createHash('sha1').update(str.toString()).digest('hex')
}
export function getBase64(value: string): any {
let buffer
if (isString(value)) {
buffer = Buffer.from(value, 'base64').toString('ascii')
}
if (isJson(buffer)) {
buffer = JSON.parse(Buffer.from(value, 'base64').toString('ascii'))
}
return buffer
}
export function setBase64(value: any): any {
if (isObject(value)) {
return Buffer.from(JSON.stringify(value)).toString('base64')
}
return isString(value) ? Buffer.from(value).toString('base64') : null
}
export function getRandomCode(max: number): string {
let code = ''
let randomPoz
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
max = max || 12
for (let i = 0; i < max; i += 1) {
randomPoz = Math.floor(Math.random() * charset.length)
code += charset.substring(randomPoz, randomPoz + 1)
}
return code
}
|
ContentPI/lib
|
src/files/index.ts
|
<reponame>ContentPI/lib
import fetch from 'isomorphic-fetch'
export function getFileInfo(file: any): any {
if (!file) {
return {
fileName: '',
extension: ''
}
}
const parts = file.split('.')
const extension = parts.pop()
const fileName = parts.pop()
return {
fileName,
extension: extension.toLowerCase()
}
}
export function bytesToSize(bytes: any, maxFileSize: number, round?: boolean): any {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
let allowed = true
if (bytes > maxFileSize) {
allowed = false
}
const n = Number(bytes)
// @ts-ignore
const i = parseInt(Math.floor(Math.log(n) / Math.log(1024)), 10)
if (i === 0) {
return `${bytes} ${sizes[i]}`
}
let size: any = (bytes / 1024 ** i).toFixed(1)
if (round) {
size = Math.ceil(size)
}
return {
size: `${size} ${sizes[i]}`,
allowed
}
}
export function getFileExtensionFromURL(fileUrl = ''): any {
let file: any = ''
if (fileUrl) {
file = fileUrl.split('/').pop()
}
return getFileInfo(file)
}
export function getImageData(file: any): Promise<any> {
return new Promise((resolve, reject) => {
const img = new Image()
img.src = window.URL.createObjectURL(file)
img.onload = (): any => resolve({ width: img.width, height: img.height })
img.onerror = reject
})
}
export async function uploadFile(file: any, url: string): Promise<boolean> {
if (!file) {
return false
}
const fileData: any = new FormData()
fileData.append('file', file)
const response = await fetch(url, {
method: 'POST',
body: fileData
})
const responseData = await response.json()
if (responseData.destination) {
return true
}
return false
}
|
ContentPI/lib
|
src/core/__tests__/index.ts
|
import { getReferenceTitle, getEmptyValues } from '../index'
const data = [
{
id: 'a7e48837-a759-49d9-9061-7c0e0cc9ca53',
type: 'Status',
fieldName: 'Status',
identifier: 'status',
description: 'The status of the record',
isHide: false,
isMedia: false,
isRequired: true,
isUnique: false,
isSystem: true,
isPrimaryKey: false,
values: [
{
id: '6120bac8-dd52-482f-be5c-a76c919a12a3',
entry: '247791ee-49e9-4f9a-a30e-be2524764d11',
value: 'Draft',
__typename: 'Value'
},
{
id: 'd72b044e-5886-42fa-805e-58fdcae027fe',
entry: '11111111-49e9-4f9a-a30e-be2524764d11',
value: 'Draft',
__typename: 'Value'
}
],
__typename: 'Field'
},
{
id: '7596002c-4937-48d1-a3e0-2ff75b339e21',
type: 'DateTime',
fieldName: 'Updated At',
identifier: 'updatedAt',
description: 'The time the record was updated',
isHide: true,
isMedia: false,
isRequired: true,
isUnique: false,
isSystem: true,
isPrimaryKey: false,
values: [
{
id: 'dcbaaabd-cb9e-4bec-a6b7-915486c6637c',
entry: '247791ee-49e9-4f9a-a30e-be2524764d11',
value: '2020-06-01 22:42:56.383-07',
__typename: 'Value'
},
{
id: '602c8183-71f2-454d-bf15-644df28f0edb',
entry: '11111111-49e9-4f9a-a30e-be2524764d11',
value: '2020-06-02 22:44:55.797-07',
__typename: 'Value'
}
],
__typename: 'Field'
},
{
id: '4d1f74b5-244d-4ce2-9e45-bf3d09f086cf',
type: 'DateTime',
fieldName: 'Created At',
identifier: 'createdAt',
description: 'The time the record was created',
isHide: true,
isMedia: false,
isRequired: true,
isUnique: false,
isSystem: true,
isPrimaryKey: false,
values: [
{
id: 'c95a09ed-6692-4b43-8eb8-a57eca7a3ad7',
entry: '247791ee-49e9-4f9a-a30e-be2524764d11',
value: '2020-05-27 22:42:56.383-07',
__typename: 'Value'
},
{
id: '9b055610-a977-46d1-8372-c43529abdc1f',
entry: '11111111-49e9-4f9a-a30e-be2524764d11',
value: '2020-05-28 22:44:55.797-07',
__typename: 'Value'
}
],
__typename: 'Field'
},
{
id: 'a0dd3f73-968a-4419-9b4e-c2b780f75c23',
type: 'ID',
fieldName: 'ID',
identifier: 'id',
description: 'The unique identifier',
isHide: false,
isMedia: false,
isRequired: true,
isUnique: true,
isSystem: true,
isPrimaryKey: true,
values: [
{
id: '90188b3c-18ec-443f-94c6-69502f6e509c',
entry: '247791ee-49e9-4f9a-a30e-be2524764d11',
value: 'dac4fcdd-0954-4e86-be6a-160be8ffbf2e',
__typename: 'Value'
},
{
id: '642ae442-8df6-4810-a085-a498263bdf94',
entry: '11111111-49e9-4f9a-a30e-be2524764d11',
value: 'fe07c143-ecb5-4fd3-aa29-2058981ed328',
__typename: 'Value'
}
],
__typename: 'Field'
},
{
id: '00c71451-321c-4630-9e99-8decf6d2a2a0',
type: 'String',
fieldName: 'Title',
identifier: 'title',
description: '',
isHide: false,
isMedia: false,
isRequired: true,
isUnique: false,
isSystem: false,
isPrimaryKey: false,
values: [
{
id: 'a0d9893f-7e7d-435a-97b8-8c62672a9bb3',
entry: '247791ee-49e9-4f9a-a30e-be2524764d11',
value: 'Blog post 1',
__typename: 'Value'
},
{
id: 'da1c267b-8a8a-4877-9c3c-4e80e95af494',
entry: '11111111-49e9-4f9a-a30e-be2524764d11',
value: 'My blog post 2',
__typename: 'Value'
}
],
__typename: 'Field'
}
]
describe('getReferenceTitle', () => {
it('should get the correct title', () => {
const entry = {
authorName: '<NAME>',
createdAt: '2020-09-18T22:51:03-07:00',
id: 'a0c38fdc-0732-4a1a-b2f3-9430fd9c810b',
modelName: 'Author',
status: 'Draft'
}
const title = getReferenceTitle(entry)
expect(title).toBe('Carlos Santana')
})
it('should get Unknown title', () => {
const entry = {
createdAt: '2020-09-18T22:51:03-07:00',
id: 'a0c38fdc-0732-4a1a-b2f3-9430fd9c810b',
modelName: 'Author',
status: 'Draft'
}
const title = getReferenceTitle(entry)
expect(title).toBe('Unknown')
})
})
describe('#getEmptyValues', () => {
it('should get all empty values', () => {
const values = {
firstName: ' ',
lastName: 'foo',
age: 20,
email: ''
}
const expectedValues = {
firstName: true,
email: true
}
const emptyValues = getEmptyValues(values)
expect(emptyValues).toEqual(expectedValues)
})
it('should get false if there is not empty values', () => {
const values = {
firstName: 'baz',
lastName: 'foo',
age: 20,
email: '<EMAIL>'
}
const emptyValues = getEmptyValues(values)
expect(emptyValues).toBe(false)
})
it('should get just required empty values', () => {
const values = {
firstName: '',
lastName: '',
age: 20,
email: ''
}
const emptyValues = getEmptyValues(values, ['firstName', 'email'])
expect(emptyValues).toEqual({
firstName: true,
email: true
})
})
})
// describe('#getValuesForTable', () => {
// it('should order the data', () => {
// const values = getValuesForTable(data, null, 'createdAt', 'desc')
// expect(values).toEqual({
// head: ['ID', 'Title', 'Status', 'Created At'],
// body: ['id', 'title', 'status', 'createdAt'],
// rows: [
// [
// {
// status: 'Draft',
// createdAt: '2020-05-28 22:44:55.797-07',
// id: 'fe07c143-ecb5-4fd3-aa29-2058981ed328',
// title: 'My blog post 2'
// },
// {
// status: 'Draft',
// createdAt: '2020-05-27 22:42:56.383-07',
// id: 'dac4fcdd-0954-4e86-be6a-160be8ffbf2e',
// title: 'Blog post 1'
// }
// ]
// ],
// total: 2
// })
// })
// it('should return the correct values', () => {
// const values = getValuesForTable(data)
// expect(values).toEqual({
// head: ['ID', 'Title', 'Status', 'Created At'],
// body: ['id', 'title', 'status', 'createdAt'],
// rows: [
// [
// {
// status: 'Draft',
// createdAt: '2020-05-27 22:42:56.383-07',
// id: '<PASSWORD>',
// title: 'Blog post 1'
// },
// {
// status: 'Draft',
// createdAt: '2020-05-28 22:44:55.797-07',
// id: 'fe<PASSWORD>',
// title: 'My blog post 2'
// }
// ]
// ],
// total: 2
// })
// })
// })
|
ContentPI/lib
|
src/global.d.ts
|
export {}
declare global {
interface Window {
initialState: any
}
}
|
ContentPI/lib
|
src/graphql/index.ts
|
// Interfaces
interface Error {
error: boolean
message: string
}
export function getGraphQlError(error: any): Error {
return {
error: true,
message: error.toString().replace('Error: GraphQL error: ', '')
}
}
export function validateFields(
validations: any,
values: any,
alert = 'Error trying to create the item'
): any {
const messages: any = {}
Object.keys(validations).forEach(field => {
const { len, isEmpty } = validations[field]
if (len && len.arg) {
if (values[field].length !== len.arg) {
messages[field] = {
msg: len.msg
}
}
}
if (isEmpty) {
if (values[field] === '' || !values[field]) {
messages[field] = {
msg: isEmpty.msg
}
}
}
})
return Object.keys(messages).length > 0
? {
error: true,
alert,
messages
}
: {
error: false
}
}
export function getQueryName(query: any): string | boolean {
if (query && query.definitions && query.definitions.length > 0) {
return query.definitions[0].name.value
}
return false
}
|
ContentPI/lib
|
src/security/__tests__/index.test.ts
|
import { encrypt, getBase64, setBase64 } from '../index'
describe('#encrypt', () => {
it('should return a encrypted salted string', () => {
expect(encrypt('foo')).toBe('0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33')
})
})
describe('#getBase64', () => {
it('should get a value from base64 string', () => {
expect(getBase64('Zm9v')).toBe('foo')
})
it('should get a JSON from base64 string', () => {
expect(getBase64('eyJmb28iOiJiYXIifQ==')).toEqual({ foo: 'bar' })
})
})
describe('#setBase64', () => {
it('should set a string value to base64 string', () => {
expect(setBase64('foo')).toBe('Zm9v')
})
it('should set a JSON to base64 string', () => {
expect(setBase64(JSON.stringify({ foo: 'bar' }))).toEqual('eyJmb28iOiJiYXIifQ==')
})
})
|
ContentPI/lib
|
src/languages.ts
|
export const languagesList: any = {
ar: {
name: 'العربية',
lang: 'ar',
dir: 'rtl'
},
'de-DE': {
name: 'Deutsch',
lang: 'de-DE'
},
'en-US': {
name: 'English (US)',
lang: 'en-US'
},
'en-GB': {
name: 'English (UK)',
lang: 'en-GB'
},
es: {
name: 'Español',
lang: 'es'
},
'es-AR': {
name: 'Español (AR)',
lang: 'es-AR'
},
'es-ES': {
name: 'Español (ES)',
lang: 'es-ES'
},
'es-MX': {
name: 'Español (MX)',
lang: 'es-MX'
},
'fr-FR': {
name: 'Français',
lang: 'fr-FR'
},
'it-IT': {
name: 'Italiano',
lang: 'it-IT'
},
'pt-BR': {
name: 'Português (BR)',
lang: 'pt-BR'
},
'pt-PT': {
name: 'Português (PT)',
lang: 'pt-PT'
},
'ja-JP': {
name: '日本語',
lang: 'ja-JP'
},
'ko-KR': {
name: '한국어',
lang: 'ko-KR'
},
'ru-RU': {
name: 'Русский',
lang: 'ru-RU'
},
'zh-CN': {
name: '中文(简体)',
lang: 'zh-CN'
}
}
|
ContentPI/lib
|
src/frontend/index.ts
|
// Dependencies
import slug from 'slug'
// Utils
import { isDefined, isString } from '../is'
// Interfaces
interface Router {
asPath: string
}
interface PathInfo {
section: string
module: string
action: string
id: string
}
interface iAdd {
if: (condition: boolean) => string
}
interface iProps {
ccn: string
data: string[]
className?: string
}
export function buildUrl(params: string[]): string {
return params.filter(v => v).join('/')
}
export function slugFn(str = ''): string {
return slug(str, { lower: true })
}
export function cx(...classes: string[]): string {
return classes.join(' ').trim()
}
export function isFirstRender(items: any[] | any): boolean {
return !isDefined(items) || items.length === 0 || Object.keys(items).length === 0
}
export function waitFor(time: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, time * 1000))
}
export function add(cssRule: string | any): iAdd {
return {
if: (condition: boolean) => {
if (condition && cssRule) {
if (isString(cssRule)) {
return cssRule
}
let cssString = ''
Object.keys(cssRule).forEach((property: string) => {
cssString += `${property}: ${cssRule[property]};`
})
return cssString
}
return ''
}
}
}
export function cxGenerator({ ccn, data, className }: iProps): string {
const classList = [ccn]
data.forEach(key => {
if (key !== '') {
classList.push(`${ccn}-${key}`)
}
})
if (className) {
classList.push(className)
}
return classList.join(' ')
}
export function getModuleInfo(router: Router): PathInfo {
let cleanPath = router.asPath.split('?')[0]
if (cleanPath.substr(-1) === '/') {
cleanPath = cleanPath.slice(0, -1)
}
const [, section, module = 'home', action, id] = cleanPath.split('/')
return {
section,
module,
action,
id
}
}
export function scrollToTop(): void {
document.body.scrollTop = 0
document.documentElement.scrollTop = 0
}
export function isValidHexColor(hexCode: string): boolean {
return /^#([0-9a-f]{3}){1,2}$/i.test(hexCode.toLowerCase())
}
export function generateHexCode(): string {
let newHex = `${Math.floor(Math.random() * 16777215)
.toString(16)
.substring(0, 7)}`
if (newHex.length < 6) {
newHex += 'f'
}
return `#${newHex}`
}
export function invertHexCode(hexCode?: any): string {
if (!hexCode) {
return '#FFFFFF'
}
let hex = hexCode.replace('#', '')
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
}
const r = parseInt(hex.slice(0, 2), 16)
const g = parseInt(hex.slice(2, 4), 16)
const b = parseInt(hex.slice(4, 6), 16)
return r * 0.299 + g * 0.587 + b * 0.114 > 186 ? '#000000' : '#FFFFFF'
}
export function getInitialState() {
if (typeof window !== 'undefined') {
if (window.initialState) {
return window.initialState
}
}
return {}
}
|
ContentPI/lib
|
src/is/index.ts
|
<gh_stars>0
import { languagesList } from '../languages'
export function isArray(v: unknown): boolean {
return v instanceof Array
}
export function isDefined(v: unknown): boolean {
return typeof v !== 'undefined' && v !== null
}
export function isFalse(v: unknown): boolean {
return isDefined(v) && v === false
}
export function isNumber(v: unknown): boolean {
return typeof v === 'number'
}
export function isFunction(v: any): boolean {
return typeof v === 'function'
}
export function isJson(str: string): boolean | any {
if (!str || str === null) {
return false
}
try {
JSON.parse(str)
} catch (e) {
return false
}
return true
}
export function isObject(v: unknown): boolean {
return isDefined(v) && typeof v === 'object' && !isArray(v)
}
export function isPassword(password: string, min = 8): boolean {
return Boolean(password && password.length >= min)
}
export function isPasswordMatch(p1: string, p2: string): boolean {
return isPassword(p1) && isPassword(p2) && p1 === p2
}
export function isString(v: unknown): boolean {
return isDefined(v) && typeof v === 'string'
}
export function isUndefined(v: unknown): boolean {
return typeof v === 'undefined' || v === null
}
export function isBrowser(): boolean {
return typeof window !== 'undefined'
}
export function isSymbol(v: unknown): boolean {
return typeof v === 'symbol' || isObject(v)
}
export function isEmptyObject(v: any): boolean {
return v ? Object.keys(v).length === 0 : true
}
export const isLanguage = (lang: string) => {
return !!languagesList[lang]
}
|
ContentPI/lib
|
src/object/__tests__/index.test.ts
|
<filename>src/object/__tests__/index.test.ts
import {
buildContentJson,
cloneObject,
forEach,
getDebug,
hasOwnProperty,
keys,
objectToDot,
pick
} from '../index'
describe('#cloneObject', () => {
it('should clone an object', () => {
const obj = {
foo: true,
baz: false
}
const clonedObj = cloneObject(obj)
expect(clonedObj).toEqual(obj)
})
it('should clone an object and have a different instance', () => {
const obj = {
foo: true,
baz: false
}
const clonedObj = cloneObject(obj)
expect(clonedObj === obj).toBe(false)
})
})
describe('#getDebug', () => {
it('should get the debug data', () => {
const query = {
_DEBUG: JSON.stringify({
foo: 'bar'
})
}
const debug = getDebug(query)
expect(debug.foo).toEqual('bar')
})
it('should clone an object and have a different instance', () => {
const obj = {
foo: true,
baz: false
}
const clonedObj = cloneObject(obj)
expect(clonedObj === obj).toBe(false)
})
})
describe('#keys', () => {
it('should get the object keys', () => {
const obj = {
foo: 'bar',
baz: 'bar'
}
expect(keys(obj)).toEqual(['foo', 'baz'])
})
})
describe('#hasOwnProperty', () => {
it('should get find a node', () => {
const obj = {
foo: 'bar',
baz: 'bar'
}
expect(hasOwnProperty(obj, 'foo')).toBe(true)
})
})
describe('#buildContentJson', () => {
it('should build a json from content', () => {
const content = [
{
key: 'site.language',
value: 'en'
},
{
key: 'site.title',
value: 'Bar'
},
{
key: 'site.meta.abstract',
value: 'Foo'
}
]
const expectedResult = {
site: {
language: 'en',
title: 'Bar',
meta: {
abstract: 'Foo'
}
}
}
expect(buildContentJson(content)).toEqual(expectedResult)
})
})
describe('#forEach', () => {
it('should call the callback on the forEach', () => {
const mockCallback = jest.fn()
forEach([0, 1], mockCallback)
// The mock function is called twice
expect(mockCallback.mock.calls.length).toBe(2)
// The first argument of the first call to the function was 0
expect(mockCallback.mock.calls[0][0]).toBe(0)
// The first argument of the second call to the function was 1
expect(mockCallback.mock.calls[1][0]).toBe(1)
})
it('should return false when the items are not defined', () => {
const mockCallback = jest.fn()
expect(forEach(undefined, mockCallback)).toBe(false)
})
})
describe('#objectToDot', () => {
it('should convert an object to dot notation', () => {
const content = {
site: {
language: 'en',
title: 'Bar',
meta: {
abstract: 'Foo'
}
}
}
const expectedResult = {
'site.language': 'en',
'site.meta.abstract': 'Foo',
'site.title': 'Bar'
}
const result = objectToDot(content)
expect(result).toEqual(expectedResult)
})
it('should return null if content is not an object', () => {
const content = ['foo', 'bar']
const expectedResult = null
const result = objectToDot(content)
expect(result).toEqual(expectedResult)
})
})
describe('#pick', () => {
it('should pick a key from object', () => {
const test = {
foo: {
bar: 'Testing'
}
}
expect(pick('foo.bar', test)).toBe('Testing')
})
it('should return a key that could not find in the object', () => {
const test = {
foo: {
bar: 'Testing'
}
}
expect(pick('foo.baz', test)).toBe('foo.baz')
})
})
|
ContentPI/lib
|
src/i18n/index.ts
|
<filename>src/i18n/index.ts
import { isLanguage, isString, isDefined, isBrowser } from '../is'
import { pick } from '../object'
import { getLocation } from '../url'
import { languagesList } from '../languages'
export function getParams(url: string, index = 0): string | string[] {
if (!url) {
url = getLocation().pathname
}
if (isString(url)) {
if (url.indexOf('?') > -1) {
url = url.substr(0, url.indexOf('?'))
}
const params = url.split('/')
params.shift()
if (params[params.length - 1] === '') {
params.pop()
}
if (index) {
if (isLanguage(params[0])) {
index += 1
}
if (isDefined(params[index])) {
return params[index]
}
}
return params
}
return ''
}
export const getCurrentLanguage = (url?: string, defaultLanguage = 'en-US') => {
const params = getParams(url || '')
return params && isLanguage(params[0]) ? params[0] : defaultLanguage
}
export function redirectTo(url = '/', includeLanguage?: any): void {
if (isBrowser()) {
const { pathname } = window.location
const language = getCurrentLanguage()
let slash = '/'
if (url === '_self') {
if (isLanguage(includeLanguage)) {
const segments = pathname.split(slash).filter(v => v)
if (isLanguage(segments[0])) {
segments[0] = includeLanguage
}
window.location.href = `${slash}${segments.join('/')}`
} else {
window.location.href = pathname
}
} else if (includeLanguage) {
if (url[0] === '/') {
slash = ''
}
window.location.href = `/${language}${slash}${url}`
} else {
window.location.href = url
}
}
}
export const getLanguagesList = () => {
return languagesList
}
export const getSelectLanguages = (list: any) => {
const languages: any = []
const currentLanguage = getCurrentLanguage()
list.forEach((language: string) => {
languages.push({
option: languagesList[language].name,
value: languagesList[language].lang,
selected: language === currentLanguage
})
})
return languages
}
export const availableLanguages = (join = true) => {
const listOfLanguages = Object.keys(languagesList)
if (join) {
return listOfLanguages.join('|')
}
return listOfLanguages
}
export function t(key: string, __: any) {
return pick(key, __)
}
export function getDirection(language?: any, value1?: any, value2?: any): any {
if (!isLanguage(language)) {
language = getCurrentLanguage()
}
if (!value1) {
value1 = 'rtl'
}
if (!value2) {
value2 = 'ltr'
}
return language === 'ar' ? value1 : value2
}
|
isabella232/avalanche-explorer
|
cypress/plugins/index.ts
|
/**
* Rather then have a bunch of configs for each environment we simply
* create a object here, dynamically change it based on various environment variables
* and pass it to cypress just before it starts.
*/
const CYPRESS_BASE_CONFIG = {
nodeVersion: "system",
};
const CYPRESS_CONFIG_PROD = {
...CYPRESS_BASE_CONFIG,
baseUrl: 'https://explorer-xp.avax.network/',
}
const CYPRESS_CONFIG_LOCAL = {
...CYPRESS_BASE_CONFIG,
baseUrl: `${!process.env.USE_HTTP ? "http" : "https"}://localhost:8080/`,
};
/**
* @type {Cypress.PluginConfig}
*/
module.exports = () => {
return process.env.runProduction ? CYPRESS_CONFIG_PROD : CYPRESS_CONFIG_LOCAL;
};
|
isabella232/avalanche-explorer
|
src/plugins/vuetify.ts
|
import Vue from 'vue'
import Vuetify from 'vuetify'
// Font Awesome
import { library } from '@fortawesome/fontawesome-svg-core'
import {
faAngleDown,
faAngleLeft,
faAngleRight,
faArrowLeft,
faArrowRight,
faBars,
faCheck,
faCheckCircle,
faCog,
faCoins,
faCopy,
faExclamation,
faInfo,
faInfoCircle,
faFont,
faLink,
faSearch,
faSnowman,
faSync,
faTimes,
} from '@fortawesome/free-solid-svg-icons'
import { faClock } from '@fortawesome/free-regular-svg-icons'
import {
faTwitter,
faDiscord,
faReddit,
faGithub,
} from '@fortawesome/free-brands-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
library.add(
faAngleDown,
faAngleLeft,
faAngleRight,
faArrowLeft,
faArrowRight,
faBars,
faCheck,
faCheckCircle,
faClock,
faCog,
faCoins,
faCopy,
faDiscord,
faFont,
faGithub,
faExclamation,
faInfo,
faInfoCircle,
faLink,
faReddit,
faSearch,
faSnowman,
faSync,
faTimes,
faTwitter
)
Vue.component('fa', FontAwesomeIcon)
Vue.use(Vuetify)
export default new Vuetify({
theme: {
themes: {
light: {},
dark: {
nav_bar: '#fff',
primary: '#4fb1d6',
},
},
},
})
|
PritishSawant/rn-thub-share-module
|
src/index.tsx
|
<gh_stars>1-10
import { NativeModules } from 'react-native';
type RnThubShareModuleType = {
multiply(a: number, b: number): Promise<number>;
};
const { RnThubShareModule } = NativeModules;
export default RnThubShareModule as RnThubShareModuleType;
|
Aschen/nsecure
|
index.d.ts
|
/// <reference types="js-x-ray"/>
/// <reference types="ntlp"/>
import { Warning, Dependencies } from "js-x-ray";
import { license as License } from "ntlp";
declare namespace NodeSecure {
interface Publisher {
name: string;
version: string;
at: string;
}
interface Maintainer {
name: string;
email: string;
}
interface Author {
name?: string;
url?: string;
email?: string;
}
interface Flags {
isGit: boolean;
hasManifest: boolean;
hasOutdatedDependency: boolean;
isDeprecated: boolean;
hasWarnings: boolean;
hasLicense: boolean;
hasMultipleLicenses: boolean;
hasMissingOrUnusedDependency: boolean;
hasMinifiedCode: boolean;
hasIndirectDependencies: boolean;
hasCustomResolver: boolean;
hasDependencies: boolean;
hasExternalCapacity: boolean;
hasScript: boolean;
hasBannedFile: boolean;
}
interface Dependency {
name: string;
version: string;
parent?: {
name: string;
version: string;
};
flags: Flags;
}
interface Vulnerability {
id: number;
created_at: string;
updated_at: string;
title: string;
author: {
name: string;
website: string | null;
username: string | null;
};
module_name: string;
publish_data: string;
cves: string[];
vulnerable_versions: string;
patched_versions: string;
overview: string;
recommendation: string;
references: string[];
cvss_vector: string;
cvss_score: number;
coordinating_vendor: string;
}
interface VersionDescriptor {
metadata: {
dependencyCount: number;
publishedCount: number;
lastUpdateAt: number;
lastVersion: number;
hasChangedAuthor: boolean;
hasManyPublishers: boolean;
hasReceivedUpdateInOneYear: boolean;
author: string | null;
homepage: string | null;
maintainers: Maintainer[];
publishers: Publisher[];
};
versions: string[];
vulnerabilities: Vulnerability[];
[version: string]: {
id: number;
usedBy: {
[packageName: string]: string;
};
size: number;
description: string;
author: string | Author;
warnings: Warning[];
composition: {
extensions: string[];
files: string[];
minified: string[];
required: string[];
required_builtin: string[];
unused: string[];
missing: string[];
};
license: string | License[];
flags: Flags;
gitUrl: null | string;
};
}
interface Payload {
id: string;
rootDependencyName: string;
warnings: [],
dependencies: {
[packageName: string]: VersionDescriptor;
}
}
interface VerifyPayload {
files: {
list: string[];
extensions: string[];
minified: string[];
};
directorySize: number;
uniqueLicenseIds: string[];
licenses: License[];
ast: {
dependencies: {
[fileName: string]: Dependencies;
};
warnings: Warning[];
};
}
interface Options {
readonly verbose?: boolean;
readonly maxDepth?: number;
}
export function cwd(path: string, options?: NodeSecure.Options): Promise<NodeSecure.Payload>;
export function from(packageName: string, options?: NodeSecure.Options): Promise<NodeSecure.Payload>;
export function verify(packageName: string): Promise<NodeSecure.VerifyPayload>;
}
export = NodeSecure;
export as namespace NodeSecure;
|
keemy/anchor
|
ts/src/utils/index.ts
|
<reponame>keemy/anchor
import { sha256 } from "crypto-hash";
import * as bs58 from "bs58";
import * as rpc from "./rpc";
import * as publicKey from "./pubkey";
export function decodeUtf8(array: Uint8Array): string {
const decoder =
typeof TextDecoder === "undefined"
? new (require("util").TextDecoder)("utf-8") // Node.
: new TextDecoder("utf-8"); // Browser.
return decoder.decode(array);
}
export default { sha256, bs58, rpc, publicKey };
|
brett0701/nativescript-confusion
|
src/app/shared/baseurl.ts
|
<reponame>brett0701/nativescript-confusion
export const baseURL = "http://127.0.0.1:3000/";
|
llooker/carousel
|
src/components/Embed/EmbedDashboard.tsx
|
<reponame>llooker/carousel
import React, { useCallback, useContext, useEffect } from "react"
import { EmbedProps } from "./types"
import { LookerEmbedSDK, LookerEmbedDashboard } from '@looker/embed-sdk'
import {
ExtensionContext,
ExtensionContextData,
} from "@looker/extension-sdk-react"
import { Button, Heading, Label, ToggleSwitch } from "@looker/components"
import { SandboxStatus } from '../SandboxStatus'
import { EmbedContainer } from './components/EmbedContainer'
export const EmbedDashboard: React.FC<EmbedProps> = () => {
const [dashboardNext, setDashboardNext] = React.useState(true)
const [activeFilter, setActiveFilter] = React.useState('')
const [activeFilterIndex, setActiveFilterIndex] = React.useState(0)
const [running, setRunning] = React.useState(true)
const [dashboard, setDashboard] = React.useState<LookerEmbedDashboard>()
const extensionContext = useContext<ExtensionContextData>(ExtensionContext)
const filters = {0:'Login_Login',1:'FT_UPI',2:'FT_Mobile',3:'FT_MMID',4:'FT_Account',5:'FA_UPI'}
React.useEffect(() => {
var counter = 0
const interval = setInterval(() => {
counter += 1
setActiveFilterIndex((counter)%4)
}, 10000);
return () => clearInterval(interval);
}, []);
React.useEffect(() => {
if (dashboard) {
console.log(filters[activeFilterIndex])
dashboard.updateFilters({'_carousel':filters[activeFilterIndex]})
dashboard.run()
}
}, [activeFilterIndex]
);
const updateRunButton = (running: boolean) => {
setRunning(running)
}
const setupDashboard = (dashboard: LookerEmbedDashboard) => {
setDashboard(dashboard)
}
const embedCtrRef = useCallback(el => {
const hostUrl = extensionContext?.extensionSDK?.lookerHostData?.hostUrl
if (el && hostUrl) {
el.innerHTML = ''
LookerEmbedSDK.init(hostUrl)
const db = LookerEmbedSDK.createDashboardWithId(4)
// db.withNext()
db.appendTo(el)
.build()
.connect()
.then(setupDashboard)
.catch((error: Error) => {
console.error('Connection error', error)
})
}
}, [])
return (
<>
<EmbedContainer ref={embedCtrRef}/>
</>
)
}
|
stomo21/ng-router-state-params
|
router-state-params.ts
|
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from '@angular/router';
import { RouterStateParamsService } from './src/router-state-params.service';
// for manual imports
export * from './src/router-state-params.service';
@NgModule({
imports: [
RouterModule
],
declarations: [
],
providers: [
RouterStateParamsService
],
exports: [
]
})
export class RouterStateParamsModule {
}
|
stomo21/ng-router-state-params
|
src/router-state-params.service.ts
|
<reponame>stomo21/ng-router-state-params
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { map, filter } from 'rxjs/operators';
/**
* router state params service
* usage: add to a component constructor
* constructor(public routerStateService: RouterStateService) { }
*
* the may be used in component class or template
* getRoute() : Observable<ActivatedRoute> - contains the ActivatedRoute object
* getUrl() : Observable<string> - url component, does not include domain
* getConfig() : Observable<object> - route config options for the active route (contains title if provided)
* getParams() : Observable<object> - all params and values for current route (duplicate names overwritten)
* getPath() : Observable<string> - returns the active path string
*
* getRouteValue() : ActivatedRoute - contains the ActivatedRoute object
* getUrlValue() : string - url component, does not include domain
* getConfigValue() : object - route config options for the active route (contains title if provided)
* getParamsValue() : object - all params and values for current route (duplicate names overwritten)
* getPathValue() : string - active path
*/
@Injectable()
export class RouterStateParamsService {
url: String;
urlSubject: BehaviorSubject<String>;
path: String;
pathSubject: BehaviorSubject<String>;
route: ActivatedRoute;
routeSubject: BehaviorSubject<ActivatedRoute>;
config: Object;
configSubject: BehaviorSubject<Object>;
params: Object;
paramsSubject: BehaviorSubject<Object>;
constructor(private activatedRoute: ActivatedRoute, private router: Router) {
this.urlSubject = new BehaviorSubject<String>(null);
this.pathSubject = new BehaviorSubject<String>(null);
this.routeSubject = new BehaviorSubject<ActivatedRoute>(null);
this.configSubject = new BehaviorSubject<Object>(null);
this.paramsSubject = new BehaviorSubject(null);
var allRoutes = [];
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map((_) => this.router.routerState.root),
map((route) => {
allRoutes = [];
allRoutes.push({
config: route.routeConfig,
params: route.params,
});
while (route.firstChild) {
route = route.firstChild;
allRoutes.push({
config: route.routeConfig,
params: route.params,
});
}
return allRoutes;
})
)
.subscribe((data) => {
this.route = activatedRoute;
this.url = router.url;
this.config = data[data.length - 1].config;
let paths = [];
this.params = {};
if (allRoutes.length) {
allRoutes.map((val) => {
if (val && val.params && val.params.value) {
this.params = Object.assign(this.params, val.params.value);
}
if (val && val.config && val.config.path) {
paths.push(val.config.path);
}
});
}
this.path = paths.join('/');
this.routeSubject.next(this.route);
this.urlSubject.next(this.url);
this.configSubject.next(this.config);
this.paramsSubject.next(this.params);
});
}
getRoute() {
return this.routeSubject.asObservable();
}
getPath() {
return this.pathSubject.asObservable();
}
getUrl() {
return this.urlSubject.asObservable();
}
getConfig() {
return this.configSubject.asObservable();
}
getParams() {
return this.paramsSubject.asObservable();
}
getRouteValue() {
return this.route || {};
}
getPathValue() {
return this.path || '';
}
getUrlValue() {
return this.url;
}
getConfigValue() {
return this.config || {};
}
getParamsValue() {
return this.params;
}
isActivePath(path: string, exact: boolean) {
if (this.path) {
if (exact) {
if (path == this.path || path == '/' + this.path) {
return true;
}
} else {
if (
this.path.indexOf(path) === 0 ||
('/' + this.path).indexOf(path) === 0
) {
return true;
}
}
}
return false;
}
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/home.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Core } from '@src/app/model/core';
import { WeaponItem } from '@src/app/model/weapon';
import { RouteKeep } from '@app/core/router-config/route-keep'
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements RouteKeep {
constructor() { }
NG_ROUTE_KEEP: boolean = true;
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/extra-info/extra-info.component.ts
|
<gh_stars>1-10
import { Component, Input, OnInit } from '@angular/core';
import { ExtraInfo } from '../../model';
@Component({
selector: 'app-extra-info',
templateUrl: './extra-info.component.html',
styleUrls: ['./extra-info.component.scss']
})
export class ExtraInfoComponent {
@Input() extra: ExtraInfo;
constructor() { }
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/result/atk/atk.component.ts
|
<reponame>elernal-tree/elernal-tree
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-atk',
templateUrl: './atk.component.html',
styleUrls: ['./atk.component.scss'],
})
export class AtkComponent {
constructor() {}
@Input() magunaAtk: number;
@Input() normalAtk: number;
@Input() exAtk: number;
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/result/stamina/stamina.component.ts
|
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-stamina',
templateUrl: './stamina.component.html',
styleUrls: ['./stamina.component.scss'],
})
export class StaminaComponent {
@Input() magunaStamina: number;
@Input() normalStamina: number;
@Input() exStamina: number;
@Input() weaponStamina: number;
@Input() sklStamina: number;
constructor() {}
}
|
elernal-tree/elernal-tree
|
src/app/constants/enum.ts
|
<gh_stars>1-10
/** section 1 方阵 2 ex 3 普刃 */
export enum SkillSection {
maguna = 1,
ex,
normal,
}
export enum CoreSeries {
maguna = 1,
normal,
ex,
}
export enum CoreElement {
'火' = 1,
"水",
"地",
"风",
"光",
"暗"
}
/**
* core paramType
*/
export enum SklAttrType {
atk = 3,
hp,
da,
ta,
enmity, // 背水
stamina, // 浑身
critical = 10, // 暴击率
ub,
skill = 13,
ubLimit = 22,
skillLimit = 23,
criticalDamageRatio = 36,
counter = 43,
}
export enum CoreRarity {
r = 1,
sr,
ssr,
sp
}
export enum Robot {
maguna = 1,
attribute,
normal
}
export enum AtkType {
sa = 1,
da,
ta,
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/weapon.component.ts
|
<gh_stars>1-10
import { Component, Input, OnInit } from '@angular/core';
import { CoreElement, Robot, SkillSection, SklAttrType } from '@src/app/constants/enum';
import { Core, CoreStage, PaSkillFuncition, Skill } from '@src/app/model/core';
import { WeaponItem } from '@src/app/model/weapon';
import { isNullOrUndefined } from '@src/app/util';
import { PanelData, Section } from './model';
@Component({
selector: 'app-weapon',
templateUrl: './weapon.component.html',
styleUrls: ['./weapon.component.scss'],
})
export class WeaponComponent {
weaponList: WeaponItem[] = new Array(10).fill({
core: null,
lv: 60,
sLv: 3,
exLv: 0
});
panelData: PanelData = {
element: CoreElement.火,
mainRobot: Robot.maguna,
mainRobotValue: 0,
subRobot: Robot.attribute,
subRobotValue: 0,
pureAtk: 0,
pureHp: 0,
atk: {
normal: 0,
ex: 0,
maguna: 0,
},
hp: {
normal: 0,
ex: 0,
maguna: 0,
},
da: {
normal: 0,
ex: 0,
maguna: 0,
},
ta: {
normal: 0,
ex: 0,
maguna: 0,
},
enmity: {
normal: 0,
ex: 0,
maguna: 0,
},
stamina: {
normal: 0,
ex: 0,
maguna: 0,
},
critical: {
normal: 0,
ex: 0,
maguna: 0,
},
criticalDamageRatio: {
normal: 0,
ex: 0,
maguna: 0,
},
ub: {
normal: 0,
ex: 0,
maguna: 0,
},
ubLimit: {
normal: 0,
ex: 0,
maguna: 0,
},
skillDamage: {
normal: 0,
ex: 0,
maguna: 0,
},
skillLimit: {
normal: 0,
ex: 0,
maguna: 0,
},
};
constructor() {}
dragDroped(ev: any) {
const data = ev.data;
if (isNullOrUndefined(data.index)) {
this.weaponList[ev.index] = {
core: data,
lv: 60,
sLv: 3,
exLv: 0
};
} else {
if (this.weaponList[ev.index].core) {
this.weaponList[data.index] = this.weaponList[ev.index];
}
this.weaponList[ev.index] = data.data;
}
this.countResult();
}
countResult() {
let [pureAtk, pureHp] = [0, 0];
const atk: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const hp: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const da: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const ta: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const enmity: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const stamina: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const critical: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const ub: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const skill: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const skillLimit: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const ubLimit: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
const criticalDamageRatio: Section = {
normal: 0,
maguna: 0,
ex: 0,
};
this.weaponList.forEach((weapon) => {
if (weapon.core) {
const core = weapon.core.data;
const stage = core.coreStage[core.coreMaxstage];
pureHp += core.coreMinHp + core.coreAddHp * (weapon.lv - 1) + core.coreBounsHp[weapon.exLv];
pureAtk += core.coreMinAtk + core.coreAddAtk * (weapon.lv - 1) + core.coreBounsAtk[weapon.exLv];
const paSkillFuncition2 = stage.skill2?.paSkillFuncition ?? [];
const paSkillFuncition = [...stage.skill1.paSkillFuncition, ...paSkillFuncition2];
paSkillFuncition.forEach((skillfn) => {
if (this.canCountWithElement(skillfn.element)) {
this.countAtk(atk, skillfn, weapon.sLv);
this.countHp(hp, skillfn, weapon.sLv);
this.countDa(da, skillfn, weapon.sLv);
this.countTa(ta, skillfn, weapon.sLv);
this.countEnmity(enmity, skillfn, weapon.sLv);
this.countCritical(critical, skillfn, weapon.sLv);
this.countStamina(stamina, skillfn, weapon.sLv);
this.countUb(ub, skillfn, weapon.sLv);
this.countSkill(skill, skillfn, weapon.sLv);
this.countSkillLimit(skillLimit, skillfn, weapon.sLv);
this.countUbLimit(ubLimit, skillfn, weapon.sLv);
this.countCrticaliDamageRatio(criticalDamageRatio, skillfn, weapon.sLv);
}
});
}
});
this.panelData.pureAtk = pureAtk;
this.panelData.pureHp = pureHp;
this.panelData.atk = atk;
this.panelData.hp = hp;
this.panelData.enmity = enmity;
this.panelData.stamina = stamina;
this.panelData.da = da;
this.panelData.ta = ta;
this.panelData.critical = critical;
this.panelData.ub = ub;
this.panelData.skillDamage = skill;
this.panelData.skillLimit = skillLimit;
this.panelData.ubLimit = ubLimit;
this.panelData.criticalDamageRatio = criticalDamageRatio;
}
/**
* 1 + (加成) * 回响
*/
countAtk(atk: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.atk) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
atk.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
atk.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
atk.ex += sklVal;
}
}
}
}
countHp(hp: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.hp) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
hp.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
hp.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
hp.ex += sklVal;
}
}
}
}
countEnmity(enmity: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.enmity) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
enmity.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
enmity.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
enmity.ex += sklVal;
}
}
}
}
countStamina(stamina: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.stamina) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
stamina.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
stamina.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
stamina.ex += sklVal;
}
}
}
}
countDa(da: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.da) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
da.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
da.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
da.ex += sklVal;
}
}
}
}
countTa(ta: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.ta) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
ta.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
ta.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
ta.ex += sklVal;
}
}
}
}
countCritical(critical: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.critical) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
critical.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
critical.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
critical.ex += sklVal;
}
}
}
}
countUb(ub: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.ub) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
ub.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
ub.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
ub.ex += sklVal;
}
}
}
}
countSkill(skill: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.skill) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
skill.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
skill.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
skill.ex += sklVal;
}
}
}
}
countSkillLimit(skillLimit: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.skillLimit) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
skillLimit.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
skillLimit.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
skillLimit.ex += sklVal;
}
}
}
}
/** elemnt为0或者无,为全属性加成,列如格拉拉. */
canCountWithElement(element?: number) {
return !element || this.panelData.element === element;
}
countUbLimit(ubLimit: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.ubLimit) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
ubLimit.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
ubLimit.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
ubLimit.ex += sklVal;
}
}
}
}
countCrticaliDamageRatio(crticaliDamageRatio: Section, skillfn: PaSkillFuncition, sklLv: number) {
if (this.canCountWithElement(skillfn.element)) {
if (skillfn.paramType === SklAttrType.criticalDamageRatio) {
const sklVal = skillfn.paValue[sklLv];
if (skillfn.section === SkillSection.maguna) {
crticaliDamageRatio.maguna += sklVal;
} else if (skillfn.section === SkillSection.normal) {
crticaliDamageRatio.normal += sklVal;
} else if (skillfn.section === SkillSection.ex) {
crticaliDamageRatio.ex += sklVal;
}
}
}
}
}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/data-panel.component.ts
|
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CoreOption, Limit } from '@src/app/constants/constants';
import { Robot } from '@src/app/constants/enum';
import { ExtraInfo, PanelData } from '../model';
import { ShushuService } from '@app/core/service/shushu.service';
const calcBonus = 'x * (100 + y) / 10000';
@Component({
selector: 'app-data-panel',
templateUrl: './data-panel.component.html',
styleUrls: ['./data-panel.component.scss'],
})
export class DataPanelComponent {
robotOption = [
{
label: '方阵',
value: Robot.maguna,
},
{
label: '属性',
value: Robot.attribute,
},
{
label: '老王',
value: Robot.normal,
},
];
coreOption = CoreOption;
@Input() panelData: PanelData;
@Output() dataChange = new EventEmitter<void>();
extra: ExtraInfo = {
atk: 0,
hp: 0,
attribute: 0,
skill: 0,
ub: 0,
cri: 0,
criDamageRadio: 0,
atkBuff: 20,
defense: 10,
/** 当前hp百分比 */
hpPercent: 50,
weaponEnmity: 0,
weaponStamina: 0,
sklEnmity: 0,
sklStamina: 0,
da: 0,
ta: 0,
hpBonus: 20,
ubLimit: 0,
sklLimit: 0,
damageLimit: 0,
spLimit: 0,
damageBonus: 0,
atkLimit: 0,
};
constructor(private shushuSrv: ShushuService) {}
// TODO 修改实现
elementChange() {
setTimeout(() => {
this.dataChange.emit();
}, 0);
}
calcBonus(x: number, y: number) {
return eval(calcBonus.replace('x', `${x}`).replace('y', `${y}`));
}
get attributeBonus() {
return this.transferPercent(this.roboteBonus.attribute + this.extra.attribute);
}
get roboteBonus() {
return {
maguna:
(this.panelData.mainRobot === Robot.maguna ? this.panelData.mainRobotValue : 0) +
(this.panelData.subRobot === Robot.maguna ? this.panelData.subRobotValue : 0),
normal:
(this.panelData.mainRobot === Robot.normal ? this.panelData.mainRobotValue : 0) +
(this.panelData.subRobot === Robot.normal ? this.panelData.subRobotValue : 0),
attribute:
(this.panelData.mainRobot === Robot.attribute ? this.panelData.mainRobotValue : 0) +
(this.panelData.subRobot === Robot.attribute ? this.panelData.subRobotValue : 0),
};
}
get magunaAtk() {
return this.calcBonus(this.panelData.atk.maguna, this.roboteBonus.maguna);
}
get normalAtk() {
return this.calcBonus(this.panelData.atk.normal, this.roboteBonus.normal);
}
get exAtk() {
return this.calcBonus(this.panelData.atk.ex, 0);
}
/**
* 上限 -70%~
*/
getHpLimit(hp: number) {
return hp <= Limit.hp ? Limit.hp : hp;
}
get magunaHp() {
return this.getHpLimit(this.calcBonus(this.panelData.hp.maguna, this.roboteBonus.maguna));
}
get normalHp() {
return this.getHpLimit(this.calcBonus(this.panelData.hp.normal, this.roboteBonus.normal));
}
get exHp() {
return this.getHpLimit(this.calcBonus(this.panelData.hp.ex, 0));
}
/**
* 综合上限 -99.99%~
*/
get hpBonus() {
let hp = this.magunaHp + this.normalHp + this.exHp;
hp = hp <= Limit.totalHp ? Limit.totalHp : hp;
return hp + this.transferPercent(this.extra.hpBonus);
}
get magunaDa() {
return this.calcBonus(this.panelData.da.maguna, this.roboteBonus.maguna);
}
get normalDa() {
return this.calcBonus(this.panelData.da.normal, this.roboteBonus.normal);
}
get exDa() {
return this.calcBonus(this.panelData.da.ex, 0);
}
/**
* 盘子上限 75 不包含职武
*/
get da() {
let coreDa = this.magunaDa + this.normalDa + this.exDa;
coreDa = coreDa >= Limit.combo ? Limit.combo : coreDa;
const da = coreDa + this.transferPercent(this.extra.da);
return da >= 1 ? 1 : da;
}
get magunaTa() {
return this.calcBonus(this.panelData.ta.maguna, this.roboteBonus.maguna);
}
get normalTa() {
return this.calcBonus(this.panelData.ta.normal, this.roboteBonus.normal);
}
get exTa() {
return this.calcBonus(this.panelData.ta.ex, 0);
}
/**
* 盘子上限 75 不包含职武
*/
get ta() {
let coreTa = this.magunaTa + this.normalTa + this.exTa;
coreTa = coreTa >= Limit.combo ? Limit.combo : coreTa;
const ta = coreTa + this.transferPercent(this.extra.ta);
return ta >= 1 ? 1 : ta;
}
/**
* 根据背水曲线公式计算当前hp的背水攻刃加成 80%hp以上为0
*/
get enmityWithHp() {
return this.shushuSrv.enmityWithHp(this.extra.hpPercent);
}
get staminaWithHp() {
return this.shushuSrv.staminaWithHp(this.extra.hpPercent);
}
get magunaEnmity() {
return this.calcBonus(this.panelData.enmity.maguna, this.roboteBonus.maguna);
}
get normalEnmity() {
return this.calcBonus(this.panelData.enmity.normal, this.roboteBonus.normal);
}
get exEnmity() {
return this.calcBonus(this.panelData.enmity.ex, 0);
}
/** 综合背水 */
get enmity() {
return this.magunaEnmity + this.normalEnmity + this.exEnmity;
}
get magunaStamina() {
return this.calcBonus(this.panelData.stamina.maguna, this.roboteBonus.maguna);
}
get normalStamina() {
return this.calcBonus(this.panelData.stamina.normal, this.roboteBonus.normal);
}
get exStamina() {
return this.calcBonus(this.panelData.stamina.ex, 0);
}
get stamina() {
return this.magunaStamina + this.normalStamina + this.exStamina;
}
get magunaSkl() {
return this.calcBonus(this.panelData.skillDamage.maguna, this.roboteBonus.maguna);
}
get mormalSkl() {
return this.calcBonus(this.panelData.skillDamage.normal, this.roboteBonus.normal);
}
get exSkl() {
return this.calcBonus(this.panelData.skillDamage.ex, 0);
}
get skill() {
return this.magunaSkl + this.mormalSkl + this.exSkl + this.transferPercent(this.extra.skill);
}
get magunaUb() {
return this.calcBonus(this.panelData.ub.maguna, this.roboteBonus.maguna);
}
get noramlUb() {
return this.calcBonus(this.panelData.ub.normal, this.roboteBonus.normal);
}
get exUb() {
return this.calcBonus(this.panelData.ub.ex, 0);
}
get ub() {
return this.magunaUb + this.noramlUb + this.exUb + this.transferPercent(this.extra.ub);
}
/**老王 方阵 ex每个区间 上限为 0~50% */
getUbLimit(ub: number) {
return ub >= Limit.ubBonus ? Limit.ubBonus : ub;
}
get magunaUbLimit() {
return this.getUbLimit(this.calcBonus(this.panelData.ubLimit.maguna, this.roboteBonus.maguna));
}
get noramlUbLimit() {
return this.getUbLimit(this.calcBonus(this.panelData.ubLimit.normal, this.roboteBonus.normal));
}
get exUbLimit() {
return this.getUbLimit(this.calcBonus(this.panelData.ubLimit.ex, 0));
}
get ubLimit() {
return (
this.magunaUbLimit +
this.noramlUbLimit +
this.exUbLimit +
this.transferPercent(this.extra.ubLimit + this.extra.damageLimit)
);
}
/** 老王 方阵 ex每个区间 上限为 skillLimit 0~50% */
getSkillLimit(skill: number) {
return skill >= Limit.sklBonus ? Limit.sklBonus : skill;
}
get magunaSklLimit() {
return this.getSkillLimit(
this.calcBonus(this.panelData.skillLimit.maguna, this.roboteBonus.maguna)
);
}
get normalSklLimit() {
return this.getSkillLimit(
this.calcBonus(this.panelData.skillLimit.normal, this.roboteBonus.normal)
);
}
get exSklLimit() {
return this.getSkillLimit(this.calcBonus(this.panelData.skillLimit.ex, 0));
}
get skillLimit() {
return (
this.magunaSklLimit +
this.normalSklLimit +
this.exSklLimit +
this.transferPercent(this.extra.sklLimit + this.extra.damageLimit)
);
}
get magunaCri() {
return this.calcBonus(this.panelData.critical.maguna, this.roboteBonus.maguna);
}
get normalCri() {
return this.calcBonus(this.panelData.critical.normal, this.roboteBonus.normal);
}
get exCri() {
return this.calcBonus(this.panelData.critical.ex, 0);
}
/** 暴击率 */
get critical() {
return this.magunaCri + this.normalCri + this.exCri + this.transferPercent(this.extra.cri);
}
get magunaCriticalDamageRatio() {
return this.calcBonus(this.panelData.criticalDamageRatio.maguna, this.roboteBonus.maguna);
}
get normalCriticalDamageRatio() {
return this.calcBonus(this.panelData.criticalDamageRatio.normal, this.roboteBonus.normal);
}
get exCriticalDamageRatio() {
return this.calcBonus(this.panelData.criticalDamageRatio.ex, 0);
}
get criticalDamageRatio() {
return (
this.magunaCriticalDamageRatio +
this.normalCriticalDamageRatio +
this.exCriticalDamageRatio +
this.transferPercent(this.extra.criDamageRadio)
);
}
/** 基础10防御 由于浑身公式不明确 所以计算直接使用的面板数值*/
get atkDamage() {
return (
((this.panelData.pureAtk + this.extra.atk) *
(1 + this.magunaAtk) *
(1 + this.normalAtk) *
(1 + this.exAtk) *
(1 + this.attributeBonus) *
(1 + this.transferPercent(this.extra.atkBuff)) *
(1 + (this.enmity + this.transferPercent(this.extra.weaponEnmity)) * this.enmityWithHp) *
(1 + (this.stamina + this.transferPercent(this.extra.weaponStamina)) * this.staminaWithHp) *
(1 + this.transferPercent(this.extra.sklEnmity) * this.enmityWithHp) *
(1 + this.transferPercent(this.extra.sklStamina) * this.staminaWithHp) *
(1 + this.transferPercent(this.extra.damageBonus))) /
this.extra.defense
);
}
// HP白值
get pureHp() {
return this.panelData.pureHp + this.extra.hp;
}
transferPercent(value: number) {
return value / 100;
}
get spLimit() {
return this.transferPercent(this.extra.spLimit);
}
get atkLimit() {
return this.transferPercent(this.extra.atkLimit + this.extra.damageLimit);
}
}
|
elernal-tree/elernal-tree
|
src/app/core/service/shushu.service.ts
|
import { Injectable } from '@angular/core';
import { Limit } from '@src/app/constants/constants';
import { AtkType } from '@src/app/constants/enum';
@Injectable({
providedIn: 'root',
})
export class ShushuService {
constructor() {}
atkLimit(damage: number, type: AtkType, LimitBonus: number) {
let limit = Limit.saDamage;
if (type === AtkType.da) {
limit = Limit.daDamage;
}
if (type === AtkType.ta) {
limit = Limit.taDamage;
}
limit = limit * ( 1 + LimitBonus);
return damage >= limit ? limit : damage;
}
/**
* 根据背水曲线公式计算当前hp的背水攻刃加成 80%hp以上为0
* X 为当前剩余血量百分比
* 1.3X^2-3.75X+2.55
*/
enmityWithHp(hp: number) {
if (hp >= 80) {
return 0;
}
const X = hp / 100;
return 1.3 * X * X - 3.75 * X + 2.55;
}
/**
* 根据浑身公式计算当前hp的浑身加成 25%以下为0
* 浑身公式暂不明确
* X 为当前血量百分比
* 0.99X^2+0.075X+0.01
*/
staminaWithHp(hp: number) {
if (hp <= 25) {
return 0;
}
const X = hp / 100;
return 0.99 * X * X + 0.075 * X + 0.01;
}
}
|
elernal-tree/elernal-tree
|
src/app/share/directives/darg-drop/cdrag.directive.ts
|
<gh_stars>1-10
import { DOCUMENT } from '@angular/common';
import {
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
NgZone,
OnDestroy,
Output,
} from '@angular/core';
@Directive({
selector: '[appCdrag]',
})
export class CdragDirective<T = any> implements OnDestroy {
@Input('dragData') data!: any;
// @Input() dataSource: string =
@Input('dataKey') key!: string;
@Output('dragStarted') readonly started: EventEmitter<DragEvent> =
new EventEmitter<DragEvent>();
@Output('dragMoved') readonly moved: EventEmitter<DragEvent> =
new EventEmitter<DragEvent>();
constructor(
public element: ElementRef<HTMLElement>,
@Inject(DOCUMENT) _document: Document,
private _ngZone: NgZone
) {
element.nativeElement?.setAttribute('draggable', 'true');
_ngZone.runOutsideAngular(() => {
const _el = element.nativeElement;
_el.addEventListener('dragstart', (ev) => {
this.started.emit(ev);
let data = '';
try {
data = JSON.stringify(this.data);
} catch (error) {
data = this.data;
}
if(data) {
ev.dataTransfer?.setData('Text', data);
}
});
_el.addEventListener('drag', (ev) => {
this.moved.emit(ev);
});
});
}
ngOnDestroy() {
this._ngZone.runOutsideAngular(() => {
this.element.nativeElement.removeAllListeners?.();
});
}
}
|
elernal-tree/elernal-tree
|
src/app/share/directives/directives.module.ts
|
<gh_stars>1-10
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ClickStopModule } from './click-stop/click-stop.module';
import { ContextmuneModule } from './contextmenu/contextmenu.module';
import { DargDropModule } from './darg-drop/darg-drop.module';
@NgModule({
declarations: [],
imports: [CommonModule],
exports: [ClickStopModule, ContextmuneModule, DargDropModule],
})
export class DirectivesModule {}
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/result/enmity/enmity.component.ts
|
<gh_stars>1-10
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-enmity',
templateUrl: './enmity.component.html',
styleUrls: ['./enmity.component.scss']
})
export class EnmityComponent {
@Input() magunaEnmity: number;
@Input() normalEnmity: number;
@Input() exEnmity: number;
@Input() weaponEnmity: number;
@Input() sklEnmity: number;
constructor() { }
}
|
elernal-tree/elernal-tree
|
src/app/pages/ng-zorro.ts
|
import { NzGridModule } from 'ng-zorro-antd/grid'
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzPopoverModule } from 'ng-zorro-antd/popover';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzTableModule } from 'ng-zorro-antd/table';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzButtonModule } from 'ng-zorro-antd/button';
export const NgZorroModules = [
NzGridModule,
NzSelectModule,
NzPopoverModule,
NzInputNumberModule,
NzTableModule,
NzTabsModule,
NzButtonModule
]
|
elernal-tree/elernal-tree
|
src/app/pages/home/component/weapon/data-panel/result/result.component.ts
|
import { Component, Input, OnInit } from '@angular/core';
import { ShushuService } from '@app/core/service/shushu.service';
import { AtkRatio, CriRatio } from '@src/app/constants/constants';
import { AtkType } from '@src/app/constants/enum';
@Component({
selector: 'app-result',
templateUrl: './result.component.html',
styleUrls: ['./result.component.scss'],
})
export class ResultComponent {
nzWidthConfig = new Array(5).fill('20%');
@Input() hpBonus: number;
@Input() hpPercent: number;
@Input() pureHp: number;
@Input() critical: number;
@Input() criticalDamageRatio: number;
@Input() magunaEnmity: number;
@Input() normalEnmity: number;
@Input() exEnmity: number;
@Input() weaponEnmity: number;
@Input() sklEnmity: number;
@Input() magunaStamina: number;
@Input() normalStamina: number;
@Input() exStamina: number;
@Input() weaponStamina: number;
@Input() sklStamina: number;
@Input() attributeBonus: number;
@Input() magunaAtk: number;
@Input() normalAtk: number;
@Input() exAtk: number;
@Input() atkDamage: number;
@Input() spLimit: number;
@Input() atkLimit: number;
constructor(private shushuSrv: ShushuService) {}
fixedAtkDamage(num: number) {
return (this.shushuSrv.atkLimit(num, AtkType.sa, this.atkLimit) * (1 + this.spLimit)).toFixed(0);
}
get enmityWithHp() {
return this.shushuSrv.enmityWithHp(this.hpPercent);
}
get staminaWithHp() {
return this.shushuSrv.staminaWithHp(this.hpPercent);
}
get coreEnmity() {
return (
(this.magunaEnmity + this.normalEnmity + this.exEnmity + this.weaponEnmity / 100) *
this.enmityWithHp
);
}
get enmity() {
return (1 + this.coreEnmity) * (1 + (this.sklEnmity / 100) * this.enmityWithHp) - 1;
}
get coreStamina() {
return (
(this.magunaStamina + this.normalStamina + this.exStamina + this.weaponStamina / 100) *
this.staminaWithHp
);
}
get stamina() {
return (1 + this.coreStamina) * (1 + (this.sklStamina / 100) * this.staminaWithHp) - 1;
}
get hp() {
return (this.pureHp * (1 + this.hpBonus)).toFixed(0);
}
get atkBonus() {
return (1 + this.magunaAtk) * (1 + this.normalAtk) * (1 + this.exAtk) - 1;
}
get damage() {
return this.fixedAtkDamage(this.atkDamage * AtkRatio.normal);
}
get upDamage() {
return this.fixedAtkDamage(this.atkDamage * AtkRatio.up);
}
get downDamage() {
return this.fixedAtkDamage(this.atkDamage * AtkRatio.down);
}
get criDamage() {
return this.fixedAtkDamage(this.atkDamage * (CriRatio.noraml + this.criticalDamageRatio));
}
get criUpDamage() {
return this.fixedAtkDamage(
this.atkDamage * AtkRatio.up * (CriRatio.up + this.criticalDamageRatio)
);
}
get criDownDamage() {
return this.fixedAtkDamage(
this.atkDamage * AtkRatio.down * (CriRatio.down + this.criticalDamageRatio)
);
}
}
|
elernal-tree/elernal-tree
|
src/app/share/directives/darg-drop/darg-drop.module.ts
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {CdragDirective} from './cdrag.directive'
import { DragDropBoxDirective} from './drag-drop-box.directive';
@NgModule({
declarations: [CdragDirective, DragDropBoxDirective],
imports: [
CommonModule
],
exports: [
CdragDirective,
DragDropBoxDirective
]
})
export class DargDropModule { }
|
elernal-tree/elernal-tree
|
src/app/share/pipe/fixed.pipe.ts
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'fixed',
})
export class FixedPipe implements PipeTransform {
transform(value: number, ...args: [number?, boolean?]): unknown {
const fractionDigits = args[0] ?? 2;
const isPercent = args[1] ?? true;
return (value * (isPercent ? 100 : 1)).toFixed(fractionDigits);
}
}
|
elernal-tree/elernal-tree
|
src/app/constants/constants.ts
|
<gh_stars>1-10
import { CoreElement } from './enum';
export const CoreOption = Object.freeze([
{
label: '火',
value: CoreElement.火,
},
{
label: '水',
value: CoreElement.水,
},
{
label: '地',
value: CoreElement.地,
},
{
label: '风',
value: CoreElement.风,
},
{
label: '光',
value: CoreElement.光,
},
{
label: '暗',
value: CoreElement.暗,
},
]);
/**
* 暴击倍率:有利属性为0.5,其他属性为0.25
*/
export const CriRatio = {
up: 1.5,
noraml: 1.25,
down: 1.25
};
export const AtkRatio = {
up: 1.25,
normal: 1,
down: 0.75
}
export const DaTaRatio = {
da : 1.5,
ta: 2
}
export const Limit = {
/** 伤害上限 */
saDamage: 4e5,
daDamage: 6e5,
taDamage: 8e5,
skillDamage: 6e5,
ubDamage: 28e5,
// 单独hp区间下限
hp: -0.7,
// 综合hp下限
totalHp: -9.99999,
// 连击概率上限
combo: 0.75,
/** 单独UB上限 */
ubBonus: 0.5,
sklBonus: 0.5,
}
|
elernal-tree/elernal-tree
|
src/environments/environment.cdn.ts
|
export const environment = {
production: true,
ImgUrl:"https://cdn.jsdelivr.net/gh/elernal-tree/elernal-tree@master/static/image/core/{id}.png"
};
|
elernal-tree/elernal-tree
|
src/app/layout/default/default.component.ts
|
<gh_stars>1-10
import { AfterViewInit, Component, OnInit, QueryList, ViewChildren } from '@angular/core';
import { NzModalService} from 'ng-zorro-antd/modal';
@Component({
selector: 'app-default',
templateUrl: './default.component.html',
styleUrls: ['./default.component.scss'],
})
export class DefaultComponent {
constructor(
private nzModalSrv: NzModalService,
) { }
}
|
elernal-tree/elernal-tree
|
src/app/model/weapon.ts
|
import { Core } from "./core";
export interface WeaponItem {
core: Core,
lv: number,
sLv: number,
exLv: number
}
|
elernal-tree/elernal-tree
|
src/app/pages/pages.module.ts
|
<filename>src/app/pages/pages.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ShareModule } from '@app/share';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PagesRoutingModule } from './pages-routing.module';
import { HomeComponent } from './home/home.component';
import { NgZorroModules } from './ng-zorro';
import { WeaponComponent } from './home/component/weapon/weapon.component';
import { ArsenalComponent } from './home/component/arsenal/arsenal.component';
import { WeaponItemComponent } from './home/component/weapon/weapon-item/weapon-item.component';
import { DataPanelComponent } from './home/component/weapon/data-panel/data-panel.component';
import { NzIconModule } from 'ng-zorro-antd/icon';
import { IconDefinition } from '@ant-design/icons-angular';
import { PlusOutline } from '@ant-design/icons-angular/icons';
import { ResultComponent } from './home/component/weapon/data-panel/result/result.component';
import { ExtraInfoComponent } from './home/component/weapon/data-panel/extra-info/extra-info.component';
import { EnmityComponent } from './home/component/weapon/data-panel/result/enmity/enmity.component';
import { StaminaComponent } from './home/component/weapon/data-panel/result/stamina/stamina.component';
import { AboutComponent } from './about/about.component';
import { AtkComponent } from './home/component/weapon/data-panel/result/atk/atk.component';
import { SklUbComponent } from './home/component/weapon/data-panel/skl-ub/skl-ub.component';
import { ComboCriticalComponent } from './home/component/weapon/data-panel/combo-critical/combo-critical.component';
import { SimulationComponent } from './simulation/simulation.component';
const icons: IconDefinition[] = [ PlusOutline ];
@NgModule({
declarations: [
HomeComponent,
WeaponComponent,
ArsenalComponent,
WeaponItemComponent,
DataPanelComponent,
ResultComponent,
ExtraInfoComponent,
EnmityComponent,
StaminaComponent,
AboutComponent,
AtkComponent,
SklUbComponent,
ComboCriticalComponent,
SimulationComponent
],
imports: [
CommonModule,
PagesRoutingModule,
ShareModule,
...NgZorroModules,
DragDropModule,
NzIconModule.forChild(icons)
]
})
export class PagesModule { }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.