repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
elernal-tree/elernal-tree
src/app/pages/home/component/weapon/model.ts
<gh_stars>1-10 import { CoreElement, Robot } from '@src/app/constants/enum'; export interface Section { normal: number; maguna: number; ex: number; } export interface PanelData { element: CoreElement; mainRobot: Robot; mainRobotValue: number; subRobot: Robot; subRobotValue: number; atk: Section; hp: Section; da: Section; ta: Section; enmity: Section; stamina: Section; /** 暴击率 */ critical: Section; /** 暴击伤害提升百分比 */ criticalDamageRatio: Section; ub: Section; ubLimit: Section; skillLimit: Section; skillDamage: Section; pureHp: number; pureAtk: number; } export interface ExtraInfo { /** 攻击力白值 */ atk: number; /** hp 白值 */ hp: number; /** 属攻 */ attribute: number; /** 技能攻刃 */ skill: number; /** UB攻刃 */ ub: number; cri: number; // 暴击率 criDamageRadio: number; // 爆伤提升 /** 普刃 攻刃% */ atkBuff: number; /** 敌方防御力 */ defense: number; /** 当前hp百分比 */ hpPercent: number; weaponEnmity: number; weaponStamina: number; sklStamina: number; sklEnmity: number; da: number; ta: number; /** 生命值百分比加成 */ hpBonus: number; /** 奥义上限 */ ubLimit: number; /** 技能上限 */ sklLimit: number; /** 全伤害上限 */ damageLimit: number; /** 天司被动 最终算 */ spLimit: number; /** 增加伤害 比如夏洛特*/ damageBonus: number /** 平A上限 */ atkLimit: number; }
elernal-tree/elernal-tree
src/app/share/widget/etimg/etimg/etimg.component.ts
import { Component, OnInit, Input } from '@angular/core'; import { Core, Skill } from '@src/app/model/core'; import {environment } from '@src/environments/environment' const Rarity = ['', 'R', 'SR', 'SSR']; @Component({ selector: 'app-etimg', templateUrl: './etimg.component.html', styleUrls: ['./etimg.component.scss'], }) export class EtimgComponent { _core: Core; imgSrc = ''; rarity = 'R'; skill1: Skill; skill2?: Skill; coreName = ''; @Input() set core(value) { this._core = value; this.setImgSrc(); this.setRarity(); this.setSkill(); this.setName(); } get core() { return this._core; } @Input() showTip = true; constructor() {} setImgSrc() { this.imgSrc = environment.ImgUrl.replace('{id}', `${this.core.id}`); } setRarity() { this.rarity = Rarity[this.core.data.coreRarity] ?? 'R'; } setSkill() { const value = this.core; const skillData = value.data.coreStage[value.data.coreMaxstage]; this.skill1 = skillData.skill1; this.skill1.paSkillFuncition.forEach((r) => { this.skill1.cnDescription = this.skill1.cnDescription.replace( /&/, r.paValue .slice(0, value.data.coreMaxSklv) .map((v) => +v.toFixed(1)) .join('/') ); }); if (skillData.skill2) { this.skill2 = skillData.skill2; this.skill2.paSkillFuncition.forEach((r) => { this.skill2.cnDescription = this.skill2.cnDescription.replace( /&/, r.paValue .slice(0, value.data.coreMaxSklv) .map((v) => +v.toFixed(1)) .join('/') ); }); } } setName() { let label = this.core.data.name; this.coreName = label; } }
elernal-tree/elernal-tree
src/app/core/core.module.ts
<gh_stars>1-10 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CacheReuseStrategy } from './router-config/cacheReuseStrategy'; import { RouteReuseStrategy } from '@angular/router'; @NgModule({ declarations: [], imports: [ CommonModule ], providers: [ { provide: RouteReuseStrategy, useClass: CacheReuseStrategy }, ] }) export class CoreModule { }
elernal-tree/elernal-tree
src/app/share/directives/darg-drop/drag-drop-box.directive.ts
<reponame>elernal-tree/elernal-tree import { DOCUMENT } from '@angular/common'; import { Directive, ElementRef, EventEmitter, Inject, Input, NgZone, OnDestroy, Output, } from '@angular/core'; @Directive({ selector: '[appDragDropBox]', }) export class DragDropBoxDirective implements OnDestroy { @Output('dragEnterd') readonly enterd: EventEmitter<DragEvent> = new EventEmitter<DragEvent>(); @Output('dragDroped') readonly droped: EventEmitter<{ ev: DragEvent, data: string }> = new EventEmitter<{ ev: DragEvent, data: string }>(); @Output('dragLeaved') readonly leaved: EventEmitter<DragEvent> = new EventEmitter<DragEvent>(); @Input('previewClass') previewClass = 'previewPlacehoder' currentData: any; constructor( public element: ElementRef<HTMLElement>, @Inject(DOCUMENT) _document: Document, private _ngZone: NgZone ) { const _el = element.nativeElement; _ngZone.runOutsideAngular(() => { _el.addEventListener('dragenter', (ev: any) => { this.enterd.emit(ev); console.log('enter box') const toEl: HTMLElement = ev.toElement _el.classList.add(this.previewClass) }); _el.addEventListener('dragleave', (ev: any) => { this.leaved.emit(ev); const toEl: HTMLElement = ev.toElement _el.classList.remove(this.previewClass) }); // dragover会阻止放入 _el.addEventListener('dragover', (ev) => { ev.preventDefault() }) }); _el.addEventListener('drop', (ev: any) => { ev.preventDefault() console.log('drop') const toEl: HTMLElement = ev.toElement; _el.classList.remove(this.previewClass) let data = ev.dataTransfer?.getData('Text'); try { data = JSON.parse(ev.dataTransfer?.getData('Text')) } catch (error) { } this.droped.emit({ ev, data: data }); }); } ngOnDestroy() { this._ngZone.runOutsideAngular(() => { this.element.nativeElement.removeAllListeners?.(); }); } }
elernal-tree/elernal-tree
src/app/pages/home/component/weapon/weapon-item/weapon-item.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { WeaponItem } from '@src/app/model/weapon'; @Component({ selector: 'app-weapon-item', templateUrl: './weapon-item.component.html', styleUrls: ['./weapon-item.component.scss'] }) export class WeaponItemComponent { @Input() weapon: WeaponItem; @Input() index: number; @Output('dragDroped') droped = new EventEmitter<{ index: number, data: any }>() @Output() dataChange = new EventEmitter<void>(); sLvOption = [{ label: 1, value: 0 }, { label: 2, value: 1 }, { label: 3, value: 2 }, { label: 4, value: 3 }]; exLvOption = new Array(60).fill(0).map((_, index) => ({label: index + 1, value: index})); constructor() { } dragDroped(event: any) { this.droped.emit({ data: event.data, index: this.index }); } onDataChange() { this.dataChange.emit(); } onDeleteCore() { // this.deleteCore.emit() this.weapon.core = null; this.onDataChange(); } }
elernal-tree/elernal-tree
src/app/pages/home/component/arsenal/arsenal.component.ts
<filename>src/app/pages/home/component/arsenal/arsenal.component.ts import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { Core } from '@src/app/model/core'; import { HttpClient } from '@angular/common/http'; import { CoreElement, CoreSeries } from '@src/app/constants/enum'; import { CdkDragDrop, CdkDragStart, CdkDragMove } from '@angular/cdk/drag-drop'; import { CoreOption } from '@src/app/constants/constants'; @Component({ selector: 'app-arsenal', templateUrl: './arsenal.component.html', styleUrls: ['./arsenal.component.scss'], }) export class ArsenalComponent implements OnInit { coreList: Core[] = []; currentCoreElement = CoreElement.火; coreOption = CoreOption; constructor(private _http: HttpClient) {} ngOnInit(): void { this._http.get<Core[]>('/api/core').subscribe((r) => { this.coreList = r; }); } get currentCoreList() { return this.coreList.filter((core) => core.data.coreElement === this.currentCoreElement); } get magunaCore() { return this.currentCoreList .filter((core) => core.data.coreSeries === CoreSeries.maguna) .sort((a, b) => b.data.coreRarity - a.data.coreRarity); } get normalCore() { return this.currentCoreList .filter((core) => core.data.coreSeries === CoreSeries.normal) .sort((a, b) => b.data.coreRarity - a.data.coreRarity); } get exCore() { return this.currentCoreList .filter((core) => core.data.coreSeries === CoreSeries.ex) .sort((a, b) => b.data.coreRarity - a.data.coreRarity); } }
elernal-tree/elernal-tree
src/app/pages/home/component/weapon/data-panel/combo-critical/combo-critical.component.ts
<gh_stars>1-10 import { Component, Input, OnInit } from '@angular/core'; import { DaTaRatio, CriRatio } from '@src/app/constants/constants'; import { AtkType } from '@src/app/constants/enum'; import { ShushuService } from '@src/app/core/service/shushu.service'; import { ExtraInfo } from '../../model'; // TODO 如果da+ta满100就不触发sa 需要进行期望计算改动 // 满100. 溢出da无效 // 不满100 2*ta+1.5*min(1-ta,da)+1*max(1-da-ta,0) // 伤害期望计算 // 100x1x0.1 // 基础伤害 x TA倍率(1) x TA率 // 100x0.5x(1-0.1)x0.1 // 基础伤害 x DA倍率(0.5) x (1-TA率)x DA率 @Component({ selector: 'app-combo-critical', templateUrl: './combo-critical.component.html', styleUrls: ['./combo-critical.component.scss'], }) export class ComboCriticalComponent { constructor(private shushuSrc: ShushuService) {} @Input() atkDamage: number; @Input() extra: ExtraInfo; @Input() da: number; @Input() ta: number; @Input() critical: number; @Input() criticalDamageRatio: number; @Input() spLimit: number; @Input() atkLimit: number; nzWidthConfig = new Array(3).fill('25%'); fixedDamage(num: number) { return (this.shushuSrc.atkLimit(num, AtkType.ta, this.atkLimit) * (1 + this.spLimit)).toFixed(0); } /**原算法 */ // get damage() { // return ( // (DaTaRatio.ta * this.ta + // DaTaRatio.da * (1 - this.ta) * this.da + // (1 - this.ta) * (1 - this.da)) * // this.atkDamage // ); // } /** 树树为圆桌,ta+da满100必定无sa */ get damage() { return ( this.atkDamage * (DaTaRatio.ta * this.ta + DaTaRatio.da * Math.min(this.da, 1 - this.ta) + Math.max(0, 1 - this.ta - this.da)) ); } get criDamage() { return this.damage * (1 + this.critical * (CriRatio.noraml + this.criticalDamageRatio - 1)); } get criUpDamage() { return this.damage * (1 + this.critical * (CriRatio.up + this.criticalDamageRatio - 1)); } get criDownDamage() { return this.damage * (1 + this.critical * (CriRatio.down + this.criticalDamageRatio - 1)); } }
elernal-tree/elernal-tree
src/environments/environment.prod.ts
<gh_stars>1-10 export const environment = { production: true, ImgUrl:"https://yjzs-core.oss-cn-beijing.aliyuncs.com/core/{id}.png" };
elernal-tree/elernal-tree
src/app/model/core.ts
<reponame>elernal-tree/elernal-tree export interface Core { id: number; data: CoreData; } export interface CoreData { canUseSpItem: number; coreAddAtk: number; coreAddHp: number; coreCanDepose: number; coreCanSell: number; coreElement: number; coreMaxLevel: number; coreMaxSklv: number; coreMaxstage: number; coreMinAtk: number; coreMinHp: number; coreRarity: number; coreSeries: number; coreStage?: CoreStage[]; id: number; skillCoreCost: SkillCoreCost; skillGoldCost: number[]; name: string; cnDescription: string[]; cnData: string[]; prefix: string[]; coreBounsAtk: number[]; coreBounsHp: number[]; } export interface CoreStage { coreDeposeItem: CoreDeposeItem[]; coreSellPrice: number; coreStageLevelLimit: number; overStageCore?: CoreDeposeItem[]; overStageGold?: number; skillSlot1: number; skill1: Skill; coreStage?: number; skillSlot2?: number; skill2?: Skill; } export interface CoreDeposeItem { count: number; itemId: number; } export interface Skill { centerIcon?: number; id: number; levelIcon: number; paSkillFuncition: PaSkillFuncition[]; paramIcon: number; seriesIcon: number; name: string; cnDescription: string; } export interface PaSkillFuncition { element?: number; paLevel: number; paramType: number; section: number; paValue: number[]; } export interface SkillCoreCost { coreId: number; count: number; }
elernal-tree/elernal-tree
src/app/pages/home/component/weapon/data-panel/skl-ub/skl-ub.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AtkRatio, Limit } from '@src/app/constants/constants'; @Component({ selector: 'app-skl-ub', templateUrl: './skl-ub.component.html', styleUrls: ['./skl-ub.component.scss'], }) export class SklUbComponent { constructor() {} @Input() atkDamage: number; @Input() skill: number; @Input() skillLimit: number; @Input() ub: number; @Input() ubLimit: number; @Input() spLimit: number; // 用于计算伤害的技能倍率 skillRatio = 200; // 用于计算伤害的奥义倍率 ubRatio = 300; sklDamageByLimit(damage: number) { const limit = Limit.skillDamage * (1 + this.skillLimit); const result = damage >= limit ? limit : damage; return result * (1 + this.spLimit); } get _sklDamage() { return ((this.atkDamage * this.skillRatio) / 100) * (1 + this.skill); } get sklDmage() { return this.sklDamageByLimit(this._sklDamage); } get sklUpDamage() { return this.sklDamageByLimit(this._sklDamage * AtkRatio.up); } get sklDownDamage() { return this.sklDamageByLimit(this._sklDamage * AtkRatio.down); } ubDamageByLimit(damage: number) { const limit = Limit.ubDamage * (1 + this.ubLimit); const result = damage >= limit ? limit : damage; return result * (1 + this.spLimit); } get _ubDamage() { return ((this.atkDamage * this.ubRatio) / 100) * (1 + this.ub); } get ubDamage() { return this.ubDamageByLimit(this._ubDamage); } get ubUpDamage() { return this.ubDamageByLimit(this._ubDamage * AtkRatio.up); } get ubDownDamage() { return this.ubDamageByLimit(this._ubDamage * AtkRatio.down); } }
elernal-tree/elernal-tree
src/app/share/widget/etimg/etimg.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { EtimgComponent } from './etimg/etimg.component'; import { NzPopoverModule } from 'ng-zorro-antd/popover' @NgModule({ declarations: [ EtimgComponent ], imports: [ CommonModule, NzPopoverModule ], exports: [EtimgComponent] }) export class EtimgModule { }
Shinerising/easyblog
src/app/app.component.spec.ts
<filename>src/app/app.component.spec.ts import { TestBed, waitForAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { AppComponent } from './app.component'; import { ConfigService } from './service/config.service'; describe('AppComponent', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], providers: [ ConfigService ] }).compileComponents(); })); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); }); it(`should have header`, () => { const config = TestBed.inject(ConfigService); const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.header).toEqual(config.Title); }); it(`should have url`, () => { const config = TestBed.inject(ConfigService); const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.url).toEqual(config.getRepoURL()); }); it('should render title in a h1 tag', () => { const config = TestBed.inject(ConfigService); const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toEqual(config.Title); }); it('should add custom stylesheet', () => { const config = TestBed.inject(ConfigService); config.Theme = 'dark'; const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const document = fixture.debugElement.componentInstance.document; expect(document.querySelector('link:last-child').getAttribute('href')).toContain(config.Theme); }); });
Shinerising/easyblog
src/app/service/markdown.service.ts
import { Injectable, Inject } from '@angular/core'; import { ConfigService } from '../service/config.service'; import marked from 'marked'; import hljs from 'highlight.js'; import bash from 'highlight.js/lib/languages/bash'; import cs from 'highlight.js/lib/languages/csharp'; import cpp from 'highlight.js/lib/languages/cpp'; import css from 'highlight.js/lib/languages/css'; import xml from 'highlight.js/lib/languages/xml'; import json from 'highlight.js/lib/languages/json'; import java from 'highlight.js/lib/languages/java'; import javascript from 'highlight.js/lib/languages/javascript'; import markdown from 'highlight.js/lib/languages/markdown'; import objectivec from 'highlight.js/lib/languages/objectivec'; import php from 'highlight.js/lib/languages/php'; import python from 'highlight.js/lib/languages/python'; import ruby from 'highlight.js/lib/languages/ruby'; import sql from 'highlight.js/lib/languages/sql'; import typescript from 'highlight.js/lib/languages/typescript'; @Injectable({ providedIn: 'root', }) export class MarkDownService { public constructor( private config: ConfigService) { hljs.registerLanguage('bash', bash); hljs.registerLanguage('cs', cs); hljs.registerLanguage('cpp', cpp); hljs.registerLanguage('css', css); hljs.registerLanguage('xml', xml); hljs.registerLanguage('json', json); hljs.registerLanguage('java', java); hljs.registerLanguage('javascript', javascript); hljs.registerLanguage('markdown', markdown); hljs.registerLanguage('objectivec', objectivec); hljs.registerLanguage('php', php); hljs.registerLanguage('python', python); hljs.registerLanguage('ruby', ruby); hljs.registerLanguage('sql', sql); hljs.registerLanguage('typescript', typescript); const langList = ['bash', 'cs', 'cpp', 'css', 'xml', 'json', 'java', 'javascript', 'markdown', 'objectivec', 'php', 'python', 'ruby', 'sql', 'typescript']; marked.setOptions({ baseUrl: this.config.getRAWRoot(), highlight: (code: string, lang: string): string => { return lang && langList.includes(lang) ? hljs.highlight(lang, code).value : hljs.highlightAuto(code).value; } }); } public render(text: string): string { return marked(text); } }
Shinerising/easyblog
src/app/service/config.service.ts
import { Injectable, Injector } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs'; export interface Config { User: string; Repo: string; Path: string; Title: string; RAWRoot: string; Theme: string; } @Injectable({ providedIn: 'root', }) export class ConfigService implements Config { public User: string; public Repo: string; public Path: string; public Title = 'Blog'; public RAWRoot = `https://raw.githubusercontent.com`; public Theme: string; public getMarkDownURL(filename: string = ''): string { return `${this.RAWRoot}/${this.User}/${this.Repo}/master/${this.Path}/${filename}`; } public getRAWRoot(): string { return `${this.RAWRoot}/${this.User}/${this.Repo}/master/${this.Path}/`; } public getRepoURL(): string { return `https://github.com/${this.User}/${this.Repo}`; } public getFileURL(file: string): string { return `https://github.com/${this.User}/${this.Repo}/blob/master/${this.Path}/${file}`; } public getContentQuery(): string { return ` query getContent { repo:repository(owner: "${this.User}", name: "${this.Repo}") { content: object(expression: "master:${this.Path}") { ... on Tree { entries { name type oid } } } } } `; } public getCommitQuery(file: string): string { const path = this.Path ? this.Path + '/' + file : file; return ` query getCommit { repo:repository(owner: "${this.User}", name: "${this.Repo}") { content: object(expression: "master") { ... on Commit { history(path: "${path}", first:1) { edges { commit: node { oid commitUrl committedDate committer { name date email avatarUrl } } } } } } } } `; } constructor(private injector: Injector) { } public async loadConfig() { const http = this.injector.get(HttpClient); const config = await firstValueFrom(http.get<Config>('./assets/config.json')); this.User = config.User || this.User; this.Repo = config.Repo || this.Repo; this.Path = config.Path || this.Path; this.Title = config.Title || this.Title; this.RAWRoot = config.RAWRoot || this.RAWRoot; this.Theme = config.Theme || this.Theme; } }
Shinerising/easyblog
src/app/pipe/sanitize.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'sanitizeHTML' }) export class SanitizehtmlPipe implements PipeTransform { constructor( private sanitizer: DomSanitizer) { } transform(value: string, exponent?: string): SafeHtml { const data = value || ''; return this.sanitizer.bypassSecurityTrustHtml(data); } }
Shinerising/easyblog
src/app/post.component.ts
import { Apollo, gql } from 'apollo-angular'; import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { HttpService } from './service/http.service'; import { Title } from '@angular/platform-browser'; import { Commits, Commit } from './interface/commit.interface'; import { FileNamePipe } from './pipe/filename.pipe'; import { firstValueFrom } from 'rxjs'; import { ConfigService } from './service/config.service'; import { MarkDownService } from './service/markdown.service'; @Component({ selector: 'app-post', templateUrl: './post.component.html', styleUrls: ['./post.component.css'] }) export class PostComponent implements OnInit, OnDestroy { private subscription: Subscription; public header: string; public author: string; public updateTime: Date; public url: string; public html: string; public email: string; public avatar: string; public error: boolean; constructor( private route: ActivatedRoute, private router: Router, private http: HttpService, private title: Title, private apollo: Apollo, private markdown: MarkDownService, private config: ConfigService) { } ngOnInit(): void { this.subscription = this.route.fragment.subscribe(fragment => { if (fragment === null) { this.router.navigateByUrl(''); } else { this.header = new FileNamePipe().transform(fragment); this.title.setTitle(this.header); this.LoadCommits(fragment); this.LoadArticle(fragment); } }); } ngOnDestroy() { this.subscription.unsubscribe(); } private async LoadCommits(file: string) { const response = await firstValueFrom(this.apollo.query<Commits>({ query: gql(this.config.getCommitQuery(file)) })); const commits = response.data; const commitList = commits.repo.content.history.edges; if (commitList && commitList.length > 0) { const committer = commitList[0].commit.committer; this.author = committer.name; this.updateTime = committer.date; this.email = committer.email; this.avatar = committer.avatarUrl; this.url = this.config.getFileURL(file); this.error = false; } else { this.error = true; } } private async LoadArticle(file: string) { const data = await this.http.getMarkdown(this.config.getMarkDownURL(file)); this.html = this.markdown.render(data); } }
Shinerising/easyblog
src/app/app.component.ts
import { Component, Inject } from '@angular/core'; import { ConfigService } from './service/config.service'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public header: string; public url: string; constructor( @Inject(DOCUMENT) private document, private config: ConfigService) { this.header = config.Title; this.url = config.getRepoURL(); if (config.Theme) { const link: HTMLLinkElement = this.document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('href', `./assets/${config.Theme}.css`); this.document.head.appendChild(link); } } }
Shinerising/easyblog
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { NgModule, APP_INITIALIZER } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ListComponent } from './list.component'; import { PostComponent } from './post.component'; import { FileNamePipe } from './pipe/filename.pipe'; import { SanitizehtmlPipe } from './pipe/sanitize.pipe'; import { GraphQLModule } from './graphql.module'; import { ConfigService } from './service/config.service'; @NgModule({ imports: [ BrowserModule, HttpClientModule, AppRoutingModule, GraphQLModule ], declarations: [ AppComponent, ListComponent, PostComponent, FileNamePipe, SanitizehtmlPipe ], providers: [ ConfigService, { provide: APP_INITIALIZER, useFactory: (config: ConfigService) => () => config.loadConfig(), deps: [ConfigService], multi: true } ], bootstrap: [AppComponent] }) export class AppModule { }
Shinerising/easyblog
src/app/interface/commit.interface.ts
<filename>src/app/interface/commit.interface.ts export interface Commit { commit: { oid: string; commitUrl: string, committedDate: Date, committer: { name: string, email: string, avatarUrl: string, date: Date } }; } export interface Commits { repo: { content: { history: { edges: Array<Commit> } } }; }
Shinerising/easyblog
src/app/pipe/filename.pipe.ts
<gh_stars>1-10 import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filename' }) export class FileNamePipe implements PipeTransform { transform(value: string, exponent?: string): string { const name = value.substr(0, value.lastIndexOf('.')); if (exponent === 'img') { return name + '.jpg'; } return name; } }
Shinerising/easyblog
src/app/list.component.ts
import { Apollo, gql } from 'apollo-angular'; import { Component } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Contents, Content } from './interface/content.interface'; import { ConfigService } from './service/config.service'; import { firstValueFrom } from 'rxjs'; @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css'] }) export class ListComponent { public contentList: Array<Content>; public imageRootUri: string; constructor( private title: Title, private apollo: Apollo, private config: ConfigService) { this.title.setTitle(config.Title); this.imageRootUri = config.getRAWRoot(); this.LoadContents(); } private async LoadContents() { const entriesQuery = await firstValueFrom(this.apollo.query<Contents>({ query: gql(this.config.getContentQuery()) })); const contents: Contents = entriesQuery.data; this.contentList = contents.repo.content.entries.filter((content) => { if (content.type === 'blob') { const extension: string = content.name.substr(content.name.lastIndexOf('.')).toLowerCase(); if (extension === '.md' || extension === '.markdown') { return content; } } }); } }
Shinerising/easyblog
src/app/interface/content.interface.ts
<reponame>Shinerising/easyblog<gh_stars>1-10 export interface Contents { repo: { content: { entries: Array<Content> } }; } export interface Content { name: string; type: string; oid: string; commitedDate: Date; }
Shinerising/easyblog
src/app/service/http.service.ts
<filename>src/app/service/http.service.ts import { Injectable, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class HttpService { public constructor( private http: HttpClient) { } public async getMarkdown(url: string, options?: object): Promise<string> { return await this.get<string>(url, { responseType: 'text' }); } private async get<T>(url: string, options?: object): Promise<T> { try { return await firstValueFrom(this.http.get<T>(url, options)); } catch (error) { return await Promise.reject(error.message || error); } } }
ekoirsyad/chonky-website
landing/src/sections/Header.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import Typography from '@material-ui/core/Typography'; import Alert from '@material-ui/lab/Alert'; import React from 'react'; export interface HeaderProps {} const useStyles = makeStyles((theme: Theme) => createStyles({ header: { textAlign: 'center', marginTop: 40, }, logo: { maxWidth: 400, width: '100%', }, subtitle: { marginTop: -30, }, shields: { padding: '20px 10px', '& > *': { margin: 4, }, }, warning: { backgroundColor: '#ffcc8a', margin: 'auto', maxWidth: 700, }, }) ); export const Header: React.FC<HeaderProps> = (props) => { const classes = useStyles(); return ( <header className={classes.header}> <img className={classes.logo} alt="Chonky - A File Browser for React" src="./chonky-logo-v2.png" /> <Typography className={classes.subtitle} variant="h5"> A File Browser for React </Typography> <div className={classes.shields}> <a href="https://www.npmjs.com/package/chonky"> <img alt="NPM package" src="https://img.shields.io/npm/v/chonky.svg?style=flat&colorB=ffac5c" /> </a> <a href="https://tldrlegal.com/license/mit-license"> <img alt="MIT license" src="https://img.shields.io/npm/l/chonky?style=flat&colorB=dcd67a" /> </a> <a href="https://www.npmjs.com/package/chonky"> <img alt="NPM downloads" src="https://img.shields.io/npm/dt/chonky?style=flat&colorB=aef498" /> </a> <a href="https://github.com/TimboKZ/Chonky"> <img alt="GitHub stars" src="https://img.shields.io/github/stars/TimboKZ/Chonky?style=flat&colorB=50f4cc" /> </a> <a href="https://discord.gg/4HJaFn9"> <img alt="Chat on Discord" src="https://img.shields.io/discord/696033621986770957?label=discord&style=flat&colorB=08acee" /> </a> </div> <br /> <Alert className={classes.warning} severity="warning"> Chonky 2.x was released on November 8th, 2020. There will likely be some minor bugs in the code base. Please{' '} <a href="https://github.com/TimboKZ/Chonky/issues"> create an issue on GitHub </a>{' '} if you run into any such bugs. </Alert> </header> ); };
ekoirsyad/chonky-website
landing/src/demo/demo-component.tsx
<gh_stars>1-10 import { faSyncAlt } from '@fortawesome/free-solid-svg-icons/faSyncAlt'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import Button from '@material-ui/core/Button'; import Paper from '@material-ui/core/Paper'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import { ChonkyActions, FileBrowser, FileContextMenu, FileData, FileList, FileNavbar, FileToolbar, setChonkyDefaults, } from 'chonky'; import { ChonkyIconFA } from 'chonky-icon-fontawesome'; import React, { useCallback, useMemo } from 'react'; import { getButtonStyles } from '../components/LinkButton'; import { DemoSource2x, MostRecentStorybook } from '../util/links'; import { useCustomFileMap, useFileActionHandler, useFiles, useFolderChain, } from './demo-hooks'; setChonkyDefaults({ iconComponent: ChonkyIconFA }); export const DemoComponent: React.FC = () => { const { fileMap, currentFolderId, setCurrentFolderId, resetFileMap, deleteFiles, moveFiles, createFolder, } = useCustomFileMap(); const files = useFiles(fileMap, currentFolderId); const folderChain = useFolderChain(fileMap, currentFolderId); const handleFileAction = useFileActionHandler( setCurrentFolderId, deleteFiles, moveFiles, createFolder ); const fileActions = useMemo( () => [ChonkyActions.CreateFolder, ChonkyActions.DeleteFiles], [] ); const thumbnailGenerator = useCallback( (file: FileData) => file.thumbnailUrl ? `https://chonky.io${file.thumbnailUrl}` : null, [] ); const classes = useStyles(); return ( <> <Paper className={classes.demoWrapper} elevation={3}> <FileBrowser instanceId={'chonky-demo'} files={files} folderChain={folderChain} fileActions={fileActions} onFileAction={handleFileAction} thumbnailGenerator={thumbnailGenerator} > <FileNavbar /> <FileToolbar /> <FileList /> <FileContextMenu /> </FileBrowser> </Paper> <div className={classes.buttonContainer}> <Button size="small" className={classes.button} onClick={resetFileMap} variant="contained" startIcon={<FontAwesomeIcon icon={faSyncAlt} fixedWidth={true} />} > Reset demo </Button> <Button size="small" className={classes.button} href={DemoSource2x.url} variant="contained" startIcon={ <FontAwesomeIcon icon={DemoSource2x.icon} fixedWidth={true} /> } > View source code </Button> <Button size="small" className={classes.button} href={MostRecentStorybook.url} variant="contained" startIcon={ <FontAwesomeIcon icon={MostRecentStorybook.icon} fixedWidth={true} /> } > View storybook </Button> </div> </> ); }; const useStyles = makeStyles((theme: Theme) => createStyles({ demoWrapper: { position: 'relative', height: 600, }, buttonContainer: { textAlign: 'center', padding: 10, }, button: { textTransform: 'none', fontWeight: 'bold', margin: '10px', ...getButtonStyles(theme, '#654295'), }, }) );
ekoirsyad/chonky-website
landing/src/sections/Docs.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import Grid from '@material-ui/core/Grid'; import React from 'react'; import { LinkCard } from '../components/LinkCard'; import { Title } from '../components/Title'; import { Docs0x, Docs1x, Docs2x, Storybook2x } from '../util/links'; export interface DocsProps {} export const Docs: React.FC<DocsProps> = (props) => { return ( <> <Title>Read the docs</Title> <Grid container spacing={2}> <Grid item md={4} sm={6} xs={12}> <LinkCard linkData={Docs2x} /> </Grid> <Grid item md={4} sm={6} xs={12}> <LinkCard linkData={Storybook2x} /> </Grid> <Grid item md={4} sm={6} xs={12}> <LinkCard linkData={Docs1x} /> </Grid> <Grid item md={4} sm={6} xs={12}> <LinkCard linkData={Docs0x} /> </Grid> </Grid> <br/> <br/> <br/> </> ); };
ekoirsyad/chonky-website
landing/src/components/LinkButton.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import Button from '@material-ui/core/Button'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import { CSSProperties } from '@material-ui/core/styles/withStyles'; import React from 'react'; import { LinkData } from '../util/links'; export interface LinkButtonProps { linkData: LinkData; } export const getButtonStyles = (theme: Theme, color: string): CSSProperties => ({ color: theme.palette.getContrastText(color), backgroundColor: color, '&:hover': { backgroundColor: color, }, }); const useStyles = makeStyles((theme: Theme) => createStyles({ button: (linkData: LinkData) => ({ textTransform: 'none', fontWeight: 'bold', margin: 5, ...getButtonStyles(theme, linkData.color), }), }) ); export const LinkButton: React.FC<LinkButtonProps> = ({ linkData }) => { const classes = useStyles(linkData); return ( <Button className={classes.button} href={linkData.url} variant="contained" startIcon={<FontAwesomeIcon icon={linkData.icon} fixedWidth={true} />} > {linkData.title} </Button> ); };
ekoirsyad/chonky-website
landing/src/demo/demo-util.tsx
<gh_stars>1-10 import { ChonkyActions, ChonkyFileActionData } from 'chonky'; import Noty from 'noty'; import 'noty/lib/noty.css'; import 'noty/lib/themes/relax.css'; import './demo-styles.css'; // We ignore some actions to avoid creating noise const ignoredActions = new Set<String>(); ignoredActions.add(ChonkyActions.MouseClickFile.id); ignoredActions.add(ChonkyActions.KeyboardClickFile.id); ignoredActions.add(ChonkyActions.StartDragNDrop.id); ignoredActions.add(ChonkyActions.EndDragNDrop.id); ignoredActions.add(ChonkyActions.ChangeSelection.id); export const showActionNotification = (data: ChonkyFileActionData) => { if (ignoredActions.has(data.action.id)) return; const textParts: string[] = []; textParts.push( `<div class="noty-action">Action: <code>${data.action.id}</code></div>` ); if (data.id === ChonkyActions.OpenFiles.id) { const fileNames = data.payload.files.map((f) => `<code>${f.name}</code>`); if (fileNames.length === 1) { textParts.push('You opened a single file:'); } else { textParts.push(`You opened ${fileNames.length} files:`); } textParts.push(...fileNames); } if (data.id === ChonkyActions.MoveFiles.id) { const fileCount = data.payload.files.length; const countString = `${fileCount} file${fileCount !== 1 ? 's' : ''}`; const source = `<code>${data.payload.source?.name ?? '~'}</code>`; const destination = `<code>${data.payload.destination.name}</code>`; textParts.push(`You moved ${countString} from ${source} to ${destination}.`); } if (data.id === ChonkyActions.DeleteFiles.id) { const fileCount = data.state.selectedFilesForAction.length; const countString = `${fileCount} file${fileCount !== 1 ? 's' : ''}`; textParts.push(`You deleted ${countString} files.`); } const text = textParts[0] + textParts.slice(1).join('<br/>'); new Noty({ text, type: 'success', theme: 'relax', timeout: 3000, }).show(); };
ekoirsyad/chonky-website
landing/src/sections/Features.tsx
<reponame>ekoirsyad/chonky-website<gh_stars>1-10 /** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import Avatar from '@material-ui/core/Avatar'; import Box from '@material-ui/core/Box'; import ListItem from '@material-ui/core/ListItem'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItemText from '@material-ui/core/ListItemText'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import Typography from '@material-ui/core/Typography'; import AllInclusiveIcon from '@material-ui/icons/AllInclusive'; import CodeIcon from '@material-ui/icons/Code'; import ControlCameraIcon from '@material-ui/icons/ControlCamera'; import DirectionsRunIcon from '@material-ui/icons/DirectionsRun'; import KeyboardIcon from '@material-ui/icons/Keyboard'; import MenuOpenIcon from '@material-ui/icons/MenuOpen'; import PhoneAndroidIcon from '@material-ui/icons/PhoneAndroid'; import PhotoFilterIcon from '@material-ui/icons/PhotoFilter'; import PhotoSizeSelectSmallIcon from '@material-ui/icons/PhotoSizeSelectSmall'; import PowerIcon from '@material-ui/icons/Power'; import SortByAlphaIcon from '@material-ui/icons/SortByAlpha'; import ViewComfyIcon from '@material-ui/icons/ViewComfy'; import React from 'react'; import { Title } from '../components/Title'; export interface LinksProps {} export const Features: React.FC<LinksProps> = (props) => { const classes = useStyles(); return ( <> <Title>Features...</Title> <Box className={classes.featuresWrapper}> <Typography variant="h6" className={classes.listTitle}> ...for developers: </Typography> <div className={classes.featureList}> {developerFeatures.map((feature, index) => ( <ListItem component={'div'} key={`feature-${index}`} className={classes.developerFeature} > <ListItemAvatar className={classes.developerAvatar}> <Avatar className={classes.developerIcon}> {feature.icon} </Avatar> </ListItemAvatar> <ListItemText primary={feature.title} secondary={feature.description} className={classes.developerFeatureText} /> </ListItem> ))} </div> </Box> <br /> <Box className={classes.featuresWrapper}> <Typography variant="h6" className={classes.listTitle}> ...for users: </Typography> <div className={classes.featureList}> {userFeatures.map((feature, index) => ( <ListItem component={'div'} key={`feature-${index}`} className={classes.userFeature} > <ListItemAvatar className={classes.userAvatar}> <Avatar className={classes.userIcon}> {feature.icon} </Avatar> </ListItemAvatar> <ListItemText primary={feature.title} secondary={feature.description} className={classes.userFeatureText} /> </ListItem> ))} </div> </Box> </> ); }; const useStyles = makeStyles((theme: Theme) => createStyles({ featuresWrapper: {}, listTitle: { textAlign: 'center', }, featureList: { justifyContent: 'center', flexBasis: '100%', flexWrap: 'wrap', display: 'flex', }, developerFeature: { boxShadow: '0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px' + ' rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12)', backgroundColor: 'white', flexDirection: 'column', padding: '20px 10px', textAlign: 'center', borderRadius: 6, margin: '8px', width: 280, }, userFeature: { boxShadow: '0px 3px 1px -2px rgba(0,0,0,0.2), 0px 2px 2px 0px' + ' rgba(0,0,0,0.14), 0px 1px 5px 0px rgba(0,0,0,0.12)', backgroundColor: 'white', alignItems: 'center', borderRadius: 6, padding: '15px', margin: '8px', width: 280, }, developerFeatureText: { '& > span': { fontWeight: 'bold', fontSize: '1.3em', margin: '10px', }, '& > p': { fontSize: '1em', }, }, userFeatureText: {}, developerAvatar: { minWidth: 'auto', }, userAvatar: {}, developerIcon: { '& > *': { fontSize: '2.4em', }, backgroundColor: '#4834d4', height: 75, width: 75, }, userIcon: { backgroundColor: '#6ab04c', }, }) ); interface FeatureData { icon: any; title: string; description: string; only2x?: boolean; } const developerFeatures: FeatureData[] = [ { icon: <PowerIcon />, title: 'Custom file actions', description: 'Chonky offers a powerful file action framework. File browser ' + 'behaviour can be tweaked significantly without forking the library.', }, { icon: <AllInclusiveIcon />, title: 'Backend agnostic', description: 'Chonky focuses only on file browser UI. It does not make any' + ' assumptions about your server backend (or lack thereof).', }, { icon: <CodeIcon />, title: 'TypeScript support', description: 'Chonky is written in TypeScript. It exports many types and ' + 'generic interfaces that can help you write type safe code.', }, ]; const userFeatures: FeatureData[] = [ { icon: <ViewComfyIcon />, title: 'List & Grid view', description: '' }, { icon: <PhotoFilterIcon />, title: 'Thumbnails & file icons', description: '' }, { icon: <SortByAlphaIcon />, title: 'Search, sorting & filtering', description: '', }, { icon: <MenuOpenIcon />, title: 'Toolbar & context menus', description: '' }, { icon: <KeyboardIcon />, title: 'Keyboard shortcuts', description: '' }, { icon: <ControlCameraIcon />, title: 'Drag and drop', description: '' }, { icon: <PhotoSizeSelectSmallIcon />, title: 'File selections', description: '' }, { icon: <DirectionsRunIcon />, title: 'Virtualization', description: '' }, { icon: <PhoneAndroidIcon />, title: 'Mobile friendly UI', description: '' }, ];
ekoirsyad/chonky-website
landing/src/sections/Demo.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import React from 'react'; import { Title } from '../components/Title'; import { DemoComponent } from '../demo/demo-component'; export interface DemoProps {} export const Demo: React.FC<DemoProps> = (props) => { return ( <> <Title>Try it out</Title> <DemoComponent /> </> ); };
ekoirsyad/chonky-website
landing/src/components/Title.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import Typography from '@material-ui/core/Typography'; import React from 'react'; export interface TitleProps {} const useStyles = makeStyles((theme: Theme) => createStyles({ title: { position: 'relative', textAlign: 'center', marginBottom: 20, marginTop: 60, }, text: { backgroundColor: '#f2f2f2', padding: '0 20px', }, line: { backgroundColor: '#ccc', position: 'absolute', width: '100%', zIndex: -1, top: '50%', height: 2, }, }) ); export const Title: React.FC<TitleProps> = (props) => { const classes = useStyles(); return ( <Typography className={classes.title} variant="h4"> <div className={classes.line} /> <span className={classes.text}>{props.children}</span> </Typography> ); };
ekoirsyad/chonky-website
landing/src/sections/Links.tsx
<filename>landing/src/sections/Links.tsx /** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import Box from '@material-ui/core/Box'; import { Theme } from '@material-ui/core/styles/createMuiTheme'; import createStyles from '@material-ui/core/styles/createStyles'; import makeStyles from '@material-ui/core/styles/makeStyles'; import React from 'react'; import { LinkButton } from '../components/LinkButton'; import { Title } from '../components/Title'; import { DiscordLink, GitHubLink, MostRecentDocs, MostRecentStorybook, NpmLink, } from '../util/links'; export interface LinksProps {} const useStyles = makeStyles((theme: Theme) => createStyles({ buttonWrapper: { textAlign: 'center', margin: 'auto', maxWidth: 700, }, }) ); export const Links: React.FC<LinksProps> = (props) => { const classes = useStyles(); return ( <> <Title>Quick links</Title> <Box className={classes.buttonWrapper}> <LinkButton linkData={GitHubLink} /> <LinkButton linkData={NpmLink} /> <LinkButton linkData={DiscordLink} /> <LinkButton linkData={MostRecentDocs} /> <LinkButton linkData={MostRecentStorybook} /> </Box> </> ); };
ekoirsyad/chonky-website
landing/src/App.tsx
/** * @author <NAME> <<EMAIL>> * @copyright 2020 * @license MIT */ import Container from '@material-ui/core/Container'; import React from 'react'; import { Demo } from './sections/Demo'; import { Docs } from './sections/Docs'; import { Features } from './sections/Features'; import { Header } from './sections/Header'; import { Links } from './sections/Links'; export const App: React.FC = () => { return ( <Container maxWidth="md"> <Header /> <Links /> <Features /> <Demo /> <Docs /> </Container> ); };
mkloubert/vs-cron
src/workspace.ts
/// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as Path from 'path'; import * as vscode from 'vscode'; let currentFolder: vscode.WorkspaceFolder | false = false; /** * Returns the root path of the selected workspace folder. * * @return {string} The root path. */ export function getRootPath() { let folder: vscode.WorkspaceFolder; if (false === currentFolder) { if (vscode.workspace.workspaceFolders) { if (vscode.workspace.workspaceFolders.length > 0) { folder = vscode.workspace.workspaceFolders[0]; } } } else { folder = currentFolder; } let workspace_root: string; if (folder) { workspace_root = vscode.workspace.getWorkspaceFolder(folder.uri) .uri .fsPath; } else { try { workspace_root = vscode.workspace.rootPath; } catch (e) { //TODO: log workspace_root = undefined; } } if ('undefined' !== typeof workspace_root) { return Path.resolve(workspace_root); } } /** * Resets the selected workspace folder. */ export function resetSelectedWorkspaceFolder() { currentFolder = false; }
mkloubert/vs-cron
src/contracts.ts
<gh_stars>1-10 /// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as Moment from 'moment'; import * as vscode from 'vscode'; /** * An item that uses JavaScript code if it is available or not. */ export interface ConditionalItem { /** * One or more (JavaScript) conditions that check if that item is available or not. */ if?: string | string[]; } /** * App settings */ export interface Configuration { /** * Disable popups that report for a new (installed) version or not. */ disableNewVersionPopups?: boolean; /** * Data that is available everywhere, in scripts e.g. */ globals?: any; /** * One or more job to configure. */ jobs?: Job | Job[]; /** * The default timezone to use. */ timeZone?: string; } /** * A document. */ export interface Document { /** * The body / content of the document. */ body: Buffer; /** * The encoding. */ encoding?: string; /** * The ID. */ id?: any; /** * The MIME type. */ mime?: string; /** * The title. */ title?: string; } /** * Settings for a job. */ export interface Job extends ConditionalItem, MachineItem, PlatformItem { /** * [ONLY FOR INTERNAL USE] * * Detail information for the GUI. */ __detail?: string; /** * The command / action to invoke. */ action?: string | JobAction; /** * Directly run on startup or not. */ autoStart?: boolean; /** * A description for the job. */ description?: string; /** * Format. */ format?: string; /** * The maximum number of executions. */ maximum?: number; /** * The minimum number of ticks before the job does its first action. */ minimum?: number; /** * The (display) name of the job. */ name?: string; /** * Indicates if this job can run parallel to another or not. */ runParallel?: boolean; /** * The start delay in milliseconds. */ startDelay?: number; /** * The time value that is used to configure the job. */ time?: string; /** * The custom timezone to use. */ timeZone?: string; /** * Defines the minumum time the job can be executed. */ validFrom?: string; /** * Defines the maximum time the job can be executed. */ validUntil?: string; } /** * A job action. */ export interface JobAction { /** * Type of the action. */ type?: string; } /** * A job action for running a command. */ export interface JobCommandAction extends JobAction { /** * The optional arguments for the execution. */ arguments?: any[]; /** * The ID of the command to execute. */ command: string; } /** * Information about a job. */ export interface JobInfo { /** * Gets the description of the underlying job. */ readonly description: string; /** * Gets the details for the underlying job. */ readonly detail: string; /** * Gets if the job is currently running or not. */ readonly isRunning: boolean; /** * Gets the timestamp of the last execution in ISO format. */ readonly lastExecution: string; /** * Gets the name of the job. */ readonly name: string; } /** * Job name(s). */ export type JobNames = string | string[]; /** * A job scheduler. */ export interface JobScheduler extends vscode.Disposable { /** * Gets the description of the underlying job. */ readonly description: string; /** * Gets the details for the underlying job. */ readonly detail: string; /** * Gets if the scheduler is running or not. */ readonly isRunning: boolean; /** * Gets the timestamp of the last execution. */ readonly lastExecution: Moment.Moment; /** * Gets the name of the underlying job. */ readonly name: string; /** * Starts the scheduler. * * @returns {Thenable<boolean>} The promise. */ readonly start: () => Thenable<boolean>; /** * Stops the scheduler. * * @returns {Thenable<boolean>} The promise. */ readonly stop: () => Thenable<boolean>; } /** * A job action for running a script. */ export interface JobScriptAction extends JobAction { /** * Store script (module) in cache or not. */ cached?: boolean; /** * Optional data for the execution. */ options?: any; /** * The path to the script to execute. */ script: string; /** * The initial state value for the script. */ state?: any; } /** * A script module of a job. */ export interface JobScriptModule extends ScriptModule { /** * The action for a job tick. */ tick: JobScriptModuleExecutor; } /** * Describes a function that is executed on a job tick. * * @param {JobScriptModuleExecutorArguments} args The arguments for the execution. * * @returns {JobScriptModuleExecutorResult} The result. */ export type JobScriptModuleExecutor = (args: JobScriptModuleExecutorArguments) => JobScriptModuleExecutorResult; /** * The result of a job tick. */ export type JobScriptModuleExecutorResult = Thenable<number> | number | void; /** * The arguments for a job tick. */ export interface JobScriptModuleExecutorArguments extends ScriptArguments { /** * Activates the job. * * @param {number} [delay] The delay in milliseconds. * * @chainable */ readonly activate: (delay?: number) => ScriptArguments; /** * Gets the extension's Memento for accessing app wide data. */ readonly appState: vscode.Memento; /** * Gets or sets the value that indicates to cache the underlying script or not. */ cached: boolean; /** * Gets or sets the counter that indicates how often the job has been executed. */ counter: number; /** * Deactivates the job. * * @param {number} [delay] The delay in milliseconds. * * @chainable */ readonly deactivate: (delay?: number) => ScriptArguments; /** * Gets or sets the description for the underlying job. */ description: string; /** * Gets or sets the detail information for the GUI. */ detail: string; /** * Deploys one or more file to a list of targets. * * This requires 'extension.deploy.filesTo' command as available in extensions like 'vs-deploy' * s. https://github.com/mkloubert/vs-deploy * * @param {string|string[]} files One or more file to deploy. * @param {string|string[]} targets One or more target (name) to deploy to. * * @returns {Promise<any>} The promise. */ readonly deploy: (files: string | string[], targets: string | string[]) => Promise<any>; /** * Gets if the underlying job is active or not. */ readonly isActive: boolean; /** * Gets if the underlying job is currently running or not. */ readonly isRunning: boolean; /** * Gets the timestamp of the previous execution. */ readonly lastExecution: Moment.Moment; /** * Gets or sets the maximum value that indicates how often the job can be executed. */ maximum: number; /** * Gets or sets the minumum value that how many ticks have to been made before the job can be executed. */ minimum: number; /** * Gets or sets the name of the underlying job. */ name: string; /** * The package file with the information about this extension. */ readonly packageFile: PackageFile; /** * Gets the value from the previous execution. */ readonly previousValue: any; /** * Gets or sets the value for the next execution. */ nextValue: any; /** * Gets or sets the value that indicates if this job can ran parallel to another or not. */ runParallel: boolean; /** * Gets the script that is currently executed or sets it for the next execution. */ script: string; /** * Starts the underlying job. * * @param {number} [delay] The delay in milliseconds. * * @return {Thenable<boolean>} The promise. */ readonly start: (delay?: number) => Thenable<boolean>; /** * Stops the underlying job. * * @param {number} [delay] The delay in milliseconds. * * @return {Thenable<boolean>} The promise. */ readonly stop: (delay?: number) => Thenable<boolean>; /** * Gets the array to which disposables can be added for this extension. */ readonly subscriptions: { dispose(): any }[]; /** * Gets or sets the current timezone. */ timeZone: string; /** * Gets or sets the value that indicates the minimum time the job can be executed. */ validFrom: Moment.MomentInput; /** * Gets or sets the value that indicates the maximum time the job can be executed. */ validUntil: Moment.MomentInput; /** * Gets the extension's Memento for accessing workspace wide data. */ readonly workspaceState: vscode.Memento; } /** * An item for a specific machine. */ export interface MachineItem { /** * A list of one or more (host)names that item is (visible) for. */ isFor?: string | string[]; } /** * Describes the structure of the package file of that extenstion. */ export interface PackageFile { /** * The display name. */ displayName: string; /** * The (internal) name. */ name: string; /** * The version string. */ version: string; } /** * An item / object that can be filtered by platform. */ export interface PlatformItem { /** * One or more platform the item is for. */ platforms?: string | string[]; } /** * Describes a button of a popup. */ export interface PopupButton extends vscode.MessageItem { /** * Gets the action of that button. */ action?: PopupButtonAction; /** * Contains an additional object that should be linked with that instance. */ tag?: any; } /** * A popup button action. */ export type PopupButtonAction = () => void; /** * Script arguments. */ export interface ScriptArguments { /** * Emits an event. * * @param {string} event The event to emit. * @param {any[]} [args] Additional arguments for the event. * * @returns {boolean} Event was emitted or not. */ readonly emit: (event: string | Symbol, ...args: any[]) => boolean; /** * The global data from the settings. */ readonly globals: any; /** * Gets an object that stores data for all scripts. */ readonly globalState: Object; /** * Logs a message. * * @param {any} msg The message to log. * * @chainable */ readonly log: (msg: any) => ScriptArguments; /** * Registers for an event. * * @param {string|Symbol} event The event to register for. * @param {Function} listener The event listener. * * @chainable */ readonly on: (event: string | Symbol, listener: Function) => ScriptArguments; /** * Registers for an one-time event. * * @param {string|Symbol} event The event to register for. * @param {Function} listener The event listener. * * @chainable */ readonly once: (event: string | Symbol, listener: Function) => ScriptArguments; /** * Opens a HTML document in a new tab. * * @param {string} html The HTML document (source code). * @param {string} [title] The custom title for the tab. * @param {any} [id] The custom ID for the document in the storage. * * @returns {Thenable<any>} The promise. */ readonly openHtml: (html: string, title?: string, id?: any) => Thenable<any>; /** * Additional / optional data for the execution. */ readonly options: any; /** * Gets the output channel the script can use. */ readonly outputChannel: vscode.OutputChannel; /** * Registers for an one-time event. * * @param {string|Symbol} event The event to register for. * @param {Function} listener The event listener. * * @chainable */ readonly removeListener: (event: string | Symbol, listener: Function) => ScriptArguments; /** * Loads a module from the script context. * * @param {string} id The ID of the module. * * @returns any The loaded module. */ readonly require: (id: string) => any; /** * Gets or sets a value for the script that is available while the current session. */ state: any; } /** * A script module. */ export interface ScriptModule { }
mkloubert/vs-cron
src/objects.ts
<filename>src/objects.ts /// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as cj_contracts from './contracts'; import * as cj_controller from './controller'; import * as cj_helpers from './helpers'; const cron = require('cron'); import * as events from 'events'; import * as Moment from 'moment'; const momentTimeZone = require('moment-timezone'); import * as vscode from 'vscode'; /** * Name of the event that indicates if a job has been started. */ export const EVENT_JOB_STARTED = 'job.started'; /** * Name of the event that indicates if a job has been stopped. */ export const EVENT_JOB_STOPPED = 'job.stopped'; /** * A job based on config settins. */ export class ConfigJob extends events.EventEmitter implements cj_contracts.JobScheduler { /** * Stores the underlying config entry. */ protected readonly _CONFIG: cj_contracts.Job; /** * Stores the underlying controller. */ protected readonly _CONTROLLER: cj_controller.Controller; /** * Stores the timestamp of the last execution. */ protected _lastExecution: Moment.Moment; /** * Stores the current job scheduler. */ protected _scheduler: any; /** * Initializes a new instance of that class. * * @param {cj_contracts.Job} config The config entry. * @param {cj_controller.Controller} controller The underlying controller. */ constructor(config: cj_contracts.Job, controller: cj_controller.Controller) { super(); this._CONFIG = config; this._CONTROLLER = controller; } /** * Gets the underlying config entry. */ public get config(): cj_contracts.Job { return this._CONFIG; } /** * Gets the underlying controller. */ public get controller(): cj_controller.Controller { return this._CONTROLLER; } /** @inheritdoc */ public get description(): string { return this.config.description; } /** @inheritdoc */ public get detail(): string { return this.config.__detail; } /** @inheritdoc */ public dispose() { this.stopSync(); this.removeAllListeners(); } /** * Gets if the job is currently running or not. */ public get isRunning(): boolean { let s = this._scheduler; return cj_helpers.toBooleanSafe(s && s.running); } /** * Gets the timestamp of the last execution. */ public get lastExecution(): Moment.Moment { return this._lastExecution; } /** @inheritdoc */ public get name(): string { return this.config.name; } /** * Starts the job. * * @return {Thenable<boolean>} The promise. */ public start(): Thenable<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { completed(null, me.startSync()); } catch (e) { completed(e); } }); } /** * Starts the job. * * @returns {boolean} Job has been started or not. */ protected startSync(): boolean { let me = this; let started: boolean; let s = me._scheduler; if (cj_helpers.toBooleanSafe(s && s.running)) { started = false; // already running } else { let newScheduler: any; let isActive = true; let stopScheduler = () => { isActive = false; me.stop().then(() => { }, (err) => { me.controller.log(`[ERROR] objects.ConfigJob.startSync().stopScheduler(): ${cj_helpers.toStringSafe(err)}`); }); }; let onStartingActions: Function[] = []; let cfg = me.config; let jobAction = cfg.action; if (!jobAction) { jobAction = { type: "command", }; } if ('object' !== typeof jobAction) { let commandAction: cj_contracts.JobCommandAction = { command: cj_helpers.toStringSafe(cfg.action), type: "command", }; jobAction = commandAction; } let format = cj_helpers.normalizeString(cfg.format); let cronTime: string | Date; switch (format) { case '': case 'crontab': cronTime = cj_helpers.toStringSafe(cfg.time); if (cj_helpers.isEmptyString(cronTime)) { cronTime = '* * * * *'; } break; case 'date': cronTime = Moment(cfg.time).toDate(); break; } // timezone let timeZone = cj_helpers.toStringSafe(me.controller.config.timeZone).trim(); let customTimeZone = cj_helpers.toStringSafe(cfg.timeZone).trim(); if (!cj_helpers.isEmptyString(customTimeZone)) { timeZone = customTimeZone; // use custom timezone for job } if (cj_helpers.isEmptyString(timeZone)) { timeZone = undefined; } let validFrom: Moment.Moment; if (!cj_helpers.isEmptyString(cfg.validFrom)) { let vf = cj_helpers.toStringSafe(cfg.validFrom); if (timeZone) { validFrom = momentTimeZone.tz(vf, timeZone); } else { validFrom = Moment(vf); } } let validUntil: Moment.Moment; if (!cj_helpers.isEmptyString(cfg.validUntil)) { let vu = cj_helpers.toStringSafe(cfg.validUntil); if (timeZone) { validUntil = momentTimeZone.tz(vu, timeZone); } else { validUntil = Moment(vu); } } let runParallel = cj_helpers.toBooleanSafe(cfg.runParallel); let isExecuting = false; let action: () => void; switch (cj_helpers.normalizeString(jobAction.type)) { case '': case 'command': { let jca = <cj_contracts.JobCommandAction>jobAction; action = () => { try { isExecuting = true; let cmdArgs = [ cj_helpers.toStringSafe(jca.command) ]; if (jca.arguments) { cmdArgs = cmdArgs.concat( jca.arguments ); } vscode.commands.executeCommand.apply(null, cmdArgs).then(() => { isExecuting = false; }, (err) => { isExecuting = false; me.controller .log(`[ERROR] objects.ConfigJob.startSync().command.action(): ${cj_helpers.toStringSafe(err)}`); }); } catch (e) { isExecuting = false; throw e; } }; } break; case 'script': { let jsa = <cj_contracts.JobScriptAction>jobAction; let doCacheScript = cj_helpers.toBooleanSafe(jsa.cached); let prevValue: any; let scriptState = jsa.state; let scriptToExecute = jsa.script; action = () => { try { isExecuting = true; let tickerCompleted = (err: any, exitCode?: number, nextVal?: any) => { try { if (err) { me.controller .log(`[ERROR] objects.ConfigJob.startSync().script.action(): ${cj_helpers.toStringSafe(err)}`); } else { if (cj_helpers.isNullOrUndefined(exitCode)) { exitCode = 0; } exitCode = parseInt(cj_helpers.toStringSafe(exitCode).trim()); } } finally { prevValue = nextVal; isExecuting = false; } }; let scriptModule: cj_contracts.JobScriptModule; if (!cj_helpers.isEmptyString(scriptToExecute)) { scriptModule = cj_helpers.loadModuleSync<cj_contracts.JobScriptModule>(scriptToExecute, doCacheScript); } if (scriptModule) { let ticker = scriptModule.tick; if (ticker) { let tickerArgs: cj_contracts.JobScriptModuleExecutorArguments = { activate: function(delay?) { delay = parseInt(cj_helpers.toStringSafe(delay).trim()); if (isNaN(delay)) { isActive = true; } else { setTimeout(() => { isActive = true; }, delay); } return this; }, appState: undefined, cached: undefined, counter: undefined, deactivate: function(delay?) { delay = parseInt(cj_helpers.toStringSafe(delay).trim()); if (isNaN(delay)) { isActive = false; } else { setTimeout(() => { isActive = false; }, delay); } return this; }, description: undefined, detail: undefined, deploy: (files, targets) => { // files files = cj_helpers.asArray(files) .map(x => cj_helpers.toStringSafe(x)) .filter(x => !cj_helpers.isEmptyString(x)); files = cj_helpers.distinctArray(files); // targets targets = cj_helpers.asArray(targets) .map(x => cj_helpers.normalizeString(x)) .filter(x => x); targets = cj_helpers.distinctArray(targets); return new Promise<any>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { vscode.commands.executeCommand('extension.deploy.filesTo', files, targets).then((result) => { completed(null, result); }, (err) => { completed(err); }); } catch (e) { completed(e); } }); }, emit: function() { return me.emit .apply(me, arguments); }, globals: me.controller.getGlobals(), globalState: undefined, isActive: undefined, isRunning: undefined, lastExecution: undefined, log: function(msg) { me.controller.log(msg); return this; }, maximum: undefined, minimum: undefined, name: undefined, nextValue: undefined, on: function() { me.on.apply(me, arguments); return this; }, once: function() { me.once.apply(me, arguments); return this; }, openHtml: (html, title, docId) => { return cj_helpers.openHtmlDocument(me.controller.htmlDocuments, html, title, docId); }, options: jsa.options, outputChannel: undefined, packageFile: cj_helpers.cloneObject(me.controller.packageFile), previousValue: undefined, removeListener: function() { me.removeListener.apply(me, arguments); return this; }, require: function(id) { return cj_helpers.requireModule(id); }, runParallel: undefined, script: undefined, start: function(delay?) { delay = parseInt(cj_helpers.toStringSafe(delay).trim()); return new Promise<boolean>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); let startJob = () => { me.start().then((hasStarted) => { completed(null, hasStarted); }, (err) => { completed(err); }); }; if (isNaN(delay)) { startJob(); } else { setTimeout(() => { startJob(); }, delay); } }); }, stop: function(delay?) { delay = parseInt(cj_helpers.toStringSafe(delay).trim()); return new Promise<boolean>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); let stopJob = () => { let oldIsActive = isActive; isActive = false; me.stop().then((hasStopped) => { completed(null, hasStopped); }, (err) => { isActive = oldIsActive; // restore 'isActive' completed(err); }); }; if (isNaN(delay)) { stopJob(); } else { setTimeout(() => { stopJob(); }, delay); } }); }, state: undefined, subscriptions: undefined, timeZone: undefined, validFrom: undefined, validUntil: undefined, workspaceState: undefined, }; // tickerArgs.appState Object.defineProperty(tickerArgs, 'appState', { enumerable: true, get: () => { return me.controller.context.globalState; } }); // tickerArgs.cached Object.defineProperty(tickerArgs, 'cached', { enumerable: true, get: () => { return doCacheScript; }, set: (newValue) => { doCacheScript = cj_helpers.toBooleanSafe(newValue); } }); // tickerArgs.counter Object.defineProperty(tickerArgs, 'counter', { enumerable: true, get: () => { return counter; }, set: (newValue) => { counter = parseInt(cj_helpers.toStringSafe(newValue).trim()); } }); // tickerArgs.description Object.defineProperty(tickerArgs, 'description', { enumerable: true, get: () => { return me.config.description; }, set: (newValue) => { me.config.description = cj_helpers.toStringSafe(newValue); } }); // tickerArgs.detail Object.defineProperty(tickerArgs, 'detail', { enumerable: true, get: () => { return me.config.__detail; }, set: (newValue) => { me.config.__detail = cj_helpers.toStringSafe(newValue); } }); // tickerArgs.globalState Object.defineProperty(tickerArgs, 'globalState', { enumerable: true, get: () => { return me.controller.globalScriptStates; } }); // tickerArgs.isActive Object.defineProperty(tickerArgs, 'isActive', { enumerable: true, get: () => { return isActive; } }); // tickerArgs.isRunning Object.defineProperty(tickerArgs, 'isRunning', { enumerable: true, get: () => { return me.isRunning; } }); // tickerArgs.lastExecution Object.defineProperty(tickerArgs, 'lastExecution', { enumerable: true, get: () => { return me.lastExecution; } }); // tickerArgs.maximum Object.defineProperty(tickerArgs, 'maximum', { enumerable: true, get: () => { return maximum; }, set: (newValue) => { maximum = parseInt(cj_helpers.toStringSafe(newValue).trim()); } }); // tickerArgs.minimum Object.defineProperty(tickerArgs, 'minimum', { enumerable: true, get: () => { return minimum; }, set: (newValue) => { minimum = parseInt(cj_helpers.toStringSafe(newValue).trim()); } }); // tickerArgs.name Object.defineProperty(tickerArgs, 'name', { enumerable: true, get: () => { return me.config.name; }, set: (newValue) => { me.config.name = cj_helpers.toStringSafe(newValue); } }); // tickerArgs.outputChannel Object.defineProperty(tickerArgs, 'outputChannel', { enumerable: true, get: () => { return me.controller.outputChannel; } }); // tickerArgs.previousValue Object.defineProperty(tickerArgs, 'previousValue', { enumerable: true, get: () => { return prevValue; } }); // tickerArgs.runParallel Object.defineProperty(tickerArgs, 'runParallel', { enumerable: true, get: () => { return runParallel; }, set: (newValue) => { runParallel = cj_helpers.toBooleanSafe(newValue); } }); // tickerArgs.script Object.defineProperty(tickerArgs, 'script', { enumerable: true, get: () => { return scriptToExecute; }, set: (newValue) => { scriptToExecute = cj_helpers.toStringSafe(newValue); } }); // tickerArgs.state Object.defineProperty(tickerArgs, 'state', { enumerable: true, get: () => { return scriptState; }, set: (newValue) => { scriptState = newValue; } }); // tickerArgs.subscriptions Object.defineProperty(tickerArgs, 'subscriptions', { enumerable: true, get: () => { return me.controller.context.subscriptions; } }); // tickerArgs.timeZone Object.defineProperty(tickerArgs, 'timeZone', { enumerable: true, get: () => { return timeZone; }, set: (newValue) => { newValue = cj_helpers.toStringSafe(newValue); if (!newValue) { newValue = undefined; } timeZone = newValue; } }); // tickerArgs.validFrom Object.defineProperty(tickerArgs, 'validFrom', { enumerable: true, get: () => { return validFrom; }, set: (newValue) => { let nvf: Moment.Moment = newValue; if (nvf) { if (!Moment.isMoment(nvf)) { nvf = Moment(newValue); } } validFrom = nvf; } }); // tickerArgs.validUntil Object.defineProperty(tickerArgs, 'validUntil', { enumerable: true, get: () => { return validUntil; }, set: (newValue) => { let nvu: Moment.Moment = newValue; if (nvu) { if (!Moment.isMoment(nvu)) { nvu = Moment(newValue); } } validUntil = nvu; } }); // tickerArgs.workspaceState Object.defineProperty(tickerArgs, 'workspaceState', { enumerable: true, get: () => { return me.controller.context.workspaceState; } }); try { let tickerResult = ticker(tickerArgs); if (tickerResult) { if ('object' === typeof tickerResult) { tickerResult.then((ec) => { tickerCompleted(null, ec, tickerArgs.nextValue); }, (err) => { tickerCompleted(err, undefined, tickerArgs.nextValue); }); } else { tickerCompleted(null, tickerResult, tickerArgs.nextValue); } } else { tickerCompleted(null, 0, tickerArgs.nextValue); } } catch (e) { tickerCompleted(e, undefined, tickerArgs.nextValue); } } else { // no function tickerCompleted(null); } } else { // no module tickerCompleted(null); } } catch (e) { isExecuting = false; throw e; } }; } break; default: // unknown action = () => { try { isExecuting = true; } finally { isExecuting = false; } }; break; } // start delay let isOnDelay = false; onStartingActions.push(() => { let startDelay = parseInt(cj_helpers.toStringSafe(cfg.startDelay)); if (!isNaN(startDelay)) { isOnDelay = true; setTimeout(() => { isOnDelay = false; }, startDelay); } }); let isValid = (): boolean => { let now = Moment(); if (validFrom && validFrom.isValid()) { if (now.isBefore(validFrom)) { return false; // not valid yet } } if (validUntil && validUntil.isValid()) { if (now.isAfter(validUntil)) { // stop it to save resources stopScheduler(); return false; // not valid anymore } } return true; }; let maximum = parseInt(cj_helpers.toStringSafe(cfg.maximum).trim()); let minimum = parseInt(cj_helpers.toStringSafe(cfg.minimum).trim()); let counter = 0; newScheduler = new cron.CronJob({ cronTime: cronTime, onTick: () => { try { if (isOnDelay) { return; // start delay } if (!isActive) { return; // no active } if (!isValid()) { return; // no valid (anymore) } if (isExecuting) { if (!runParallel) { // do not run while // this job is executing return; } } ++counter; if (!isNaN(minimum)) { if (counter < minimum) { return; } } if (!isNaN(maximum)) { if (counter > maximum) { // stop it to save resources stopScheduler(); return; } } me._lastExecution = Moment(); action(); } catch (e) { me.controller .log(`[ERROR] objects.ConfigJob.startSync().newScheduler: ${cj_helpers.toStringSafe(e)}`); } }, start: false, timeZone: timeZone, }); onStartingActions.forEach(x => { x(); }); me._lastExecution = null; newScheduler.start(); me._scheduler = newScheduler; started = true; } if (started) { try { me.emit(EVENT_JOB_STARTED); } catch (e) { cj_helpers.log(`[ERROR] objects.ConfigJob.startSync(): ${cj_helpers.toStringSafe(e)}`); } } return started; } /** * Stops the job. * * @return {Thenable<boolean>} The promise. */ public stop(): Thenable<boolean> { let me = this; return new Promise<boolean>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { completed(null, me.stopSync()); } catch (e) { completed(e); } }); } /** * Stops the job. * * @returns {boolean} Job has been stopped or not. */ protected stopSync(): boolean { let me = this; let stopped = false; let oldScheduler = me._scheduler; if (cj_helpers.toBooleanSafe(oldScheduler && oldScheduler.running)) { oldScheduler.stop(); stopped = true; me._scheduler = null; me._lastExecution = undefined; } if (stopped) { try { me.emit(EVENT_JOB_STOPPED); } catch (e) { cj_helpers.log(`[ERROR] objects.ConfigJob.stopSync(): ${cj_helpers.toStringSafe(e)}`); } } return stopped; } } /** * A quick pick item for a config job. */ export interface ConfigJobQuickPickItem extends vscode.QuickPickItem { /** * The underlying job. */ job: ConfigJob; }
mkloubert/vs-cron
src/extension.ts
<filename>src/extension.ts 'use strict'; /// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as cj_content from './content'; import * as cj_controller from './controller'; import * as cj_contracts from './contracts'; import * as cj_helpers from './helpers'; import * as cj_workspace from './workspace'; import * as FS from 'fs'; import * as Moment from 'moment'; import * as Path from 'path'; import * as vscode from 'vscode'; let controller: cj_controller.Controller; export function activate(context: vscode.ExtensionContext) { let now = Moment(); // package file let pkgFile: cj_contracts.PackageFile; try { pkgFile = JSON.parse(FS.readFileSync(Path.join(__dirname, '../../package.json'), 'utf8')); } catch (e) { cj_helpers.log(`[ERROR] extension.activate(): ${cj_helpers.toStringSafe(e)}`); } let outputChannel = vscode.window.createOutputChannel("Cron Jobs"); // show infos about the app { if (pkgFile) { outputChannel.appendLine(`${pkgFile.displayName} (${pkgFile.name}) - v${pkgFile.version}`); } outputChannel.appendLine(`Copyright (c) ${now.format('YYYY')} <NAME> <<EMAIL>>`); outputChannel.appendLine(''); outputChannel.appendLine(`GitHub : https://github.com/mkloubert/vs-cron`); outputChannel.appendLine(`Twitter: https://twitter.com/mjkloubert`); outputChannel.appendLine(`Donate : [PayPal] https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W833F9G7EGBNY`); outputChannel.appendLine(` [Flattr] https://flattr.com/submit/auto?fid=o62pkd&url=https%3A%2F%2Fgithub.com%2Fmkloubert%2Fvs-cron`); outputChannel.appendLine(''); } controller = new cj_controller.Controller(context, outputChannel, pkgFile); cj_workspace.resetSelectedWorkspaceFolder(); let showPopupMessage = (popupMsg: string, popupAction: (m: string) => Thenable<string>) => { popupMsg = cj_helpers.toStringSafe(popupMsg).trim(); outputChannel.appendLine(popupMsg); popupAction(`[vs-cron] ${popupMsg}`).then(() => { }, (err) => { cj_helpers.log(`[ERROR] extension.activate().showPopupMessage(): ${cj_helpers.toStringSafe(err)}`); }); }; // get jobs let getJobs = vscode.commands.registerCommand('extension.cronJons.getJobs', (cb: (err: any, result: cj_contracts.JobInfo[]) => void) => { try { let jobInfos = controller.getJobSchedulers().map(s => { let le = s.lastExecution; return { description: s.description, detail: s.detail, isRunning: s.isRunning, lastExecution: le ? le.utc().toISOString() : null, name: s.name, }; }); if (cb) { cb(null, jobInfos); } } catch (e) { cj_helpers.log(`[ERROR] extension.cronJons.getJobs(): ${e}`); } }); // open HTML document let openHtmlDoc = vscode.commands.registerCommand('extension.cronJons.openHtmlDoc', (doc: cj_contracts.Document) => { try { let htmlDocs = controller.htmlDocuments; let url = vscode.Uri.parse(`vs-cron-html://authority/?id=${encodeURIComponent(cj_helpers.toStringSafe(doc.id))}` + `&x=${encodeURIComponent(cj_helpers.toStringSafe(new Date().getTime()))}`); let title = cj_helpers.toStringSafe(doc.title).trim(); if (!title) { title = `[vs-cron] HTML document #${cj_helpers.toStringSafe(doc.id)}`; } vscode.commands.executeCommand('vscode.previewHtml', url, vscode.ViewColumn.One, title).then((success) => { cj_helpers.removeDocuments(doc, htmlDocs); }, (err) => { cj_helpers.removeDocuments(doc, htmlDocs); cj_helpers.log(`[ERROR] extension.cronJons.openHtmlDoc(2): ${err}`); }); } catch (e) { cj_helpers.log(`[ERROR] extension.cronJons.openHtmlDoc(1): ${e}`); } }); let restartRunning = vscode.commands.registerCommand('extension.cronJons.restartRunningJobs', () => { controller.restartRunningJobs().then((restartedJobs) => { let popupMsg: string; if (restartedJobs.length < 1) { popupMsg = 'NO job has been RE-STARTED.'; } else if (1 == restartedJobs.length) { popupMsg = 'One job has been RE-STARTED.'; } else { popupMsg = `${restartedJobs.length} jobs have been RE-STARTED.`; } showPopupMessage(popupMsg, vscode.window.showInformationMessage); }, (err) => { showPopupMessage(`Could not RE-START RUNNING jobs: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); // re-starts a job let restartJob = vscode.commands.registerCommand('extension.cronJons.restartJob', () => { controller.restartJob().then((selectedJob) => { if (false === selectedJob) { showPopupMessage('There is no job that can be RE-STARTED.', vscode.window.showWarningMessage); } else if (selectedJob) { showPopupMessage(`Job '${selectedJob.label}' has been RE-STARTED.`, vscode.window.showInformationMessage); } }, (err) => { showPopupMessage(`Could not RE-START job: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); // re-starts jobs by name let restartJobsByName = vscode.commands.registerCommand('extension.cronJons.restartJobsByName', (jobNames: cj_contracts.JobNames) => { try { jobNames = cj_helpers.asArray(jobNames).map(x => cj_helpers.normalizeString(x)).filter(x => x); jobNames = cj_helpers.distinctArray(jobNames); jobNames.forEach(jn => { let schedulersToRestart = controller.getJobSchedulers() .filter(x => cj_helpers.normalizeString(x.name) === jn); schedulersToRestart.forEach(s => { let startScheduler = () => { s.start().then((hasStarted) => { //TODO }, (err) => { cj_helpers.log(`[ERROR] extension.cronJons.restartJobsByName(3): ${err}`); }); }; if (s.isRunning) { // first stop ... s.stop().then((hasStopped) => { // then start... startScheduler(); }, (err) => { cj_helpers.log(`[ERROR] extension.cronJons.restartJobsByName(2): ${err}`); }); } else { startScheduler(); } }); }); } catch (e) { cj_helpers.log(`[ERROR] extension.cronJons.restartJobsByName(1): ${e}`); } }); // starts a job let startJob = vscode.commands.registerCommand('extension.cronJons.startJob', () => { controller.startJob().then((selectedJob) => { if (false === selectedJob) { showPopupMessage('There is no job that can be STARTED.', vscode.window.showWarningMessage); } else if (selectedJob) { showPopupMessage(`Job '${selectedJob.label}' has been STARTED.`, vscode.window.showInformationMessage); } }, (err) => { showPopupMessage(`Could not START job: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); // starts jobs by name let startJobsByName = vscode.commands.registerCommand('extension.cronJons.startJobsByName', (jobNames: cj_contracts.JobNames) => { try { jobNames = cj_helpers.asArray(jobNames).map(x => cj_helpers.normalizeString(x)).filter(x => x); jobNames = cj_helpers.distinctArray(jobNames); jobNames.forEach(jn => { let schedulersToStart = controller.getJobSchedulers() .filter(x => cj_helpers.normalizeString(x.name) === jn && !x.isRunning); schedulersToStart.forEach(s => { s.start().then((hasStarted) => { //TODO }, (err) => { cj_helpers.log(`[ERROR] extension.cronJons.startJobsByName(2): ${err}`); }); }); }); } catch (e) { cj_helpers.log(`[ERROR] extension.cronJons.startJobsByName(1): ${e}`); } }); // start non running jobs let startNoRunning = vscode.commands.registerCommand('extension.cronJons.startNoRunningJobs', () => { controller.startNoRunningJobs().then((startedJobs) => { let popupMsg: string; if (startedJobs.length < 1) { popupMsg = 'NO job has been STARTED.'; } else if (1 == startedJobs.length) { popupMsg = 'One job has been STARTED.'; } else { popupMsg = `${startedJobs.length} jobs have been STARTED.`; } showPopupMessage(popupMsg, vscode.window.showInformationMessage); }, (err) => { showPopupMessage(`Could not START NON-RUNNING jobs: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); // stops a job let stopJob = vscode.commands.registerCommand('extension.cronJons.stopJob', () => { controller.stopJob().then((selectedJob) => { if (false === selectedJob) { showPopupMessage('There is no job that can be STOPPED.', vscode.window.showWarningMessage); } else if (selectedJob) { showPopupMessage(`Job '${selectedJob.label}' has been STOPPED.`, vscode.window.showInformationMessage); } }, (err) => { showPopupMessage(`Could not STOP job: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); // stops jobs by name let stopJobsByName = vscode.commands.registerCommand('extension.cronJons.stopJobsByName', (jobNames: cj_contracts.JobNames) => { try { jobNames = cj_helpers.asArray(jobNames).map(x => cj_helpers.normalizeString(x)).filter(x => x); jobNames = cj_helpers.distinctArray(jobNames); jobNames.forEach(jn => { let schedulersToStop = controller.getJobSchedulers() .filter(x => cj_helpers.normalizeString(x.name) === jn && x.isRunning); schedulersToStop.forEach(s => { s.stop().then((hasStopped) => { //TODO }, (err) => { cj_helpers.log(`[ERROR] extension.cronJons.stopJobsByName(2): ${err}`); }); }); }); } catch (e) { cj_helpers.log(`[ERROR] extension.cronJons.stopJobsByName(1): ${e}`); } }); // stop all running jobs let stopNoRunning = vscode.commands.registerCommand('extension.cronJons.stopRunningJobs', () => { controller.stopRunningJobs().then((stoppedJobs) => { let popupMsg: string; if (stoppedJobs.length < 1) { popupMsg = 'NO job has been STOPPED.'; } else if (1 == stoppedJobs.length) { popupMsg = 'One job has been STOPPED.'; } else { popupMsg = `${stoppedJobs.length} jobs have been STOPPED.`; } showPopupMessage(popupMsg, vscode.window.showInformationMessage); }, (err) => { showPopupMessage(`Could not STOP RUNNING jobs: ${cj_helpers.toStringSafe(err)}`, vscode.window.showErrorMessage); }); }); let htmlViewer = vscode.workspace.registerTextDocumentContentProvider('vs-cron-html', new cj_content.HtmlTextDocumentContentProvider(controller)); // controller context.subscriptions .push(controller); // html viewer context.subscriptions .push(htmlViewer); // commands context.subscriptions .push(openHtmlDoc, getJobs, startJob, startNoRunning, startJobsByName, stopJob, stopNoRunning, stopJobsByName, restartJob, restartRunning, restartJobsByName); // notfiy setting changes context.subscriptions .push(vscode.workspace.onDidChangeConfiguration(controller.onDidChangeConfiguration, controller)); controller.onActivated(); } export function deactivate() { if (controller) { controller.onDeactivate(); } }
mkloubert/vs-cron
src/helpers.ts
<filename>src/helpers.ts /// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as ChildProcess from 'child_process'; import * as cj_contracts from './contracts'; import * as cj_objects from './objects'; import * as cj_workspace from './workspace'; import * as FS from 'fs'; import * as Moment from 'moment'; import * as Path from 'path'; import * as vscode from 'vscode'; /** * Options for open function. */ export interface OpenOptions { /** * The app (or options) to open. */ app?: string | string[]; /** * The custom working directory. */ cwd?: string; /** * Wait until exit or not. */ wait?: boolean; } /** * Describes a simple 'completed' action. * * @param {any} [err] The occurred error. * @param {TResult} [result] The result. */ export type SimpleCompletedAction<TResult> = (err?: any, result?: TResult) => void; let nextHtmlDocId = -1; /** * Returns a value as array. * * @param {T | T[]} val The value. * * @return {T[]} The value as array. */ export function asArray<T>(val: T | T[]): T[] { if (!Array.isArray(val)) { return [ val ]; } return val; } /** * Clones an object / value deep. * * @param {T} val The value / object to clone. * * @return {T} The cloned value / object. */ export function cloneObject<T>(val: T): T { if (!val) { return val; } return JSON.parse(JSON.stringify(val)); } /** * Compares two values for a sort operation. * * @param {T} x The left value. * @param {T} y The right value. * * @return {number} The "sort value". */ export function compareValues<T>(x: T, y: T): number { if (x === y) { return 0; } if (x > y) { return 1; } if (x < y) { return -1; } return 0; } /** * Converts config jobs to quick pick items. * * @param {cj_objects.ConfigJob|cj_objects.ConfigJob[]} jobs The jobs to convert. * * @returns {cj_objects.ConfigJobQuickPickItem[]} The quick pick items. */ export function configJobsToQuickPicks(jobs: cj_objects.ConfigJob | cj_objects.ConfigJob[]): cj_objects.ConfigJobQuickPickItem[] { return asArray(jobs).filter(x => x).map((x, i) => { let label = toStringSafe(x.config.name).trim(); if (!label) { label = `Cron Job #${i + 1}`; } let description = toStringSafe(x.config.description).trim(); let detail = toStringSafe(x.config.__detail); if (isEmptyString(detail)) { detail = undefined; } return { description: description, detail: detail, job: x, label: label, }; }); } /** * Creates a simple 'completed' callback for a promise. * * @param {Function} resolve The 'succeeded' callback. * @param {Function} reject The 'error' callback. * * @return {SimpleCompletedAction<TResult>} The created action. */ export function createSimplePromiseCompletedAction<TResult>(resolve: (value?: TResult | PromiseLike<TResult>) => void, reject?: (reason: any) => void): SimpleCompletedAction<TResult> { return (err?, result?) => { if (err) { if (reject) { reject(err); } } else { if (resolve) { resolve(result); } } }; } /** * Removes duplicate entries from an array. * * @param {T[]} arr The input array. * * @return {T[]} The filtered array. */ export function distinctArray<T>(arr: T[]): T[] { if (!arr) { return arr; } return arr.filter((x, i) => arr.indexOf(x) === i); } /** * Returns the value from a "parameter" object. * * @param {Object} params The object. * @param {string} name The name of the parameter. * * @return {string} The value of the parameter (if found). */ export function getUrlParam(params: Object, name: string): string { if (params) { name = normalizeString(name); for (let p in params) { if (normalizeString(p) == name) { return toStringSafe(params[p]); } } } } /** * Checks if the string representation of a value is empty * or contains whitespaces only. * * @param {any} val The value to check. * * @return {boolean} Is empty or not. */ export function isEmptyString(val: any): boolean { return '' === toStringSafe(val).trim(); } /** * Checks if a value is (null) or (undefined). * * @param {any} val The value to check. * * @return {boolean} Is (null)/(undefined) or not. */ export function isNullOrUndefined(val: any): boolean { return null === val || 'undefined' === typeof val; } /** * Loads a module. * * @param {string} file The path of the module's file. * @param {boolean} useCache Use cache or not. * * @return {TModule} The loaded module. */ export function loadModuleSync<TModule extends cj_contracts.ScriptModule>(file: string, useCache: boolean = false): TModule { if (!Path.isAbsolute(file)) { file = Path.join(cj_workspace.getRootPath(), file); } file = Path.resolve(file); let stats = FS.lstatSync(file); if (!stats.isFile()) { // TODO: throw new Error(i18.t('isNo.file', file)); throw new Error(`${file} is NO file!`); } if (!useCache) { delete require.cache[file]; // remove from cache } return require(file); } /** * Logs a message. * * @param {any} msg The message to log. */ export function log(msg: any) { let now = Moment(); msg = toStringSafe(msg); console.log(`[vs-cron :: ${now.format('YYYY-MM-DD HH:mm:ss')}] => ${msg}`); } /** * Opens a target. * * @param {string} target The target to open. * @param {OpenOptions} [opts] The custom options to set. * * @param {PromiseLike<ChildProcess.ChildProcess>} The promise. */ export function open(target: string, opts?: OpenOptions): PromiseLike<ChildProcess.ChildProcess> { let me = this; if (!opts) { opts = {}; } opts.wait = toBooleanSafe(opts.wait, true); return new Promise((resolve, reject) => { let completed = (err?: any, cp?: ChildProcess.ChildProcess) => { if (err) { reject(err); } else { resolve(cp); } }; try { if (typeof target !== 'string') { throw new Error('Expected a `target`'); } let cmd: string; let appArgs: string[] = []; let args: string[] = []; let cpOpts: ChildProcess.SpawnOptions = { cwd: opts.cwd || cj_workspace.getRootPath(), }; if (Array.isArray(opts.app)) { appArgs = opts.app.slice(1); opts.app = opts.app[0]; } if (process.platform === 'darwin') { // Apple cmd = 'open'; if (opts.wait) { args.push('-W'); } if (opts.app) { args.push('-a', opts.app); } } else if (process.platform === 'win32') { // Microsoft cmd = 'cmd'; args.push('/c', 'start', '""'); target = target.replace(/&/g, '^&'); if (opts.wait) { args.push('/wait'); } if (opts.app) { args.push(opts.app); } if (appArgs.length > 0) { args = args.concat(appArgs); } } else { // Unix / Linux if (opts.app) { cmd = opts.app; } else { cmd = Path.join(__dirname, 'xdg-open'); } if (appArgs.length > 0) { args = args.concat(appArgs); } if (!opts.wait) { // xdg-open will block the process unless // stdio is ignored even if it's unref'd cpOpts.stdio = 'ignore'; } } args.push(target); if (process.platform === 'darwin' && appArgs.length > 0) { args.push('--args'); args = args.concat(appArgs); } let cp = ChildProcess.spawn(cmd, args, cpOpts); if (opts.wait) { cp.once('error', (err) => { completed(err); }); cp.once('close', function (code) { if (code > 0) { completed(new Error('Exited with code ' + code)); return; } completed(null, cp); }); } else { cp.unref(); completed(null, cp); } } catch (e) { completed(e); } }); } /** * Opens a HTML document in a new tab for a document storage. * * @param {cj_contracts.Document[]} storage The storage to open for. * @param {string} html The HTML document (source code). * @param {string} [title] The custom title for the tab. * @param {any} [id] The custom ID for the document in the storage. * * @returns {Thenable<any>} The promise. */ export function openHtmlDocument(storage: cj_contracts.Document[], html: string, title?: string, id?: any): Thenable<any> { return new Promise((resolve, reject) => { let completed = createSimplePromiseCompletedAction(resolve, reject); try { let body: Buffer; let enc = 'utf8'; if (html) { body = new Buffer(toStringSafe(html), enc); } if (isNullOrUndefined(id)) { id = 'vscjGlobalHtmlDocs::660e0c72-ef45-4305-b82c-fec885062295::' + (++nextHtmlDocId); } let doc: cj_contracts.Document = { body: body, encoding: enc, id: id, mime: 'text/html', }; if (!isEmptyString(title)) { doc.title = toStringSafe(title).trim(); } if (storage) { storage.push(doc); } vscode.commands.executeCommand('extension.cronJons.openHtmlDoc', doc).then((result: any) => { completed(null, result); }, (err) => { completed(err); }); } catch (e) { completed(e); } }); } /** * Normalizes a value as string so that is comparable. * * @param {any} val The value to convert. * @param {(str: string) => string} [normalizer] The custom normalizer. * * @return {string} The normalized value. */ export function normalizeString(val: any, normalizer?: (str: string) => string): string { if (!normalizer) { normalizer = (str) => str.toLowerCase().trim(); } return normalizer(toStringSafe(val)); } /** * Removes documents from a storage. * * @param {cj_contracts.Document|cj_contracts.Document[]} docs The document(s) to remove. * @param {cj_contracts.Document[]} storage The storage. * * @return {cj_contracts.Document[]} The removed documents. */ export function removeDocuments(docs: cj_contracts.Document | cj_contracts.Document[], storage: cj_contracts.Document[]): cj_contracts.Document[] { let ids = asArray(docs).filter(x => x) .map(x => x.id); let removed = []; if (storage) { for (let i = 0; i < storage.length; ) { let d = storage[i]; if (ids.indexOf(d.id) > -1) { removed.push(d); storage.splice(i, 1); } else { ++i; } } } return removed; } /** * Loads a module from the extension context. * * @param {string} id The ID / path of the module. * * @return {any} The loaded module. */ export function requireModule(id: string) { return require(toStringSafe(id)); } /** * Converts a value to a boolean. * * @param {any} val The value to convert. * @param {any} defaultValue The value to return if 'val' is (null) or (undefined). * * @return {boolean} The converted value. */ export function toBooleanSafe(val: any, defaultValue: any = false): boolean { if (isNullOrUndefined(val)) { return defaultValue; } return !!val; } /** * Converts a value to a string that is NOT (null) or (undefined). * * @param {any} str The input value. * @param {any} defValue The default value. * * @return {string} The output value. */ export function toStringSafe(str: any, defValue: any = ''): string { if (isNullOrUndefined(str)) { str = ''; } str = '' + str; if (!str) { str = defValue; } return str; } /** * Tries to dispose an object. * * @param {vscode.Disposable} obj The object to dispose. * * @return {boolean} Operation was successful or not. */ export function tryDispose(obj: vscode.Disposable): boolean { try { if (obj) { obj.dispose(); } return true; } catch (e) { log(`[ERROR] helpers.tryDispose(): ${toStringSafe(e)}`); return false; } } /** * Extracts the query parameters of an URI to an object. * * @param {vscode.Uri} uri The URI. * * @return {Object} The parameters of the URI as object. */ export function uriParamsToObject(uri: vscode.Uri): Object { if (!uri) { return uri; } let params: any; if (!isEmptyString(uri.query)) { // s. https://css-tricks.com/snippets/jquery/get-query-params-object/ params = uri.query.replace(/(^\?)/,'') .split("&") .map(function(n) { return n = n.split("="), this[normalizeString(n[0])] = toStringSafe(decodeURIComponent(n[1])), this} .bind({}))[0]; } if (!params) { params = {}; } return params; }
mkloubert/vs-cron
src/controller.ts
<reponame>mkloubert/vs-cron<gh_stars>1-10 'use strict'; /// <reference types="node" /> // The MIT License (MIT) // // vs-cron (https://github.com/mkloubert/vs-cron) // Copyright (c) <NAME> <<EMAIL>> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as cj_contracts from './contracts'; import * as cj_helpers from './helpers'; import * as cj_objects from './objects'; import * as cj_workspace from './workspace'; import * as Moment from 'moment'; import * as OS from 'os'; import * as vscode from 'vscode'; /** * The extension controller. */ export class Controller implements vscode.Disposable { /** * Stores the current configuration. */ protected _config: cj_contracts.Configuration; /** * Stores the underlying extension context. */ protected readonly _CONTEXT: vscode.ExtensionContext; /** * Stores the global state object for script. */ protected _globalScriptStates: Object; /** * Stores HTML documents. */ protected _htmlDocs: cj_contracts.Document[]; /** * The current list of running jobs. */ protected _jobs: cj_objects.ConfigJob[]; /** * Stores the global output channel. */ protected readonly _OUTPUT_CHANNEL: vscode.OutputChannel; /** * Stores the package file of that extension. */ protected readonly _PACKAGE_FILE: cj_contracts.PackageFile; /** * Initializes a new instance of that class. * * @param {vscode.ExtensionContext} context The underlying extension context. * @param {vscode.OutputChannel} outputChannel The global output channel to use. * @param {cj_contracts.PackageFile} pkgFile The package file of that extension. */ constructor(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, pkgFile: cj_contracts.PackageFile) { this._CONTEXT = context; this._OUTPUT_CHANNEL = outputChannel; this._PACKAGE_FILE = pkgFile; } /** * Gets the current configuration. */ public get config(): cj_contracts.Configuration { return this._config; } /** * Gets the underlying extension context. */ public get context(): vscode.ExtensionContext { return this._CONTEXT; } /** @inheritdoc */ public dispose() { } /** * Returns a copy of the globals from the settings. * * @returns {any} The global data. */ public getGlobals(): any { return cj_helpers.cloneObject(this.config.globals); } /** * Returns the list of job entries. * * @return {cj_contracts.Job[]} The job entries. */ public getJobEntries(): cj_contracts.Job[] { let me = this; let jobs: cj_contracts.Job[]; let cfg = this.config; if (cfg) { jobs = cj_helpers.asArray(cfg.jobs) .filter(x => x); // if jobs = jobs.filter(j => { try { let conditions = cj_helpers.asArray(j.if) .filter(x => !cj_helpers.isEmptyString(x)); for (let i = 0; i < conditions.length; i++) { let $cwd = process.cwd(); let $homeDir = OS.homedir(); let $require = function(id: string) { return require(cj_helpers.toStringSafe(id)); }; let $workspaceRoot = cj_workspace.getRootPath(); if (!cj_helpers.toBooleanSafe(eval(conditions[i]))) { return false; // at least one condition does NOT match } } } catch (e) { me.log(`[ERROR] Controller.getJobEntries().if: ${cj_helpers.toStringSafe(e)}`); return false; } return true; }); // isFor let myName = this.name; jobs = jobs.filter(j => { let isFor = cj_helpers.asArray(j.isFor) .map(x => cj_helpers.normalizeString(x)) .filter(x => '' !== x); return isFor.length < 1 ? true : isFor.indexOf(myName) > -1; }); // platforms let myPlatform = cj_helpers.normalizeString(process.platform); jobs = jobs.filter(j => { let platforms = cj_helpers.asArray(j.platforms) .map(x => cj_helpers.normalizeString(x)) .filter(x => '' !== x); return platforms.length < 1 ? true : platforms.indexOf(myPlatform) > -1; }); } return jobs; } /** * Returns a copy of the list of job job schedulers. * * @returns {cj_contracts.JobScheduler[]} The list of schedulers. */ public getJobSchedulers(): cj_contracts.JobScheduler[] { return this._jobs.map(x => x); } /** * Gets the object that stores global data for all script. */ public get globalScriptStates(): Object { return this._globalScriptStates; } /** * Gets the list of HTML documents. */ public get htmlDocuments(): cj_contracts.Document[] { return this._htmlDocs; } /** * Logs a message. * * @param {any} msg The message to log. * * @chainable */ public log(msg: any): Controller { let now = Moment(); this.outputChannel .appendLine(`[${now.format('YYYY-MM-DD HH:mm:ss')}] ${cj_helpers.toStringSafe(msg)}`); return this; } /** * Get the name that represents that machine. */ public get name(): string { return cj_helpers.normalizeString(OS.hostname()); } /** * Is invoked after extension has been activated. */ public onActivated() { this.reloadConfiguration(); } /** * Is invoked when extension will be deactivated. */ public onDeactivate() { let jobs = cj_helpers.asArray(this._jobs) .filter(x => x); jobs.forEach(x => { cj_helpers.tryDispose(x); }); } /** * Event after configuration changed. */ public onDidChangeConfiguration() { this.reloadConfiguration(); } /** * Gets the global output channel. */ public get outputChannel(): vscode.OutputChannel { return this._OUTPUT_CHANNEL; } /** * Gets the package file of that extension. */ public get packageFile(): cj_contracts.PackageFile { return this._PACKAGE_FILE; } /** * Reloads configuration. */ public reloadConfiguration() { let cfg = <cj_contracts.Configuration>vscode.workspace.getConfiguration("cron.jobs"); this._config = cfg; this._htmlDocs = []; this.showDeprecatedMessage().then(() => { }).catch(() => { }); this.reloadJobs(); } /** * Reloads the jobs. */ protected reloadJobs() { let me = this; let oldJobs = cj_helpers.asArray(me._jobs) .filter(x => x); oldJobs.forEach(x => { cj_helpers.tryDispose(x); }); let newJobList: cj_objects.ConfigJob[] = []; let cfg = me.config; me._globalScriptStates = {}; me.getJobEntries().forEach(x => { let newJob = new cj_objects.ConfigJob(x, me); newJobList.push(newJob); if (cj_helpers.toBooleanSafe(x.autoStart)) { newJob.start().then(() => { }, (err) => { me.log(`[ERROR] Controller.reloadJobs(): ${cj_helpers.toStringSafe(err)}`); }); } }); me._jobs = newJobList; } /** * Restarts a specific job. * * @returns {Thenable<false|cj_objects.ConfigJobQuickPickItem>} The promise. */ public restartJob(): Thenable<false | cj_objects.ConfigJobQuickPickItem> { let me = this; return new Promise<false | cj_objects.ConfigJobQuickPickItem>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let quickPicks = cj_helpers.configJobsToQuickPicks(me._jobs .filter(x => x && x.isRunning)); quickPicks.sort((x, y) => { return cj_helpers.compareValues(cj_helpers.normalizeString(x.label), cj_helpers.normalizeString(x.label)); }); if (quickPicks.length > 0) { vscode.window.showQuickPick(quickPicks, { placeHolder: 'Select the job you would like to RE-START...', }).then(x => { if (x) { // first stop ... x.job.stop().then(() => { // ... then start x.job.start().then(() => { completed(null, x); }, (err) => { completed(err, x); }); }, (err) => { completed(err); }); } else { completed(null); // nothing selected } }); } else { completed(null, false); // no items available } } catch (e) { completed(e); } }); } /** * Restarts all running jobs. * * @returns {Thenable<cj_objects.ConfigJob[]>} The promise. */ public restartRunningJobs(): Thenable<cj_objects.ConfigJob[]> { let me = this; return new Promise<cj_objects.ConfigJob[]>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let restartedJobs: cj_objects.ConfigJob[] = []; let runningJobs = me._jobs.filter(x => x.isRunning); let nextJob: () => void; nextJob = () => { if (runningJobs.length < 1) { completed(null, restartedJobs); return; } let j = runningJobs.shift(); // first stop ... j.stop().then(() => { // ... and start again j.start().then((hasStarted) => { if (hasStarted) { restartedJobs.push(j); } nextJob(); }, (err) => { completed(err); }); }, (err) => { completed(err); }); }; nextJob(); } catch (e) { completed(e); } }); } private async showDeprecatedMessage() { const KEY_SHOW_DEPRECATED_MESSAGE = 'vscjShowDeprecatedMessage'; try { this._CONTEXT .globalState .update('vscjLastKnownVersion', undefined); } catch { } let newShowMessageValue: boolean; try { const SHOW_MESSAGE = cj_helpers.toBooleanSafe( this._CONTEXT.globalState.get(KEY_SHOW_DEPRECATED_MESSAGE, true), true ); newShowMessageValue = SHOW_MESSAGE; if (SHOW_MESSAGE) { const BTN = await vscode.window.showWarningMessage( "[vs-cron] The extension has been DEPRECATED. You can try out 'vscode-powertools' for the future ...", "Open 'vscode-powertools'", "Maybe next time", "Do not show again" ); if ('Maybe next time' === BTN) { newShowMessageValue = true; } else { newShowMessageValue = false; } if ("Open 'vscode-powertools'" === BTN) { await cj_helpers.open('https://marketplace.visualstudio.com/items?itemName=ego-digital.vscode-powertools'); } } } catch (e) { this.log(`[ERROR] Controller.showDeprecatedMessage(1): ${cj_helpers.toStringSafe(e)}`); } finally { try { await this._CONTEXT.globalState.update( KEY_SHOW_DEPRECATED_MESSAGE, newShowMessageValue ); } catch { } } } /** * Starts a specific job. * * @returns {Thenable<false|cj_objects.ConfigJobQuickPickItem>} The promise. */ public startJob(): Thenable<false | cj_objects.ConfigJobQuickPickItem> { let me = this; return new Promise<false | cj_objects.ConfigJobQuickPickItem>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let quickPicks = cj_helpers.configJobsToQuickPicks(me._jobs .filter(x => x && !x.isRunning)); quickPicks.sort((x, y) => { return cj_helpers.compareValues(cj_helpers.normalizeString(x.label), cj_helpers.normalizeString(x.label)); }); if (quickPicks.length > 0) { vscode.window.showQuickPick(quickPicks, { placeHolder: 'Select the job you would like to START...', }).then(x => { if (x) { x.job.start().then(() => { completed(null, x); }, (err) => { completed(err, x); }); } else { completed(null); // nothing selected } }); } else { completed(null, false); // no items available } } catch (e) { completed(e); } }); } /** * Starts all non-running jobs. * * @returns {Thenable<cj_objects.ConfigJob[]>} The promise. */ public startNoRunningJobs(): Thenable<cj_objects.ConfigJob[]> { let me = this; return new Promise<cj_objects.ConfigJob[]>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let startedJobs: cj_objects.ConfigJob[] = []; let nonRunningJobs = me._jobs.filter(x => !x.isRunning); let nextJob: () => void; nextJob = () => { if (nonRunningJobs.length < 1) { completed(null, startedJobs); return; } let j = nonRunningJobs.shift(); j.start().then((hasStarted) => { if (hasStarted) { startedJobs.push(j); } nextJob(); }, (err) => { completed(err); }); }; nextJob(); } catch (e) { completed(e); } }); } /** * Stops a specific job. * * @returns {Thenable<false|cj_objects.ConfigJobQuickPickItem>} The promise. */ public stopJob(): Thenable<false | cj_objects.ConfigJobQuickPickItem> { let me = this; return new Promise<false | cj_objects.ConfigJobQuickPickItem>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let quickPicks = cj_helpers.configJobsToQuickPicks(me._jobs .filter(x => x && x.isRunning)); quickPicks.sort((x, y) => { return cj_helpers.compareValues(cj_helpers.normalizeString(x.label), cj_helpers.normalizeString(x.label)); }); if (quickPicks.length > 0) { vscode.window.showQuickPick(quickPicks, { placeHolder: 'Select the job you would like to STOP...', }).then(x => { if (x) { x.job.stop().then(() => { completed(null, x); }, (err) => { completed(err, x); }); } else { completed(null); // nothing selected } }); } else { completed(null, false); // no items available } } catch (e) { completed(e); } }); } /** * Stops all running jobs. * * @returns {Thenable<cj_objects.ConfigJob[]>} The promise. */ public stopRunningJobs(): Thenable<cj_objects.ConfigJob[]> { let me = this; return new Promise<cj_objects.ConfigJob[]>((resolve, reject) => { let completed = cj_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let stoppedJobs: cj_objects.ConfigJob[] = []; let runningJobs = me._jobs.filter(x => x.isRunning); let nextJob: () => void; nextJob = () => { if (runningJobs.length < 1) { completed(null, stoppedJobs); return; } let j = runningJobs.shift(); j.stop().then((hasStopped) => { if (hasStopped) { stoppedJobs.push(j); } nextJob(); }, (err) => { completed(err); }); }; nextJob(); } catch (e) { completed(e); } }); } }
cane4044/fast-dna
packages/fast-element/src/directives/index.ts
<filename>packages/fast-element/src/directives/index.ts export * from "./behavior"; export * from "./binding"; export * from "./directive"; export * from "./ref"; export * from "./repeat"; export * from "./when";
cane4044/fast-dna
packages/fast-element/src/observation/observable.ts
<reponame>cane4044/fast-dna import { Controller } from "../controller"; import { FastElement } from "../fast-element"; import { Notifier, PropertyChangeNotifier } from "./notifier"; import { Expression, ExpressionContext } from "../interfaces"; export interface GetterInspector { inspect(source: unknown, propertyName: string): void; } const notifierLookup = new WeakMap<any, Notifier>(); let currentInspector: GetterInspector | undefined = void 0; export const Observable = { setInspector(inspector: GetterInspector) { currentInspector = inspector; }, clearInspector() { currentInspector = void 0; }, createArrayObserver(array: any[]): Notifier { throw new Error("Must call enableArrayObservation before observing arrays."); }, getNotifier<T extends Notifier = Notifier>(source: any): T { let found = source.$controller || notifierLookup.get(source); if (found === void 0) { if (source instanceof FastElement) { found = Controller.forCustomElement(source); } else if (Array.isArray(source)) { found = Observable.createArrayObserver(source); } else { notifierLookup.set(source, (found = new PropertyChangeNotifier())); } } return found; }, track(source: unknown, propertyName: string) { if (currentInspector !== void 0) { currentInspector.inspect(source, propertyName); } }, notify(source: unknown, args: any) { Observable.getNotifier(source).notify(source, args); }, define(target: {}, propertyName: string) { const fieldName = `_${propertyName}`; const callbackName = `${propertyName}Changed`; const hasCallback = callbackName in target; Reflect.defineProperty(target, propertyName, { enumerable: true, get: function(this: any) { Observable.track(this, propertyName); return this[fieldName]; }, set: function(this: any, value) { const oldValue = this[fieldName]; if (oldValue !== value) { this[fieldName] = value; if (hasCallback) { this[callbackName](); } Observable.notify(this, propertyName); } }, }); }, }; export function observable($target: {}, $prop: string) { Observable.define($target, $prop); } export function inspectAndEvaluate<T = unknown>( expression: Expression, scope: unknown, context: ExpressionContext, inspector: GetterInspector ): T { Observable.setInspector(inspector); const value = expression(scope, context); Observable.clearInspector(); return value as T; }
cane4044/fast-dna
packages/fast-components/src/design-system-provider/design-system-provider.template.ts
import { accentFill, accentFillLarge, accentForeground, accentForegroundCut, accentForegroundLarge, neutralDividerRest, neutralFill, neutralFillCard, neutralFillInput, neutralFillStealth, neutralFillToggle, neutralFocus, neutralFocusInnerAccent, neutralForeground, neutralForegroundHint, neutralForegroundHintLarge, neutralForegroundToggle, neutralForegroundToggleLarge, neutralLayerCard, neutralLayerCardContainer, neutralLayerFloating, neutralLayerL1, neutralLayerL1Alt, neutralLayerL2, neutralLayerL3, neutralLayerL4, neutralOutline, } from "@microsoft/fast-components-styles-msft"; import { html } from "@microsoft/fast-element"; import { DesignSystemProvider } from "./design-system-provider"; export const DesignSystemProviderTemplate = html<DesignSystemProvider>` <template style=" --accent-base-color: ${x => x.accentBaseColor}; --background-color: ${x => x.backgroundColor}; --base-height-multiplier: ${x => x.baseHeightMultiplier}; --body-font: ${x => x.bodyFont}; --corner-radius: ${x => x.cornerRadius}; --disabled-opacity: ${x => x.disabledOpacity}; --density: ${x => x.density}; --design-unit: ${x => x.designUnit}; --elevated-corner-radius: ${x => x.elevatedCornerRadius}; --focus-outline-width: ${x => x.focusOutlineWidth}; --outline-width: ${x => x.outlineWidth}; --height-number: calc((var(--base-height-multiplier) + var(--density)) * var(--design-unit)); --neutral-foreground-rest: ${x => neutralForeground(x.designSystem).rest}; --neutral-foreground-hover: ${x => neutralForeground(x.designSystem).hover}; --neutral-foreground-active: ${x => neutralForeground(x.designSystem).active}; --neutral-foreground-focus: ${x => neutralForeground(x.designSystem).focus}; --neutral-foreground-toggle: ${x => neutralForegroundToggle(x.designSystem)}; --neutral-foreground-toggle-large: ${x => neutralForegroundToggleLarge(x.designSystem)}; --neutral-foreground-hint: ${x => neutralForegroundHint(x.designSystem)}; --neutral-foreground-hint-large: ${x => neutralForegroundHintLarge(x.designSystem)}; --accent-foreground-rest: ${x => accentForeground(x.designSystem).rest}; --accent-foreground-hover: ${x => accentForeground(x.designSystem).hover}; --accent-foreground-active: ${x => accentForeground(x.designSystem).active}; --accent-foreground-focus: ${x => accentForeground(x.designSystem).focus}; --accent-foreground-cut-rest: ${x => accentForegroundCut(x.designSystem)}; --accent-foreground-large-rest: ${x => accentForegroundLarge(x.designSystem).rest}; --accent-foreground-large-hover: ${x => accentForegroundLarge(x.designSystem).hover}; --accent-foreground-large-active: ${x => accentForegroundLarge(x.designSystem).active}; --accent-foreground-large-focus: ${x => accentForegroundLarge(x.designSystem).focus}; --neutral-fill-rest: ${x => neutralFill(x.designSystem).rest}; --neutral-fill-hover: ${x => neutralFill(x.designSystem).hover}; --neutral-fill-active: ${x => neutralFill(x.designSystem).active}; --neutral-fill-focus: ${x => neutralFill(x.designSystem).focus}; --neutral-fill-selected: ${x => neutralFill(x.designSystem).selected}; --neutral-fill-stealth-rest: ${x => neutralFillStealth(x.designSystem).rest}; --neutral-fill-stealth-hover: ${x => neutralFillStealth(x.designSystem).hover}; --neutral-fill-stealth-active: ${x => neutralFillStealth(x.designSystem).active}; --neutral-fill-stealth-focus: ${x => neutralFillStealth(x.designSystem).focus}; --neutral-fill-stealth-selected: ${x => neutralFillStealth(x.designSystem).selected}; --neutral-fill-toggle-rest: ${x => neutralFillToggle(x.designSystem).rest}; --neutral-fill-toggle-hover: ${x => neutralFillToggle(x.designSystem).hover}; --neutral-fill-toggle-active: ${x => neutralFillToggle(x.designSystem).active}; --neutral-fill-toggle-focus: ${x => neutralFillToggle(x.designSystem).focus}; --neutral-fill-input-rest: ${x => neutralFillInput(x.designSystem).rest}; --neutral-fill-input-hover: ${x => neutralFillInput(x.designSystem).hover}; --neutral-fill-input-active: ${x => neutralFillInput(x.designSystem).active}; --neutral-fill-input-focus: ${x => neutralFillInput(x.designSystem).focus}; --accent-fill-rest: ${x => accentFill(x.designSystem).rest}; --accent-fill-hover: ${x => accentFill(x.designSystem).hover}; --accent-fill-active: ${x => accentFill(x.designSystem).active}; --accent-fill-focus: ${x => accentFill(x.designSystem).focus}; --accent-fill-selected: ${x => accentFill(x.designSystem).selected}; --accent-fill-large-rest: ${x => accentFillLarge(x.designSystem).rest}; --accent-fill-large-hover: ${x => accentFillLarge(x.designSystem).hover}; --accent-fill-large-active: ${x => accentFillLarge(x.designSystem).active}; --accent-fill-large-focus: ${x => accentFillLarge(x.designSystem).focus}; --accent-fill-large-selected: ${x => accentFillLarge(x.designSystem).selected}; --neutral-fill-card-rest: ${x => neutralFillCard(x.designSystem)}; --neutral-outline-rest: ${x => neutralOutline(x.designSystem).rest}; --neutral-outline-hover: ${x => neutralOutline(x.designSystem).hover}; --neutral-outline-active: ${x => neutralOutline(x.designSystem).active}; --neutral-outline-focus: ${x => neutralOutline(x.designSystem).focus}; --neutral-divider-rest: ${x => neutralDividerRest(x.designSystem)}; --neutral-layer-floating: ${x => neutralLayerFloating(x.designSystem)}; --neutral-layer-card: ${x => neutralLayerCard(x.designSystem)}; --neutral-layer-card-container: ${x => neutralLayerCardContainer(x.designSystem)}; --neutral-layer-l1: ${x => neutralLayerL1(x.designSystem)}; --neutral-layer-l1-alt: ${x => neutralLayerL1Alt(x.designSystem)}; --neutral-layer-l2: ${x => neutralLayerL2(x.designSystem)}; --neutral-layer-l3: ${x => neutralLayerL3(x.designSystem)}; --neutral-layer-l4: ${x => neutralLayerL4(x.designSystem)}; --neutral-focus: ${x => neutralFocus(x.designSystem)}; --neutral-focus-inner-accent: ${x => neutralFocusInnerAccent(() => x.designSystem.accentBaseColor)(x.designSystem)}; "> <slot></slot> </template> `;
cane4044/fast-dna
packages/fast-element/src/template.ts
import { compileTemplate } from "./template-compiler"; import { HTMLView, ElementView, SyntheticView, View } from "./view"; import { DOM } from "./dom"; import { Behavior, BehaviorFactory } from "./directives/behavior"; import { Expression } from "./interfaces"; import { Directive } from "./directives/directive"; import { BindingDirective } from "./directives/binding"; export interface ElementViewTemplate { create(host: Element): ElementView; } export interface SyntheticViewTemplate { create(): SyntheticView; } export class HTMLTemplate extends Directive implements ElementViewTemplate, SyntheticViewTemplate { public createPlaceholder = DOM.createBlockPlaceholder; private behaviorCount: number; private hasHostBehaviors: boolean; constructor( private templateElement: HTMLTemplateElement, private viewBehaviorFactories: BehaviorFactory[], private hostBehaviorFactories: BehaviorFactory[] ) { super(); this.behaviorCount = this.viewBehaviorFactories.length + this.hostBehaviorFactories.length; this.hasHostBehaviors = this.hostBehaviorFactories.length > 0; } public create(host?: Element) { const fragment = this.templateElement.content.cloneNode(true) as DocumentFragment; const viewFactories = this.viewBehaviorFactories; const behaviors = new Array<Behavior>(this.behaviorCount); const walker = document.createTreeWalker( fragment, 133, // element, text, comment null, false ); let targetIndex = 0; let behaviorIndex = 0; let node = walker.nextNode(); for (let ii = viewFactories.length; behaviorIndex < ii; ++behaviorIndex) { const factory = viewFactories[behaviorIndex]; const factoryIndex = factory.targetIndex; while (node !== null) { if (targetIndex === factoryIndex) { behaviors[behaviorIndex] = factory.createBehavior(node); break; } else { node = walker.nextNode(); targetIndex++; } } } if (this.hasHostBehaviors) { const hostFactories = this.hostBehaviorFactories; for (let i = 0, ii = hostFactories.length; i < ii; ++i, ++behaviorIndex) { behaviors[behaviorIndex] = hostFactories[i].createBehavior(host); } } return new HTMLView(fragment, behaviors); } public createBehavior(target: any) { return new HTMLTemplateBehavior(this, target); } } export class HTMLTemplateBehavior implements Behavior { private view: SyntheticView; constructor(template: SyntheticViewTemplate, location: HTMLElement) { this.view = template.create(); this.view.insertBefore(location); } bind(source: unknown) { this.view.bind(source); } unbind() { this.view.unbind(); } } export interface CaptureType<T> {} type TemplateValue<T> = Expression<T> | string | number | Directive | CaptureType<T>; export function html<T = any>( strings: TemplateStringsArray, ...values: TemplateValue<T>[] ) { const directives: Directive[] = []; let html = ""; for (let i = 0, ii = strings.length - 1; i < ii; ++i) { html += strings[i]; let value = values[i]; if (typeof value === "function") { value = new BindingDirective(value as Expression); } if (value instanceof Directive) { html += value.createPlaceholder(i); directives.push(value); } else { html += value; } } html += strings[strings.length - 1]; return compileTemplate(html, directives); }
cane4044/fast-dna
packages/fast-element/src/dom.ts
import { Callable } from "./interfaces"; const markerClass = `fast-${Math.random() .toString(36) .substring(7)}`; const updateQueue = [] as Callable[]; export const DOM = { isMarker(node: Node): node is Comment { return node.nodeType === 8 && (node as Comment).data.startsWith(markerClass); }, extractDirectiveIndexFromMarker(node: Comment): number { return parseInt(node.data.replace(`${markerClass}:`, "")); }, createInterpolationPlaceholder(index: number) { return `@{${index}}`; }, createBlockPlaceholder(index: number) { return `<!--${markerClass}:${index}-->`; }, queueUpdate(callable: Callable) { if (updateQueue.length < 1) { window.requestAnimationFrame(processQueue); } updateQueue.push(callable); }, }; function processQueue() { const capacity = 1024; let index = 0; while (index < updateQueue.length) { const task = updateQueue[index]; (task as any).call(); index++; // Prevent leaking memory for long chains of recursive calls to `queueMicroTask`. // If we call `queueMicroTask` within a MicroTask scheduled by `queueMicroTask`, the queue will // grow, but to avoid an O(n) walk for every MicroTask we execute, we don't // shift MicroTasks off the queue after they have been executed. // Instead, we periodically shift 1024 MicroTasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for ( let scan = 0, newLength = updateQueue.length - index; scan < newLength; scan++ ) { updateQueue[scan] = updateQueue[scan + index]; } updateQueue.length -= index; index = 0; } } updateQueue.length = 0; }
cane4044/fast-dna
packages/fast-element/src/template-compiler.ts
import { ExpressionContext } from "./interfaces"; import { HTMLTemplate } from "./template"; import { BehaviorFactory } from "./directives/behavior"; import { DOM } from "./dom"; import { BindingDirective, BindingType } from "./directives/binding"; import { Directive, AttachedBehaviorDirective } from "./directives/directive"; type InlineDirective = BindingDirective | AttachedBehaviorDirective; const compilationContext = { locatedDirectives: 0, targetIndex: -1 }; const prefixToBindingType: Record<string, BindingType> = { "@": BindingType.trigger, $: BindingType.attribute, "?": BindingType.booleanAttribute, }; export function compileTemplate( html: string | HTMLTemplateElement, directives: Directive[] ): HTMLTemplate { let element: HTMLTemplateElement; if (typeof html === "string") { element = document.createElement("template"); element.innerHTML = html; const fec = element.content.firstElementChild; if (fec !== null && fec.tagName === "TEMPLATE") { element = fec as HTMLTemplateElement; } } else { element = html; } const hostFactories: BehaviorFactory[] = []; compilationContext.locatedDirectives = 0; compileAttributes(element, directives, hostFactories, true); const fragment = element.content; const viewFactories: BehaviorFactory[] = []; const directiveCount = directives.length; const walker = document.createTreeWalker( fragment, 133, // element, text, comment null, false ); compilationContext.targetIndex = -1; while (compilationContext.locatedDirectives < directiveCount) { const node = walker.nextNode(); if (node === null) { break; } compilationContext.targetIndex++; switch (node.nodeType) { case 1: // element node compileAttributes(node as HTMLElement, directives, viewFactories); break; case 3: // text node // use wholeText to retrieve the textContent of all adjacent text nodes. const directive = tryParsePlaceholders( (node as Text).wholeText, directives ) as BindingDirective; if (directive !== null) { node.textContent = " "; directive.setType(BindingType.text); viewFactories.push(directive); directive.targetIndex = compilationContext.targetIndex; //remove adjacent text nodes. while (node.nextSibling && node.nextSibling.nodeType === 3) { node.parentNode!.removeChild(node.nextSibling); } } break; case 8: // comment if (DOM.isMarker(node)) { const directive = directives[DOM.extractDirectiveIndexFromMarker(node)]; directive.targetIndex = compilationContext.targetIndex; compilationContext.locatedDirectives++; viewFactories.push(directive); } else { node.parentNode!.removeChild(node); compilationContext.targetIndex--; } } } if (DOM.isMarker(fragment.firstChild!)) { fragment.insertBefore(document.createComment(""), fragment.firstChild); } return new HTMLTemplate(element, viewFactories, hostFactories); } function compileAttributes( node: HTMLElement, directives: Directive[], factories: BehaviorFactory[], includeBasicValues: boolean = false ) { const attributes = node.attributes; for (let i = 0, ii = attributes.length; i < ii; ++i) { const attr = attributes[i]; const attrName = attr.name; const attrValue = attr.value; let directive = tryParsePlaceholders(attrValue, directives); if (directive === null && includeBasicValues) { directive = new BindingDirective(x => attrValue); } if (directive !== null) { prepareAttributeDirective(node, attrName, directive); node.removeAttributeNode(attr); i--; ii--; directive.targetIndex = compilationContext.targetIndex; factories.push(directive); } } } function prepareAttributeDirective( element: HTMLElement, attrName: string, directive: InlineDirective ) { if (directive instanceof AttachedBehaviorDirective) { return; } const firstChar = attrName[0]; const bindingType = prefixToBindingType[firstChar]; if (bindingType === void 0) { if (attrName === "style") { directive.setType(BindingType.attribute); directive.targetName = "style"; } else { directive.targetName = attrNameToPropertyName(element.tagName, attrName); } } else { directive.setType(bindingType); directive.targetName = attrName.substr(1); } } function attrNameToPropertyName(tagName: string, attr: string): string { switch (tagName) { case "LABEL": switch (attr) { case "for": return "htmlFor"; default: return attr; } case "IMG": switch (attr) { case "usemap": return "useMap"; default: return attr; } case "INPUT": switch (attr) { case "maxlength": return "maxLength"; case "minlength": return "minLength"; case "formaction": return "formAction"; case "formenctype": return "formEncType"; case "formmethod": return "formMethod"; case "formnovalidate": return "formNoValidate"; case "formtarget": return "formTarget"; case "inputmode": return "inputMode"; default: return attr; } case "TEXTAREA": switch (attr) { case "maxlength": return "maxLength"; default: return attr; } case "TD": case "TH": switch (attr) { case "rowspan": return "rowSpan"; case "colspan": return "colSpan"; default: return attr; } default: switch (attr) { case "class": return "classList"; case "accesskey": return "accessKey"; case "contenteditable": return "contentEditable"; case "tabindex": return "tabIndex"; case "textcontent": return "textContent"; case "innerhtml": return "innerHTML"; case "scrolltop": return "scrollTop"; case "scrollleft": return "scrollLeft"; case "readonly": return "readOnly"; default: return attr; } } } function tryParsePlaceholders( value: string, directives: Directive[] ): InlineDirective | null { let i = value.indexOf("@{", 0); let ii = value.length; let char; let pos = 0; let open = 0; let quote = null; let interpolationStart; let parts: (string | Directive)[] | null; let partIndex = 0; while (i >= 0 && i < ii - 2) { open = 1; interpolationStart = i; i += 2; do { char = value[i]; i++; if (char === "'" || char === '"') { if (quote === null) { quote = char; } else if (quote === char) { quote = null; } continue; } if (char === "\\") { i++; continue; } if (quote !== null) { continue; } if (char === "{") { open++; } else if (char === "}") { open--; } } while (open > 0 && i < ii); if (open === 0) { // lazy allocate array parts = parts! || []; if ( value[interpolationStart - 1] === "\\" && value[interpolationStart - 2] !== "\\" ) { // escaped interpolation parts[partIndex] = value.substring(pos, interpolationStart - 1) + value.substring(interpolationStart, i); partIndex++; } else { // standard interpolation parts[partIndex] = value.substring(pos, interpolationStart); partIndex++; let directiveIndex = parseInt( value.substring(interpolationStart + 2, i - 1) ); let directive = directives[directiveIndex]; parts[partIndex] = directive; partIndex++; } pos = i; i = value.indexOf("@{", i); } else { break; } } // no interpolation. if (partIndex === 0) { return null; } // literal. parts![partIndex] = value.substr(pos); parts = parts!.filter(x => x !== ""); if (parts.length == 1) { compilationContext.locatedDirectives++; return parts[0] as InlineDirective; } const partCount = parts.length; const finalParts = parts!.map(x => { if (typeof x === "string") { return () => x; } compilationContext.locatedDirectives++; return (x as BindingDirective).expression; }); const expression = (scope: unknown, context: ExpressionContext) => { let output = ""; for (let i = 0; i < partCount; ++i) { output += finalParts[i](scope, context); } return output; }; return new BindingDirective(expression); }
cane4044/fast-dna
packages/fast-element/src/directives/behavior.ts
<gh_stars>1-10 export interface Behavior { bind(source: unknown): void; unbind(): void; } export interface BehaviorFactory { targetIndex: number; createBehavior(target: any): Behavior; }
cane4044/fast-dna
packages/fast-element/src/interfaces.ts
export type Callable = typeof Function.prototype.call | { call(): void }; export const emptyArray = Object.freeze([]); /** * Provides additional contextual information available to arrow functions * evaluated in the context of a template update. */ export interface ExpressionContext { event: Event; } /** * The signature of an arrow function capable of being evluated as part of a template update. */ export type Expression<T = any, K = any> = (scope: T, context: ExpressionContext) => K;
cane4044/fast-dna
packages/fast-element/src/directives/binding.ts
import { Directive } from "./directive"; import { Expression } from "../interfaces"; import { Subscriber } from "../observation/subscriber-collection"; import { Observable, GetterInspector, inspectAndEvaluate, } from "../observation/observable"; import { DOM } from "../dom"; import { Behavior } from "./behavior"; export const enum BindingType { attribute = 0, booleanAttribute = 1, text = 2, property = 3, trigger = 4, } function normalBind(this: BindingBehavior, source: unknown) { this.source = source; this.updateTarget(inspectAndEvaluate(this.expression, source, context, this)); } function triggerBind(this: BindingBehavior, source: unknown) { this.source = source; this.target.addEventListener(this.targetName!, this, true); } function normalUnbind(this: BindingBehavior) { if (this.record !== null) { this.record.unsubscribe(this); } this.source = null; } function triggerUnbind(this: BindingBehavior) { this.target.removeEventListener(this.targetName!, this, true); this.source = null; } function updateAttributeTarget(this: BindingBehavior, value: unknown): void { if (value === null || value === void 0) { this.target.removeAttribute(this.targetName!); } else { this.target.setAttribute(this.targetName!, value as string); } } function updateBooleanAttributeTarget(this: BindingBehavior, value: unknown): void { (value as boolean) ? (this.target as HTMLElement).setAttribute(this.targetName!, "") : (this.target as HTMLElement).removeAttribute(this.targetName!); } function updateTextTarget(this: BindingBehavior, value: unknown): void { this.target.textContent = value as string; } function updatePropertyTarget(this: BindingBehavior, value: unknown): void { this.target[this.targetName!] = value; } export class BindingDirective extends Directive { public targetName?: string; public createPlaceholder = DOM.createInterpolationPlaceholder; private bind: typeof normalBind = normalBind; private unbind: typeof normalUnbind = normalUnbind; private updateTarget: typeof updatePropertyTarget = updatePropertyTarget; constructor(public expression: Expression) { super(); } setType(type: BindingType) { switch (type) { case BindingType.trigger: this.bind = triggerBind; this.unbind = triggerUnbind; break; default: this.bind = normalBind; this.unbind = normalUnbind; break; } switch (type) { case BindingType.attribute: this.updateTarget = updateAttributeTarget; break; case BindingType.booleanAttribute: this.updateTarget = updateBooleanAttributeTarget; break; case BindingType.text: this.updateTarget = updateTextTarget; break; case BindingType.property: this.updateTarget = updatePropertyTarget; break; } } createBehavior(target: any) { return new BindingBehavior( target, this.expression, this.bind, this.unbind, this.updateTarget, this.targetName ); } } class ObservationRecord { constructor(private source: any, private propertyName: string) {} subscribe(subscriber: Subscriber) { Observable.getNotifier(this.source).subscribe(subscriber, this.propertyName); } unsubscribe(subscriber: Subscriber) { Observable.getNotifier(this.source).unsubscribe(subscriber, this.propertyName); } } const context = {} as any; export class BindingBehavior implements Behavior, GetterInspector, Subscriber { public source: unknown; public record: ObservationRecord | null = null; private needsQueue = true; constructor( public target: any, public expression: Expression, public bind: typeof normalBind, public unbind: typeof normalUnbind, public updateTarget: typeof updatePropertyTarget, public targetName?: string ) {} handleChange(source: any, propertyName: string): void { if (this.needsQueue) { this.needsQueue = false; DOM.queueUpdate(this); } } handleEvent(event: Event) { const context = { event }; this.expression(this.source, context as any); event.preventDefault(); } call() { this.needsQueue = true; this.updateTarget(this.expression(this.source, context)); } inspect(source: any, propertyName: string) { if (this.record !== null) { this.record.unsubscribe(this); } this.record = new ObservationRecord(source, propertyName); this.record.subscribe(this); } }
cane4044/fast-dna
packages/fast-components/src/design-system-provider/design-system-provider.ts
<reponame>cane4044/fast-dna import { parseColorHexRGB } from "@microsoft/fast-colors"; import { createColorPalette, DesignSystem, DesignSystemDefaults, } from "@microsoft/fast-components-styles-msft"; import { FastElement, observable, Observable } from "@microsoft/fast-element"; /** * The following interface is an implementation of * design-system.schema.json in TypeScript with * as much accuracy as TypeScript supports. */ export interface DesignSystemData { accentBaseColor: string; backgroundColor: string; cornerRadius: number; disabledOpacity: number; density: number; designUnit: number; elevatedCornerRadius: number; focusOutlineWidth: number; outlineWidth: number; } /** * Custom property reflector for the stub */ function designSystemProperty(target: DesignSystemProvider, name: string): void { const store = `_${name}`; const callbackName = `${name}Changed`; Reflect.defineProperty(target, name, { enumerable: true, get(this: any): string { Observable.track(this, name); return this[store]; }, set(this: any, value: any): void { if (this[store] !== value) { this[store] = value; Observable.notify(this, name); this.designSystem = { ...this.designSystem, [name]: value }; if (typeof this[callbackName] === "function") { this[callbackName](); } } }, }); } export class DesignSystemProvider extends FastElement implements DesignSystemData { @designSystemProperty public accentBaseColor: string = "#0078D4"; private accentBaseColorChanged(): void { const color = parseColorHexRGB(this.accentBaseColor); if (color !== null) { this.designSystem = { ...this.designSystem, accentPalette: createColorPalette(color), }; } } @designSystemProperty public backgroundColor: string = "#FFFFFF"; @designSystemProperty public baseHeightMultiplier: number = 8; @designSystemProperty public bodyFont: string = "Segoe UI, sans-serif"; @designSystemProperty public cornerRadius: number = 2; @designSystemProperty public disabledOpacity = 0.3; @designSystemProperty public density = 0; @designSystemProperty public designUnit = 4; @designSystemProperty public elevatedCornerRadius = 4; @designSystemProperty public focusOutlineWidth = 2; @designSystemProperty public outlineWidth = 1; @observable public designSystem: DesignSystem = DesignSystemDefaults; }
cane4044/fast-dna
packages/fast-element/src/index.ts
<filename>packages/fast-element/src/index.ts export * from "./template"; export * from "./fast-element"; export * from "./attributes"; export * from "./controller"; export * from "./interfaces"; export * from "./template-compiler"; export * from "./styles"; export * from "./di"; export * from "./view"; export * from "./observation/observable"; export * from "./dom"; export * from "./directives/behavior"; export * from "./directives/binding"; export * from "./directives/directive"; export * from "./directives/ref"; export * from "./directives/when";
cane4044/fast-dna
packages/fast-element/src/fast-element.ts
import { Controller } from "./controller"; import { emptyArray } from "./interfaces"; import { Observable } from "./observation/observable"; import { ElementViewTemplate } from "./template"; import { ElementStyles } from "./styles"; import { AttributeDefinition, AttributeConfiguration } from "./attributes"; import { Registry } from "./di"; const defaultShadowOptions: ShadowRootInit = { mode: "open" }; const defaultElementOptions: ElementDefinitionOptions = {}; function createFastElement(BaseType: typeof HTMLElement) { return class FastElement extends BaseType { public $controller!: Controller; public constructor() { super(); Controller.forCustomElement(this); } public $emit( type: string, detail?: any, options?: Omit<CustomEventInit, "detail"> ) { return this.$controller.emit(type, detail, options); } public connectedCallback() { this.$controller.onConnectedCallback(); } public disconnectedCallback() { this.$controller.onDisconnectedCallback(); } public attributeChangedCallback( name: string, oldValue: string, newValue: string ) { this.$controller.onAttributeChangedCallback(name, oldValue, newValue); } }; } const fastDefinitions = new Map<Function, FastElementDefinition>(); export const FastElement = Object.assign(createFastElement(HTMLElement), { from(BaseType: typeof HTMLElement) { return createFastElement(BaseType); }, define<T extends Function>( Type: T, nameOrDef: string | PartialFastElementDefinition = (Type as any).definition ): T { if (typeof nameOrDef === "string") { nameOrDef = { name: nameOrDef }; } const name = nameOrDef.name; const attributes = AttributeDefinition.collect( (Type as any).attributes, nameOrDef.attributes ); const shadowOptions = nameOrDef.shadowOptions === void 0 ? defaultShadowOptions : nameOrDef.shadowOptions === null ? void 0 : { ...defaultShadowOptions, ...nameOrDef.shadowOptions }; const elementOptions = nameOrDef.elementOptions === void 0 ? defaultElementOptions : { ...defaultElementOptions, ...nameOrDef.shadowOptions }; const observedAttributes = new Array(attributes.length); const proto = Type.prototype; const propertyLookup = {}; const attributeLookup = {}; for (let i = 0, ii = attributes.length; i < ii; ++i) { const current = attributes[i]; Observable.define(proto, current.property); observedAttributes[i] = current.attribute; propertyLookup[current.property] = current; attributeLookup[current.attribute] = current; } Reflect.defineProperty(Type, "observedAttributes", { value: observedAttributes, enumerable: true, }); const definition = new FastElementDefinition( name, attributes, propertyLookup, attributeLookup, nameOrDef.template, nameOrDef.styles, shadowOptions, elementOptions, nameOrDef.dependencies ); fastDefinitions.set(Type, definition); customElements.define(name, Type as any, definition.elementOptions); return Type; }, getDefinition<T extends Function>(Type: T): FastElementDefinition | undefined { return fastDefinitions.get(Type); }, }); export type PartialFastElementDefinition = { readonly name: string; readonly template?: ElementViewTemplate; readonly styles?: ElementStyles; readonly attributes?: (AttributeConfiguration | string)[]; readonly dependencies?: Registry[]; readonly shadowOptions?: Partial<ShadowRootInit> | null; readonly elementOptions?: ElementDefinitionOptions; }; export class FastElementDefinition { public constructor( public readonly name: string, public readonly attributes: ReadonlyArray<AttributeDefinition>, public readonly propertyLookup: Record<string, AttributeDefinition>, public readonly attributeLookup: Record<string, AttributeDefinition>, public readonly template?: ElementViewTemplate, public readonly styles?: ElementStyles, public readonly shadowOptions?: ShadowRootInit, public readonly elementOptions?: ElementDefinitionOptions, public readonly dependencies: ReadonlyArray<Registry> = emptyArray ) {} } export function customElement(nameOrDef: string | PartialFastElementDefinition) { return function(type: Function) { FastElement.define(type, nameOrDef); }; }
cane4044/fast-dna
packages/fast-element/src/directives/repeat.ts
import { Expression } from "../interfaces"; import { SyntheticViewTemplate, CaptureType } from "../template"; import { Behavior } from "./behavior"; import { DOM } from "../dom"; import { Observable, GetterInspector, inspectAndEvaluate, } from "../observation/observable"; import { SyntheticView, HTMLView } from "../view"; import { Subscriber } from "../observation/subscriber-collection"; import { ArrayObserver, enableArrayObservation } from "../observation/array-observer"; import { Splice } from "../observation/array-change-records"; import { Directive } from "./directive"; export class RepeatDirective extends Directive { createPlaceholder = DOM.createBlockPlaceholder; constructor(public expression: Expression, public template: SyntheticViewTemplate) { super(); enableArrayObservation(); } public createBehavior(target: any) { return new RepeatBehavior(target, this.expression, this.template); } } export class RepeatBehavior implements Behavior, GetterInspector, Subscriber { private source: unknown; private views: SyntheticView[] = []; private items: any[] | null = null; private observer?: ArrayObserver; constructor( private location: Node, private expression: Expression, private template: SyntheticViewTemplate ) {} bind(source: unknown) { this.source = source; this.items = inspectAndEvaluate(this.expression, source, null as any, this); this.checkCollectionObserver(false); this.refreshAllViews(); } unbind() { this.source = null; this.items = null; this.unbindAllViews(); this.checkCollectionObserver(true); } inspect(source: any, propertyName: string) { Observable.getNotifier(source).subscribe(this, propertyName); } handleChange(source: any, args: string | Splice[]): void { if (typeof args === "string") { this.source = source; this.items = inspectAndEvaluate( this.expression, this.source, null as any, this ); this.checkCollectionObserver(false); this.refreshAllViews(); } else { this.updateViews(args); } } private checkCollectionObserver(fromUnbind: boolean): void { const oldObserver = this.observer; if (fromUnbind) { if (oldObserver !== void 0) { oldObserver.removeSubscriber(this); } } else { if (!this.items) { this.items = []; } const newObserver = (this.observer = Observable.getNotifier<ArrayObserver>( this.items )); if (oldObserver !== newObserver && oldObserver) { oldObserver.removeSubscriber(this); } if (newObserver) { newObserver.addSubscriber(this); } } } private updateViews(splices: Splice[]) { const views = this.views; const totalRemoved: SyntheticView[] = []; let removeDelta = 0; for (let i = 0, ii = splices.length; i < ii; ++i) { const splice = splices[i]; const removed = splice.removed; totalRemoved.push( ...views.splice(splice.index + removeDelta, removed.length) ); removeDelta -= splice.addedCount; } const items = this.items!; const template = this.template; for (let i = 0, ii = splices.length; i < ii; ++i) { const splice = splices[i]; let addIndex = splice.index; const end = addIndex + splice.addedCount; for (; addIndex < end; ++addIndex) { const neighbor = views[addIndex]; const location = neighbor ? neighbor.firstChild : this.location; const view = totalRemoved.length > 0 ? totalRemoved.shift()! : template.create(); views.splice(addIndex, 0, view); view.bind(items[addIndex]); view.insertBefore(location); } } for (let i = 0, ii = totalRemoved.length; i < ii; ++i) { totalRemoved[i].dispose(); } } private refreshAllViews() { const items = this.items!; let itemsLength = items.length; let views = this.views; const viewsLength = views.length; const template = this.template; const location = this.location; if (itemsLength === 0) { // all views need to be removed HTMLView.disposeContiguousBatch(this.views); this.views = []; } else if (viewsLength === 0) { // all views need to be created this.views = views = new Array(itemsLength); for (let i = 0; i < itemsLength; ++i) { const view = template.create(); view.bind(items[i]); views[i] = view; view.insertBefore(location); } } else { // attempt to reuse existing views with new data let i = 0; for (; i < itemsLength; ++i) { if (i < viewsLength) { views[i].bind(items[i]); } else { const view = template.create(); view.bind(items[i]); views.push(view); view.insertBefore(location); } } const removed = views.splice(i, viewsLength - i); for (i = 0, itemsLength = removed.length; i < itemsLength; ++i) { removed[i].dispose(); } } } private unbindAllViews() { const views = this.views; for (let i = 0, ii = views.length; i < ii; ++i) { views[i].unbind(); } } } export function repeat<T = any, K = any>( expression: Expression<T, K[]>, template: SyntheticViewTemplate ): CaptureType<T> { return new RepeatDirective(expression, template); }
cane4044/fast-dna
packages/fast-element/src/directives/when.ts
<reponame>cane4044/fast-dna import { DOM } from "../dom"; import { SyntheticViewTemplate, CaptureType } from "../template"; import { SyntheticView } from "../view"; import { Expression } from "../interfaces"; import { Behavior } from "./behavior"; import { Observable, GetterInspector, inspectAndEvaluate, } from "../observation/observable"; import { Subscriber } from "../observation/subscriber-collection"; import { Directive } from "./directive"; export class WhenDirective extends Directive { createPlaceholder = DOM.createBlockPlaceholder; constructor(public expression: Expression, public template: SyntheticViewTemplate) { super(); } public createBehavior(target: any) { return new WhenBehavior(target, this.expression, this.template); } } export class WhenBehavior implements Behavior, GetterInspector, Subscriber { private view: SyntheticView | null = null; private cachedView?: SyntheticView; private source: unknown; constructor( private location: Node, private expression: Expression, private template: SyntheticViewTemplate ) {} bind(source: unknown) { this.source = source; this.updateTarget( inspectAndEvaluate<boolean>(this.expression, source, null as any, this) ); } unbind() { if (this.view !== null) { this.view.unbind(); } this.source = null; } inspect(source: any, propertyName: string) { Observable.getNotifier(source).subscribe(this, propertyName); } handleChange(source: any, propertyName: string): void { DOM.queueUpdate(this); } public call() { this.updateTarget(this.expression(this.source, null as any)); } updateTarget(show: boolean) { if (show && this.view == null) { this.view = this.cachedView || (this.cachedView = this.template.create()); this.view.bind(this.source); this.view.insertBefore(this.location); } else if (!show && this.view !== null) { // do not dispose, since we may want to use the view again this.view.remove(); this.view.unbind(); this.view = null; } } } export function when<T = any, K = any>( expression: Expression<T, K>, template: SyntheticViewTemplate ): CaptureType<T> { return new WhenDirective(expression, template); }
BestDingSheng/zarm-web
components/button/button.tsx
<gh_stars>0 import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import ButtonProps from './PropsType'; import Icon from '../icon'; class Button extends Component<ButtonProps, any> { static Group; static defaultProps = { prefixCls: 'za-button', htmlType: 'button', theme: 'default', shape: 'radius', ghost: false, size: null, block: false, onClick: () => {}, }; static propTypes = { type: PropTypes.string, shape: PropTypes.oneOf(['circle', 'round', 'rect', 'radius']), size: PropTypes.oneOf(['xl', 'lg', 'sm', 'xs']), onClick: PropTypes.func, loading: PropTypes.bool, className: PropTypes.string, icon: PropTypes.string, block: PropTypes.bool, }; render () { const { prefixCls, htmlType, type, size, block, shape, active, focus, disabled, ghost, loading, className, onClick, children, style, theme, href, target, icon, ...others } = this.props; const classes = classnames({ 'is-block': block, 'is-rect': shape === 'rect', 'is-radius': shape === 'radius', 'is-round': shape === 'round', 'is-circle': shape === 'circle', 'is-active': active, 'is-focus': focus, 'is-disabled': disabled, 'is-loading': loading, 'is-ghost': ghost, 'has-icon': icon, [`${prefixCls}`]: true, [`${prefixCls}--${theme}`]: theme, [`${prefixCls}--${size}`]: size, [className!]: className, }); const textContent = loading ? ( <React.Fragment> <Icon type="loading" className="rotate360"/>&nbsp;&nbsp;{children} </React.Fragment> ) : ( children ); return ( href ? <a className={classes} href={href} style={style} target={target} {...others} onClick={e => (!disabled && !loading) && onClick!(e)} > {textContent} </a> : ( <button type={htmlType} className={classes} style={style} disabled={disabled} onClick={e => (!disabled && !loading) && onClick!(e)} {...others} > {textContent} </button> ) ); } } export default Button;
BestDingSheng/zarm-web
components/notification/PropsType.tsx
<reponame>BestDingSheng/zarm-web<gh_stars>0 import React from 'react'; export default interface PropsType { prefixCls?: string; style?: React.CSSProperties; top?: number | string; theme?: 'default' | 'primary' | 'success' | 'warning' | 'danger' | 'loading'; title?: string; message?: string; stayTime?: number | string; btn?: React.ReactElement<any>; timeout?: null; willUnMount?: any; onClick?: (e?: React.SyntheticEvent<any>) => void; onClose?: (e?: React.SyntheticEvent<any>) => void; className?: string; isMessage?: boolean; key?: string; }
BestDingSheng/zarm-web
components/grid/row.tsx
<reponame>BestDingSheng/zarm-web import React, { PureComponent, cloneElement } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; type Align = 'top' | 'middle' | 'top'; type Justify = 'start' | 'end' | 'center' | 'space-around' | 'space-between'; export interface IProps { gutter?: string | number; prefixCls?: string; style?: object; className?: string; justify?: Justify; align?: Align; type?: 'flex' | undefined; } export default class Row extends PureComponent<IProps> { static defaultProps = { prefixCls: 'za-row', gutter: 0, }; static propTypes = { prefixCls: PropTypes.string, gutter: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), justify: PropTypes.oneOf(['start', 'end', 'center', 'space-around', 'space-between']), align: PropTypes.oneOf(['top', 'middle', 'bottom']), }; render () { const { gutter, prefixCls, style, className, children, justify, align, type } = this.props; const rowStyle = gutter ? { marginLeft: -gutter / 2, marginRight: -gutter / 2 } : {}; const cls = classnames(prefixCls, className, { [`${prefixCls}--flex`]: type === 'flex', [`${prefixCls}--flex-${justify}`]: justify, [`${prefixCls}--flex-${align}`]: align, }); return ( <div className={cls} style={{ ...style, ...rowStyle }}> { React.Children.map(children, (element: React.ReactElement<any>, index) => cloneElement(element, { gutter, key: index, }), ) } </div> ); } }
BestDingSheng/zarm-web
components/time-picker/TimePicker.tsx
import React, { Component, Fragment } from 'react'; import classnames from 'classnames'; import Dropdown from '../dropdown'; import Icon from '../icon'; import TimeSelect from './TimeSelect'; import LocaleReceiver from '../locale/LocaleReceiver'; type placement = 'bottomLeft' | 'bottomCenter' | 'bottomRight' | 'topLeft' | 'topCenter' | 'topRight'; export interface TimePickerProps { value?: any; defaultValue?: string; placeholder?: string; isDisabled?: boolean; isRadius?: string; size?: any; style?: React.CSSProperties; locale: { clear: string, confirm: string }; localeCode: string; dropdownStyle?: React.CSSProperties; placement?: placement; onChange?: (value: any) => void; } class TimePicker extends Component<TimePickerProps, any> { static defaultProps = { onChange: () => {}, isRadius: true, }; private unmounted: boolean; private dropdownEl: React.ReactNode; constructor (props) { super(props); const value = props.value || props.defaultValue; this.unmounted = false; this.state = { value, dropdown: false, }; } componentDidMount () { this.unmounted = true; } componentWillReceiveProps (nextProps: TimePickerProps) { if ('value' in nextProps) { this.setState({ value: nextProps.value }); } } onDateChange (value) { if (value.indexOf('undefined') > -1) { return; } this.setState({ value, }, () => { this.setDropdown(!!value, this.props.onChange); }); } setDropdown (isOpen, callback?) { if (!this.unmounted) { return; } this.setState({ dropdown: isOpen, }, () => { if (callback) { callback(this.state.value); } }); } isNodeInTree (node, tree) { while (node) { if (node === tree) { return true; } node = node.parentNode; } return false; } onVisibleChange = visible => { this.setState({ dropdown: visible, }); } onConfirmBtn () { this.setDropdown(false, this.props.onChange); } render () { const { defaultValue, placeholder, isDisabled, isRadius, size, locale, localeCode, dropdownStyle, placement, onChange, ...others } = this.props; const { value, dropdown } = this.state; const disabled = 'disabled' in this.props || isDisabled; const radius = 'radius' in this.props || isRadius; let valueText = placeholder || '00:00:00'; let hasValue = false; if (value) { valueText = value; hasValue = true; } const cls = classnames({ 'za-select': true, 'za-time__select-wrapper': true, 'za-select--open': dropdown, disabled, radius, [`size-${size}`]: !!size, }); const textCls = classnames({ 'za-select__text': true, 'za-select__text-placeholder': !hasValue, }); const overlay = ( <Fragment> <TimeSelect value={valueText} onChange={(value) => this.onDateChange(value)} /> <div className="za-select__bottom"> <a className="clear-btn" href="javascript:;" onClick={() => this.onDateChange('')}> {locale.clear} </a> <a className="confirm-btn" href="javascript:;" onClick={() => this.onConfirmBtn()}> {locale.confirm} </a> </div> </Fragment> ); return ( <div className={cls} style={this.props.style} {...others}> <Dropdown ref={el => this.dropdownEl = el} visible={dropdown} disabled={disabled} style={{ width: 240, ...dropdownStyle }} zIndex={2020} onVisibleChange={this.onVisibleChange} overlay={overlay} placement={placement} > <div className="za-select__selection" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false" > <span className={textCls}>{valueText}</span> <Icon className="za-time__select-icon" type="time-circle"/> </div> </Dropdown> </div> ); } } export default LocaleReceiver(TimePicker, 'TimePicker');
BestDingSheng/zarm-web
components/button/PropsType.tsx
import { ButtonHTMLAttributes, MouseEvent, CSSProperties } from 'react'; export type theme = 'default' | 'primary' | 'danger'; export type size = 'xl' | 'lg' | 'sm' | 'xs'; export type shape = 'circle' | 'round' | 'rect' | 'radius'; export type buttonType = 'button' | 'submit' | 'reset'; interface BasicPropsType { prefixCls?: string; htmlType?: buttonType; theme?: theme; size?: size; icon?: string; block?: boolean; shape?: shape; active?: boolean; focus?: boolean; disabled?: boolean; loading?: boolean; className?: string; ghost?: boolean; style?: CSSProperties; onClick?: (e: MouseEvent) => void; href?: string | undefined; target?: string | undefined; fRef?: any; } export interface ButtonGroupProps { size?: size; style?: React.CSSProperties; className?: string; prefixCls?: string; } type PropsType = ButtonHTMLAttributes<{}> & BasicPropsType; export default PropsType;
BestDingSheng/zarm-web
components/select/Option.tsx
import React, { Component } from 'react'; import cn from 'classnames'; import Icon from '../icon'; import { OptionProps } from './PropsType'; class Option extends Component<OptionProps, any> { static defaultProps = { isDisabled: false, onChange: () => { }, }; render() { const { props } = this; const { children, checked, disabled, onDoubleClick, showCheckIcon, } = props; const cls = cn({ 'za-option__list': true, 'is-checked': checked, 'is-disabled': disabled, }); return ( <li className={cls} style={{ paddingRight: showCheckIcon ? 25 : 10 }} onClick={e => props.onChange(e)} onDoubleClick={onDoubleClick} > {children} {showCheckIcon && checked && <Icon className="checked-icon" theme="primary" type="right" />} </li> ); } } export default Option;
EffectiveXf5/joandjane-back
src/blog/dto/blog.dto.ts
export class BlogDTO { readonly author: string; readonly reading_time: string; readonly title: string; readonly img: string; readonly description: string; readonly createdAt: Date; }
EffectiveXf5/joandjane-back
src/blog/blog.controller.spec.ts
<gh_stars>0 import { Test, TestingModule } from '@nestjs/testing'; import { BlogController } from './blog.controller'; import { BlogService } from './blog.service'; describe('BlogController', () => { let controller: BlogController; const mockBlogService = { createOneBlog: jest.fn((dto) => { return { ...dto } }), updateOneBlog: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })) }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [BlogController], providers: [BlogService] }) .overrideProvider(BlogService) .useValue(mockBlogService) .compile(); controller = module.get<BlogController>(BlogController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); it('should create a blog', async() => { const dto = { author: 'author', reading_time: '14 horas', title: 'title', img: 'img', description: 'description', createdAt: new Date(Date.now()) } expect(await controller.createOneBlog(dto)).toEqual({ author: dto.author, reading_time: dto.reading_time, title: dto.title, img: dto.img, description: dto.description, createdAt: dto.createdAt }) expect(mockBlogService.createOneBlog).toHaveBeenCalled(); }) it('should update a blog', async() => { const dto = { author: 'author', reading_time: '14 horas', title: 'title', img: 'img', description: 'description', createdAt: new Date(Date.now()) } expect(await controller.updateOneBlog(dto, '1')).toEqual({ id: '1', ...dto }) expect(mockBlogService.updateOneBlog).toHaveBeenCalled(); }) });
EffectiveXf5/joandjane-back
src/activity/schema/activity.schema.ts
<reponame>EffectiveXf5/joandjane-back<gh_stars>0 import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Document } from "mongoose"; export type ActivityDocument = Activity & Document; @Schema() export class Activity { @Prop( { required: true } ) title: string; @Prop() price: string; @Prop() img: string; @Prop( { required: true } ) destination: string[]; @Prop() type: string[]; @Prop( { required: true } ) sumary: string; @Prop() duration: string; @Prop() cancelation: string; @Prop() instant_confirmation: string; @Prop() mobile_ticket: boolean; @Prop() pet_friendly: boolean; @Prop() experience_details: string; @Prop() includes: string[]; @Prop() location: string[]; @Prop() prepare_experience: string; @Prop( { type: Object } ) reviews: object; @Prop() children: boolean; @Prop( { default: Date.now } ) createdAt: Date; }; export const ActivitySchema = SchemaFactory.createForClass(Activity);
EffectiveXf5/joandjane-back
src/blog/blog.controller.ts
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; import { BlogService } from './blog.service'; import { Blog } from './interfaces/blog.interface'; import { BlogDTO } from './dto/blog.dto'; @Controller('blog') export class BlogController { constructor(private blogService: BlogService) {} @Get('/') async getAllBlogs(): Promise<Blog[]> { return await this.blogService.getAllBlogs(); } @Get('/:blogID') async getOneBlog(@Param('blogID') blogID): Promise<Blog> { return await this.blogService.getOneBlog(blogID); } @Post('/create-blog') async createOneBlog(@Body() blogDTO: BlogDTO) { return await this.blogService.createOneBlog(blogDTO); } @Put('/update-blog/:blogID') async updateOneBlog(@Body() blogDTO: BlogDTO, @Param('blogID') blogID) { return await this.blogService.updateOneBlog(blogID, blogDTO); } @Delete('/delete-blog/:blogID') async deleteOneBlog(@Param('blogID') blogID) { return await this.blogService.deleteOneBlog(blogID); } }
EffectiveXf5/joandjane-back
src/destination/destination.controller.spec.ts
<gh_stars>0 import { Test, TestingModule } from '@nestjs/testing'; import { DestinationController } from './destination.controller'; import { DestinationService } from './destination.service'; describe('DestinationController', () => { let controller: DestinationController; const mockDestinationService = { createNewDestination: jest.fn((dto) => { return { id: Date.now(), ...dto } }), updateNewDestination: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })), }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [DestinationController], providers: [DestinationService], }) .overrideProvider(DestinationService) .useValue(mockDestinationService) .compile(); controller = module.get<DestinationController>(DestinationController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); it('should create a destination', async() => { const dto = { title: 'titlename', img: 'an image', numberOfActivities: '20 activities', createdAt: new Date(Date.now()) } expect(await controller.createOneDestination(dto)).toEqual({ id: expect.any(Number), title: dto.title, img: dto.img, numberOfActivities: dto.numberOfActivities, createdAt: dto.createdAt }); expect(mockDestinationService.createNewDestination).toHaveBeenCalled(); }); it('should update a destination', async() => { const dto = { title: 'titlename', img: 'an image', numberOfActivities: '20 activities', createdAt: new Date(Date.now()) } expect(await controller.updateDestination(dto, '1')).toEqual({ id: '1', ...dto }); expect(mockDestinationService.updateNewDestination).toHaveBeenCalled(); }); });
EffectiveXf5/joandjane-back
src/database/database.service.ts
import { ConfigModule } from '@nestjs/config'; import { MongooseModule } from '@nestjs/mongoose'; export const DatabaseConection = [ //isGlobal nos permite usar la configuracion en otros modulos de las app ConfigModule.forRoot({ isGlobal: true }), MongooseModule.forRoot(process.env.MONGODB_URL), ]
EffectiveXf5/joandjane-back
src/destination/destination.service.spec.ts
import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { DestinationService } from './destination.service'; describe('DestinationService', () => { let service: DestinationService; const mockDestinationModel = { create: jest.fn().mockImplementation( dto => dto ), findByIdAndUpdate: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })), findById: jest.fn().mockImplementation( id => id ), findByIdAndDelete: jest.fn().mockImplementation( id => id ) } beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [DestinationService, { provide: getModelToken('Destination'), useValue: mockDestinationModel }], }).compile(); service = module.get<DestinationService>(DestinationService); }); it('should be defined', () => { expect(service).toBeDefined(); }); it('should create a new destination', async() => { const dto = { title: 'title', img: 'img', numberOfActivities: '13 activities', createdAt: new Date(Date.now()) }; expect(await service.createNewDestination(dto)).toEqual({ title: dto.title, img: dto.img, numberOfActivities: dto.numberOfActivities, createdAt: dto.createdAt }); expect(mockDestinationModel.create).toHaveBeenCalled(); }); it('should update a destination', async() => { const dto = { title: 'titleNew', img: 'imgNew', numberOfActivities: '15 activities new', createdAt: new Date(Date.now()) } expect(await service.updateNewDestination('1', dto)).toEqual({ id: '1', ...dto }); expect(mockDestinationModel.findByIdAndUpdate).toHaveBeenCalled(); }); it('should get an unique destination', async() => { const id = '1'; expect(await service.getOneDestination(id)).toBeTruthy(); expect(mockDestinationModel.findById).toHaveBeenCalled(); }); it('should delete a destination', async() => { /* const id = 'id'; */ expect(await service.deleteDestination('id')).toBeTruthy(); expect(mockDestinationModel.findByIdAndDelete).toHaveBeenCalled(); }); });
EffectiveXf5/joandjane-back
src/destination/destination.controller.ts
<reponame>EffectiveXf5/joandjane-back import { Get, Param, Post, Body, Put, Delete } from '@nestjs/common'; import { Controller } from '@nestjs/common'; import { DestinationService } from './destination.service'; import { Destination } from './interface/destination.interface'; import { DestinationDTO } from './dto/destination.dto'; @Controller('destination') export class DestinationController { constructor(private destinationService: DestinationService) {} @Get('/') async getAllDestination(): Promise<Destination[]> { return await this.destinationService.getAllDestionations(); } @Get('/:destinationID') async getOneDestination(@Param('destinationID') destinationID): Promise<Destination> { return await this.destinationService.getOneDestination(destinationID); } @Post('/create-destination') createOneDestination(@Body() destinationDTO: DestinationDTO): Promise<Destination> { return this.destinationService.createNewDestination(destinationDTO); } @Put('/update-destination/:destinationID') async updateDestination(@Body() destinationDTO: DestinationDTO, @Param('destinationID') destinationID): Promise<Destination> { return await this.destinationService.updateNewDestination(destinationID, destinationDTO); } @Delete('/delete-destination/:destinationID') async deleteOneDestination(@Param('destinationID') destinationID): Promise<Destination> { return await this.destinationService.deleteDestination(destinationID); } }
EffectiveXf5/joandjane-back
src/destination/destination.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Destination } from './interface/destination.interface'; import { DestinationDTO } from './dto/destination.dto'; @Injectable() export class DestinationService { constructor(@InjectModel('Destination') private readonly destinationModel: Model<Destination>) {} async getAllDestionations(): Promise<Destination[]> { const allDestinations = await this.destinationModel.find(); return allDestinations; } async getOneDestination(destinationID: string): Promise<Destination> { const oneDestination = await this.destinationModel.findById(destinationID); return oneDestination; } async createNewDestination(destinationDTO: DestinationDTO): Promise<Destination> { const newDestination = await this.destinationModel.create(destinationDTO); return newDestination; } async updateNewDestination(destinationID: string, destinationDTO: DestinationDTO): Promise<Destination> { const destinationToUpdate = await this.destinationModel.findByIdAndUpdate(destinationID, destinationDTO, { new: true }); return destinationToUpdate; } async deleteDestination(destinationID: string): Promise<Destination> { const destinationToDelete = await this.destinationModel.findByIdAndDelete(destinationID); return destinationToDelete; } }
EffectiveXf5/joandjane-back
src/activity/activity.controller.ts
<gh_stars>0 import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; import { ActivityService } from './activity.service'; import { ActivityDTO } from './dto/activity.dto'; import { Activity } from './interfaces/activity.interface'; @Controller('activity') export class ActivityController { constructor(private activityService: ActivityService) {} @Get('/') async getAllActivities(): Promise<Activity[]> { return await this.activityService.getAllActivities(); }; @Get('/:activityID') async getOneActivity(@Param('activityID') activityID): Promise<Activity> { return await this.activityService.getOneActivity(activityID); }; @Post('/create-activity') async createOneActivity(@Body() activityDTO: ActivityDTO) { return await this.activityService.createNewActivity(activityDTO); }; @Put('/update-activity/:activityID') async updateOneActivity(@Body() activityDTO: ActivityDTO, @Param('activityID') activityID) { return await this.activityService.updateOneActivity(activityID, activityDTO); }; @Delete('/delete-activity/:activityID') async deleteOneActivity(@Param('activityID') activityID) { return await this.activityService.deleteOneActivity(activityID); }; };
EffectiveXf5/joandjane-back
src/destination/dto/destination.dto.ts
<gh_stars>0 export class DestinationDTO { readonly title: string; readonly img: string; readonly numberOfActivities: string; readonly createdAt: Date; }
EffectiveXf5/joandjane-back
src/blog/schema/blog.schema.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Document } from 'mongoose'; export type BlogDocument = Blog & Document; @Schema() export class Blog { @Prop( { required: true } ) author: string; @Prop( { required: true } ) reading_time: string; @Prop( { required: true } ) title: string; @Prop() img: string; @Prop() description: string; @Prop( { default: Date.now } ) createdAt: Date; } export const BlogSchema = SchemaFactory.createForClass(Blog);
EffectiveXf5/joandjane-back
src/activity/activity.controller.spec.ts
<filename>src/activity/activity.controller.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { ActivityController } from './activity.controller'; import { ActivityService } from './activity.service'; describe('ActivityController', () => { let controller: ActivityController; const mockActivityService = { createNewActivity: jest.fn((dto) => { return { id: Date.now(), ...dto } }), updateOneActivity: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })), }; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [ActivityController], providers: [ActivityService], }) .overrideProvider(ActivityService) .useValue(mockActivityService) .compile(); controller = module.get<ActivityController>(ActivityController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); it('should create an activity', async() => { const dto = { title: 'title', price: "12", img: 'img1', destination: ['destination', 'destination'], type: ['type', 'type'], sumary: 'sumary', duration: 'duration', cancelation: 'cancelation', instant_confirmation: "true", mobile_ticket: true, pet_friendly: true, experience_details: 'experience', includes: ['includes', 'includes'], location: ['location', 'location'], prepare_experience: "prepare", reviews: { 1: 'review1', 2: 'review2' }, children: true, createdAt: new Date(Date.now()) } expect(await controller.createOneActivity(dto)).toEqual({ id: expect.any(Number), title: dto.title, price: dto.price, img: dto.img, destination: dto.destination, type: dto.type, sumary: dto.sumary, duration: dto.duration, cancelation: dto.cancelation, instant_confirmation: dto.instant_confirmation, mobile_ticket: dto.mobile_ticket, pet_friendly: dto.pet_friendly, experience_details: dto.experience_details, includes: dto.includes, location: dto.location, prepare_experience: dto.prepare_experience, reviews: dto.reviews, children: dto.children, createdAt: dto.createdAt }); expect(mockActivityService.createNewActivity).toHaveBeenCalled(); }); it('should update an activity', async() => { const dto = { title: 'title', price: "12", img: 'img1', destination: ['destination', 'destination'], type: ['type', 'type'], sumary: 'sumary', duration: 'duration', cancelation: 'cancelation', instant_confirmation: "true", mobile_ticket: true, pet_friendly: true, experience_details: 'experience', includes: ['includes', 'includes'], location: ['location', 'location'], prepare_experience: "prepare", reviews: { 1: 'review1', 2: 'review2' }, children: true, createdAt: new Date(Date.now()) } expect(await controller.updateOneActivity(dto, '1')).toEqual({ id: '1', ...dto }); expect(mockActivityService.updateOneActivity).toHaveBeenCalled(); }); });
EffectiveXf5/joandjane-back
src/destination/schema/destination.schema.ts
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Document } from "mongoose"; export type DestinationDocument = Destination & Document; @Schema() export class Destination { @Prop() title: string; @Prop() img: string; @Prop() numberOfActivities: string; @Prop( { default: Date.now }) createdAt: Date; }; export const DestinationSchema = SchemaFactory.createForClass(Destination);
EffectiveXf5/joandjane-back
src/destination/interface/destination.interface.ts
import { Document } from "mongoose" export interface Destination extends Document { readonly title: string; readonly img: string; readonly numberOfActivities: string; readonly createdAt: Date; }
EffectiveXf5/joandjane-back
src/activity/activity.service.ts
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Activity } from './interfaces/activity.interface'; import { ActivityDTO } from './dto/activity.dto'; @Injectable() export class ActivityService { constructor(@InjectModel('Activity') private readonly activityModel: Model<Activity>){} async getAllActivities(): Promise<Activity[]> { const allActivities = await this.activityModel.find(); return allActivities; } async getOneActivity(activityID: string): Promise<Activity> { const oneActivity = await this.activityModel.findById(activityID); return oneActivity; } async createNewActivity(activityDTO: ActivityDTO): Promise<Activity> { const newActivity = await this.activityModel.create(activityDTO); return newActivity; } async updateOneActivity(activityID: string, activityDTO: ActivityDTO): Promise<Activity> { const activityToUpdate = await this.activityModel.findByIdAndUpdate(activityID, activityDTO, { new: true }); return activityToUpdate; } async deleteOneActivity(activityID: string): Promise<Activity> { const activityToDelete = await this.activityModel.findByIdAndDelete(activityID); return activityToDelete; } };
EffectiveXf5/joandjane-back
src/blog/blog.service.spec.ts
<filename>src/blog/blog.service.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { BlogService } from './blog.service'; import { getModelToken } from '@nestjs/mongoose'; describe('BlogService', () => { let service: BlogService; const mockBlogModel = { create: jest.fn().mockImplementation( dto => dto ), findByIdAndUpdate: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })), findById: jest.fn().mockImplementation( id => id ), findByIdAndDelete: jest.fn().mockImplementation( id => id ), } beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [BlogService, { provide: getModelToken('Blog'), useValue: mockBlogModel }], }).compile(); service = module.get<BlogService>(BlogService); }); it('should be defined', () => { expect(service).toBeDefined(); }); it('should create a new blog', async() => { const dto = { author: 'author', reading_time: '14 horas', title: 'title', img: 'img', description: 'description', createdAt: new Date(Date.now()) } expect(await service.createOneBlog(dto)).toEqual({ author: dto.author, reading_time: dto.reading_time, title: dto.title, img: dto.img, description: dto.description, createdAt: dto.createdAt }) expect(mockBlogModel.create).toHaveBeenCalled(); }) it('should update a new blog', async() => { const dto = { author: 'authorNew', reading_time: '14 horas new', title: 'title new', img: 'img', description: 'description', createdAt: new Date(Date.now()) } expect(await service.updateOneBlog('1', dto)).toEqual({ id: '1', ...dto }) expect(mockBlogModel.findByIdAndUpdate).toHaveBeenCalled(); }) it('should get an unique blog', async() => { const id = '1' expect(await service.getOneBlog(id)).toBeTruthy(); expect(mockBlogModel.findById).toHaveBeenCalled(); }) it('should delete a blog', async() => { expect(await service.deleteOneBlog('id')).toBeTruthy(); expect(mockBlogModel.findByIdAndDelete).toHaveBeenCalled(); }) });
EffectiveXf5/joandjane-back
src/blog/interfaces/blog.interface.ts
import { Document } from 'mongoose' export interface Blog extends Document { readonly author: string; readonly reading_time: string; readonly title: string; readonly img: string; readonly description: string; readonly createdAt: Date; }
EffectiveXf5/joandjane-back
src/destination/destination.module.ts
<gh_stars>0 import { Module } from '@nestjs/common'; import { MongooseModule } from '@nestjs/mongoose'; import { DestinationService } from './destination.service'; import { DestinationSchema } from './schema/destination.schema'; import { DestinationController } from './destination.controller'; @Module({ imports : [ MongooseModule.forFeature([ { name: 'Destination', schema: DestinationSchema } ]) ], providers: [DestinationService], controllers: [DestinationController] }) export class DestinationModule {}
EffectiveXf5/joandjane-back
src/activity/dto/activity.dto.ts
export class ActivityDTO { readonly title: string; readonly price: string; readonly img: string; readonly destination: string[]; readonly type: string[]; readonly sumary: string; readonly duration: string; readonly cancelation: string; readonly instant_confirmation: string; readonly mobile_ticket: boolean; readonly pet_friendly: boolean; readonly experience_details: string; readonly includes: string[]; readonly location: string[]; readonly prepare_experience: string; readonly reviews: object; readonly children: boolean; readonly createdAt: Date; }
EffectiveXf5/joandjane-back
src/activity/activity.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { ActivityService } from './activity.service'; import { getModelToken } from '@nestjs/mongoose'; describe('ActivitiesService', () => { let service: ActivityService; const mockActivityModel = { create: jest.fn().mockImplementation( dto => dto ), findByIdAndUpdate: jest.fn().mockImplementation((id, dto) => ({ id, ...dto })), find: jest.fn().mockImplementation(), findById: jest.fn().mockImplementation( id => id ), findByIdAndDelete: jest.fn().mockImplementation( id => id ), } beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ActivityService, { provide: getModelToken('Activity'), useValue: mockActivityModel }], }).compile(); service = module.get<ActivityService>(ActivityService); }); it('should be defined', () => { expect(service).toBeDefined(); }); it('should create a new activity', async () => { const dto = { title: 'title', price: "12", img: 'img1', destination: ['destination', 'destination'], type: ['type', 'type'], sumary: 'sumary', duration: 'duration', cancelation: 'cancelation', instant_confirmation: "true", mobile_ticket: true, pet_friendly: true, experience_details: 'experience', includes: ['includes', 'includes'], location: ['location', 'location'], prepare_experience: "prepare", reviews: { 1: 'review1', 2: 'review2' }, children: true, createdAt: new Date(Date.now()) } expect(await service.createNewActivity(dto)).toEqual({ title: dto.title, price: dto.price, img: dto.img, destination: dto.destination, type: dto.type, sumary: dto.sumary, duration: dto.duration, cancelation: dto.cancelation, instant_confirmation: dto.instant_confirmation, mobile_ticket: dto.mobile_ticket, pet_friendly: dto.pet_friendly, experience_details: dto.experience_details, includes: dto.includes, location: dto.location, prepare_experience: dto.prepare_experience, reviews: dto.reviews, children: dto.children, createdAt: dto.createdAt }); expect(mockActivityModel.create).toHaveBeenCalled(); }); it('should update an activity', async() => { const dto = { title: 'title', price: "12", img: 'img1', destination: ['destination', 'destination'], type: ['type', 'type'], sumary: 'sumary', duration: 'duration', cancelation: 'cancelation', instant_confirmation: "true", mobile_ticket: true, pet_friendly: true, experience_details: 'experience', includes: ['includes', 'includes'], location: ['location', 'location'], prepare_experience: "prepare", reviews: { 1: 'review1', 2: 'review2' }, children: true, createdAt: new Date(Date.now()) } expect(await service.updateOneActivity('1', dto)).toEqual({ id: '1', ...dto }); expect(mockActivityModel.findByIdAndUpdate).toHaveBeenCalled(); }); /* it('should get an array of articles', async() => { const arrayOfArticles = ({ article: '1', article2: '2' }) expect(await service.getAllActivities()).toEqual(arrayOfArticles) expect(mockActivityModel.find).toHaveBeenCalled(); }); */ it('should get an unique activity', async() => { const id = '1'; expect(await service.getOneActivity(id)).toBeTruthy(); expect(mockActivityModel.findById).toHaveBeenCalled(); }); it('should delete an activity', async() => { expect(await service.deleteOneActivity('id')).toBeTruthy(); expect(mockActivityModel.findByIdAndDelete).toHaveBeenCalled(); }); });
EffectiveXf5/joandjane-back
src/blog/blog.service.ts
<gh_stars>0 import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Blog } from './interfaces/blog.interface'; import { BlogDTO } from './dto/blog.dto'; @Injectable() export class BlogService { constructor(@InjectModel('Blog') private readonly blogModel: Model<Blog>) {} async getAllBlogs(): Promise<Blog[]> { const allBlogs = await this.blogModel.find(); return allBlogs; } async getOneBlog(blogID: string): Promise<Blog> { const oneBlog = await this.blogModel.findById(blogID); return oneBlog; } async createOneBlog(blogDTO: BlogDTO): Promise<Blog> { const newBlog = await this.blogModel.create(blogDTO); return newBlog; } async updateOneBlog(blogID: string, blogDTO: BlogDTO): Promise<Blog> { const blogToUpdate = await this.blogModel.findByIdAndUpdate(blogID, blogDTO, { new: true }); return blogToUpdate; } async deleteOneBlog(blogID: string): Promise<Blog> { const blogToDelete = await this.blogModel.findByIdAndDelete(blogID); return blogToDelete; } }
olujedai/sw-api
src/all-exception.filter.ts
<gh_stars>0 import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common'; @Catch() export class AllExceptionsFilter implements ExceptionFilter { catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const request = ctx.getRequest(); const status: number = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR; let responseMessage: string | string[]; if (status === HttpStatus.INTERNAL_SERVER_ERROR) { responseMessage = 'An error occured. We are working on it. Please try back later.'; } else if (status === HttpStatus.BAD_REQUEST) { responseMessage = Object.values(exception.response.message[0].constraints); } else { responseMessage = exception.response.message; } response.status(status).json({ statusCode: status, message: Array.isArray(responseMessage) === true ? responseMessage[0] : responseMessage, timestamp: new Date().toISOString(), path: request.url, }); } }
olujedai/sw-api
src/character/dto/character.query.dto.ts
<filename>src/character/dto/character.query.dto.ts import { ApiModelProperty } from '@nestjs/swagger'; import { IsOptional, IsIn } from 'class-validator'; /** * Data Transfer Object that defines rules for documenting the query parameters on swagger UI * as well as the rules for validating the queries */ export class CharacterQueryDto { @ApiModelProperty( { description: 'Indicates how the characters will be sorted.', required: false, type: 'string', example: 'sort=gender', enum: ['height', 'name', 'gender'], }, ) @IsOptional() @IsIn(['height', 'name', 'gender']) sort?: 'height' | 'name' | 'gender'; @ApiModelProperty( { description: 'Indicates how the characters will be ordered.', required: false, type: 'string', example: 'order=asc', enum: ['asc', 'desc'], }, ) @IsOptional() @IsIn(['asc', 'desc']) order?: 'asc' | 'desc'; @ApiModelProperty( { description: 'Indicates the filter to be applied to the characters.', required: false, type: 'string', example: 'filter=male', enum: ['male', 'female', 'hermaphrodite', 'n/a', 'none'], }, ) @IsOptional() @IsIn(['male', 'female', 'hermaphrodite', 'n/a', 'none']) filter?: 'male' | 'female' | 'hermaphrodite' | 'n/a' | 'none'; }
olujedai/sw-api
src/comment/dto/comment.dto.ts
import { ApiModelProperty } from '@nestjs/swagger'; import { IsNotEmpty, Length } from 'class-validator'; /** * Comment Data Transfer Object for creating a new movie comment along with the swagger api definition and * field validations are defined here. */ export class CommentBodyDto { @ApiModelProperty( { description: 'A movie viewer\'s comment', required: true, maxLength: 500, type: 'string', }, ) @IsNotEmpty() @Length(1, 500) readonly comment: string; }
olujedai/sw-api
src/character/dto/characters.dto.ts
import { Meta } from './characterMeta.dto'; import { CharacterDto } from './character.dto'; import { ApiModelProperty } from '@nestjs/swagger'; /** * Data transfer object for describing the character response object */ export class CharactersDto { @ApiModelProperty( { description: 'Response metadata', type: Meta, }, ) readonly metadata: Meta; @ApiModelProperty( { description: 'List of characters', type: CharacterDto, }, ) readonly characters: CharacterDto[]; }
olujedai/sw-api
src/movies/movies.validator.ts
<filename>src/movies/movies.validator.ts<gh_stars>0 import { Injectable, NotFoundException } from '@nestjs/common'; import { MoviesService } from './movies.service'; import { MovieDto } from './dto/movies.dto'; /** * Custom validator that checks if a movieId exists */ @Injectable() export class MovieValidator { constructor(private readonly movieService: MoviesService) {} async validateMovieId(movieId: number): Promise<MovieDto> { const movie: MovieDto|null = await this.movieService.getMovie(movieId); if (!movie) { throw new NotFoundException(`Movie ID ${movieId} not found.`); } return movie; } }
olujedai/sw-api
src/movies/dto/remoteMovie.dto.ts
// tslint:disable:variable-name /** * Data Transfer Object for specifying the one movie object */ export interface RemoteMovieObjectDto { readonly title: string; readonly episode_id: number; readonly opening_crawl: string; readonly director: string; readonly producer: string; readonly release_date: string; readonly characters: string[]; readonly planets: string[]; readonly starships: string[]; readonly vehicles: string[]; readonly species: string[]; readonly created: string; readonly edited: string; readonly url: string; }
olujedai/sw-api
src/ormconfig.ts
import { ConnectionOptions } from 'typeorm'; console.log(__dirname); export let config: ConnectionOptions; if (process.env.NODE_ENV !== 'test') { config = { name: 'default', type: 'postgres', host: String(process.env.DATABASE_HOST), port: Number(process.env.DATABASE_PORT), username: String(process.env.DATABASE_USER), password: String(<PASSWORD>), database: String(process.env.DATABASE_NAME), entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: false, migrationsTableName: 'migrations_typeorm', migrationsRun: true, migrations: [__dirname + '/migrations/**/*{.ts,.js}'], cli: { migrationsDir: 'src/migrations', }, }; } else { config = { name: 'test', type: 'postgres', host: String(process.env.DATABASE_HOST), port: Number(process.env.DATABASE_PORT), username: String(process.env.DATABASE_USER), password: String(<PASSWORD>), database: 'sw-api-test-db', entities: ['dist/**/*.entity{.ts,.js}'], dropSchema: true, synchronize: true, }; }
olujedai/sw-api
src/comment/comment.service.ts
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Comment } from './comment.entity'; import { Repository } from 'typeorm'; /** * The methods that provide the logic for interacting with the Comments database table are defined here. */ @Injectable() export class CommentService { constructor( @InjectRepository(Comment) private readonly commentRepository: Repository<Comment>, ) {} async findAll(skip: number, size: number, filter: { movieId: number; }): Promise<[Comment[], number]> { /** * Retrieves all the results that match the query along with a count of the number of results match that query. * @param skip the number of queries to skip. Used for paginating the database response * @param size the number of items to be retrieved from the database * @param filter the filter that should be applied to the database query * @returns the number of responses that match the filter and all the comments that match the query */ return await this.commentRepository.findAndCount({ where: filter, order: { dateCreated: 'DESC', }, skip, take: size || 20, }); } countMovieComments(filter: { movieId: number; }): Promise<number> { /** * Counts the results that match a filter. * @param filter the filter that should be applied to the database query * @returns the number of results that match the filter */ return this.commentRepository.count({ where: filter, }); } createComment(movieId: number, ipAddress: string, comment: string): Promise<Comment> { /** * Creates a comment in the database table and returns the comments * @param movieId the ID of the movie which the comment is for. * @param ipAddress the IP Address of the user posting this comment. * @param comment the comment sent by the user * @param commenter the user posting this comment. * @returns the Comment object. */ const newComment = new Comment(); newComment.movieId = movieId; newComment.ipAddress = ipAddress; newComment.comment = comment; return this.commentRepository.save(newComment); } }
olujedai/sw-api
src/comment/comment.module.ts
import { Module } from '@nestjs/common'; import { CommentService } from './comment.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Comment } from './comment.entity'; import { UtilsModule } from '../utils/utils.module'; /** * The providers, imports and exports of the Comment module are registered here */ @Module({ imports: [TypeOrmModule.forFeature([Comment]), UtilsModule], providers: [CommentService], exports: [CommentService], }) export class CommentModule {}
olujedai/sw-api
src/character/dto/heightMeta.dto.ts
<filename>src/character/dto/heightMeta.dto.ts import { ApiModelProperty } from '@nestjs/swagger'; import { FeetDto } from './feet.dto'; /** * Data Transfer Object for describing the height field in the character metadata */ export class HeightMeta { @ApiModelProperty( { description: 'Height in centimeters', type: 'number', }, ) readonly cm: string; @ApiModelProperty( { description: 'Height in feet', type: FeetDto, }, ) readonly feet: FeetDto; }
olujedai/sw-api
src/request/request.module.ts
import { Module } from '@nestjs/common'; import { RequestService } from './request.service'; /** * The providers exports of the Request module are registered here */ @Module({ providers: [RequestService], exports: [RequestService], }) export class RequestModule {}
olujedai/sw-api
src/character/character.module.ts
<reponame>olujedai/sw-api<filename>src/character/character.module.ts import { Module } from '@nestjs/common'; import { CharacterService } from './character.service'; import { RequestModule } from '../request/request.module'; import { UtilsModule } from '../utils/utils.module'; @Module({ providers: [CharacterService], imports: [RequestModule, UtilsModule], exports: [CharacterService], }) export class CharacterModule {}
olujedai/sw-api
src/comment/comment.service.spec.ts
<gh_stars>0 import { Test, TestingModule } from '@nestjs/testing'; import { CommentService } from './comment.service'; import { getRepositoryToken } from '@nestjs/typeorm'; import { Comment } from './comment.entity'; import { Repository } from 'typeorm'; const testComment: Comment = { movieId: 1, ipAddress: '172.16.17.32', comment: 'Good movie', id: 2, dateCreated: new Date('2019-08-27'), }; const findAndCountResponse: [Comment[], number] = [ [testComment], 1, ]; describe('CommentService', () => { let service: CommentService; let repo: Repository<Comment>; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ CommentService, { // how you provide the injection token in a test instance provide: getRepositoryToken(Comment), // as a class value, Repository needs no generics useClass: Repository, }, ], }).compile(); service = module.get<CommentService>(CommentService); repo = module.get<Repository<Comment>>(getRepositoryToken(Comment)); }); it('should be defined', () => { expect(service).toBeDefined(); expect(repo).toBeDefined(); }); it('should return for findAll', async () => { const skip = 1; const size = 1; const filter = { movieId: 1, }; jest.spyOn(repo, 'findAndCount').mockResolvedValueOnce(findAndCountResponse); expect(await service.findAll(size, skip, filter)).toBe(findAndCountResponse); }); it('should return for count', async () => { const filter = { movieId: 1, }; jest.spyOn(repo, 'count').mockResolvedValueOnce([testComment].length); expect(await service.countMovieComments(filter)).toBe(1); }); it('should create a comment and return created comment', async () => { const movieId = testComment.movieId; const ipAddress = testComment.ipAddress; const comment = testComment.comment; jest.spyOn(service, 'createComment').mockResolvedValueOnce(testComment); expect(await service.createComment(movieId, ipAddress, comment)).toBe(testComment); }); });
olujedai/sw-api
src/movies/movies.controller.ts
<filename>src/movies/movies.controller.ts import { Request } from 'express'; import { Controller, Get, Query, Param, Req, Body, Post, Header } from '@nestjs/common'; import { ApiUseTags, ApiResponse } from '@nestjs/swagger'; import { CommentService } from '../comment/comment.service'; import { CommentBodyDto } from '../comment/dto/comment.dto'; import { CommentResponseDto } from '../comment/dto/commentResponse.dto'; import { Comment } from '../comment/comment.entity'; import { CharacterService } from '../character/character.service'; import { CharactersDto } from '../character/dto/characters.dto'; import { MovieParamDto } from './movies.param.dto'; import { CharacterQueryDto } from '../character/dto/character.query.dto'; import { MoviesService } from './movies.service'; import { MovieDto } from './dto/movies.dto'; import { UtilsService } from '../utils/utils.service'; import { MovieValidator } from './movies.validator'; /* Provides methods for accepting requests and responding to them */ @ApiUseTags('sw-api') @Controller('movies') export class MoviesController { constructor( private readonly movieService: MoviesService, private readonly commentService: CommentService, private readonly characterService: CharacterService, private readonly utilsService: UtilsService, private readonly movieValidator: MovieValidator, ) {} @Get() @ApiResponse({ status: 200, type: [MovieDto]}) async getMovies(): Promise<MovieDto[]> { return await this.movieService.getMovies(); } @Get(':movieId/comments') @ApiResponse({ status: 200, type: CommentResponseDto}) async findAllMovieComments(@Param() param: MovieParamDto, @Query() query: {skip: number, size: number}): Promise<CommentResponseDto> { const movieId: number = param.movieId; await this.movieValidator.validateMovieId(movieId); const { skip, size } = query; const filter: MovieParamDto = { movieId, }; const response: [Comment[], number] = await this.commentService.findAll(skip, size, filter); const comments: Comment[] = response[0]; const count: number = response[1]; return { comments, count, }; } @Post(':movieId/comments') @Header('Content-Type', 'application/json') @ApiResponse({ status: 200, type: Comment}) async saveComment(@Param() param: MovieParamDto, @Req() request: Request, @Body() body: CommentBodyDto): Promise<Comment> { const movieId: number = param.movieId; await this.movieValidator.validateMovieId(movieId); const ipAddress: string = this.utilsService.getIpAddress(request); const {comment} = body; return await this.commentService.createComment(movieId, ipAddress, comment); } @Get(':movieId/characters') @ApiResponse({ status: 200, type: CharactersDto}) async getCharacters(@Param() param: MovieParamDto, @Query() query: CharacterQueryDto): Promise<CharactersDto> { const {sort, order, filter} = query; const movieId: number = param.movieId; await this.movieValidator.validateMovieId(movieId); const movie: MovieDto = await this.movieService.getMovie(movieId); const characters: string[] = movie.characters; return await this.characterService.getCharacters(characters, sort, order, filter); } }
olujedai/sw-api
src/app.controller.ts
<filename>src/app.controller.ts import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; import { ApiUseTags } from '@nestjs/swagger'; @ApiUseTags('server') @Controller('is-alive') export class AppController { constructor(private readonly appService: AppService) {} @Get() getIsAlive(): string { return this.appService.getIsAlive(); } }
olujedai/sw-api
src/movies/movies.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { getRepositoryToken } from '@nestjs/typeorm'; import { MoviesService } from './movies.service'; import { RequestService } from '../request/request.service'; import { UtilsService } from '../utils/utils.service'; import { CommentService } from '../comment/comment.service'; import { Comment } from '../comment/comment.entity'; import * as fs from 'fs'; import { MovieDto } from './dto/movies.dto'; import { RemoteMovieObjectDto } from './dto/remoteMovie.dto'; import { RemoteMoviesObjectDto } from './dto/remoteMovies.dto'; const processedMoviesJson: Buffer = fs.readFileSync(`${__dirname}/static/processedMovies.json`); const processedMovies: MovieDto[] = JSON.parse(processedMoviesJson.toString()); const rawMoviesJson: Buffer = fs.readFileSync(`${__dirname}/static/raw.movies.json`); const rawMovies: RemoteMoviesObjectDto = JSON.parse(rawMoviesJson.toString()); const rawMovieJson = fs.readFileSync(`${__dirname}/static/raw.movie.json`); const rawMovie: RemoteMovieObjectDto = JSON.parse(rawMovieJson.toString()); describe('Movie service', () => { let requestService: RequestService; let commentService: CommentService; let movieService: MoviesService; let utilsService: UtilsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ RequestService, CommentService, { provide: getRepositoryToken(Comment), useValue: {name: ''}, }, MoviesService, UtilsService, ], }).compile(); requestService = module.get<RequestService>(RequestService); commentService = module.get<CommentService>(CommentService); movieService = module.get<MoviesService>(MoviesService); utilsService = module.get<UtilsService>(UtilsService); }); afterAll(() => requestService.closeRedisInstance()); it('should be defined', () => { expect(requestService).toBeDefined(); expect(commentService).toBeDefined(); expect(movieService).toBeDefined(); expect(utilsService).toBeDefined(); }); it('should return a list of processed movies', async () => { jest.spyOn(movieService, 'getMovies').mockResolvedValue(processedMovies); expect(await movieService.getMovies()).toBe(processedMovies); }); it('should return a list of raw movies', async () => { jest.spyOn(movieService, 'getMoviesFromRemote').mockResolvedValue(rawMovies.results); expect(await movieService.getMoviesFromRemote('films')).toBe(rawMovies.results); }); it('should return a single movie', async () => { jest.spyOn(movieService, 'getMovieFromRemote').mockResolvedValue(rawMovie); expect(await movieService.getMovieFromRemote('films/1/')).toBe(rawMovie); }); it('should retrieve the required fields from an external API', async () => { const movie: MovieDto = movieService.retrieveFields(rawMovie); expect(movie).toEqual( expect.objectContaining({ id: expect.any(Number), name: expect.any(String), releaseDate: expect.any(String), openingCrawl: expect.any(String), characters: expect.any(Array), commentCount: expect.any(Number), }), ); }); it('takes in raw movies and returns the procesed result.', async () => { jest.spyOn(movieService, 'getCommentCount').mockResolvedValue(0); let movieArray: MovieDto[] = rawMovies.results.map(movie => movieService.retrieveFields(movie)); movieArray = await movieService.getMovieCommentsAndSort(movieArray); expect(movieArray).toEqual(processedMovies); }); });
olujedai/sw-api
src/comment/comment.entity.ts
<filename>src/comment/comment.entity.ts import { Entity, Column, CreateDateColumn, PrimaryGeneratedColumn } from 'typeorm'; import { ApiModelProperty } from '@nestjs/swagger'; /** * Comment database table definition */ @Entity() export class Comment { @PrimaryGeneratedColumn() @ApiModelProperty( { description: 'The number of comment ID', type: 'number', }, ) id: number; @Column() @ApiModelProperty( { description: 'The ID of the movie', type: 'number', }, ) movieId: number; @Column({ length: 500 }) @ApiModelProperty( { description: 'The comment of the movie', type: 'string', }, ) comment: string; // @Column({ length: 20 }) // @ApiModelProperty( // { // description: 'The name of the comment writer', // type: 'string', // }, // ) // commenter: string; @Column() @ApiModelProperty( { description: 'The IP address of the comment writer', type: 'string', }, ) ipAddress: string; @CreateDateColumn({ type: 'timestamptz' }) @ApiModelProperty( { description: 'The date this comment was stored in the database', type: 'string', }, ) dateCreated: Date; }
olujedai/sw-api
src/main.ts
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { AllExceptionsFilter } from './all-exception.filter'; import { ValidationPipe404 } from './validatation.pipe'; import * as helmet from 'helmet'; import { LoggerService } from './logger/logger.service'; import { useContainer } from 'class-validator'; process.env.TZ = 'UTC'; async function bootstrap() { const app = await NestFactory.create(AppModule); const logger = app.get(LoggerService); app.use(helmet()); app.enableCors(); app.use(logger.logInfo()); app.use(logger.logError()); app.useGlobalFilters(new AllExceptionsFilter()); useContainer(app.select(AppModule), { fallbackOnErrors: true }); app.useGlobalPipes(new ValidationPipe404()); const options = new DocumentBuilder() .setTitle('Star Wars Api') .setDescription('App for communicating with the Star Wars API') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('/docs', app, document); await app.listen(Number(process.env.PORT || 3000)); } bootstrap();
olujedai/sw-api
src/character/character.service.spec.ts
<gh_stars>0 import { Test, TestingModule } from '@nestjs/testing'; import { CharacterService } from './character.service'; import { RequestService } from '../request/request.service'; import { UtilsService } from '../utils/utils.service'; import * as fs from 'fs'; import { CharacterDto } from './dto/character.dto'; import { CharactersDto } from './dto/characters.dto'; import { FeetDto } from './dto/feet.dto'; import { RemoteCharacterObjectDto } from './dto/apiResponse.dto'; const appCharacterJson: Buffer = fs.readFileSync(`${__dirname}/static/appCharacter.json`); const appCharacter: CharacterDto = JSON.parse(appCharacterJson.toString()); const appCharacterListJson: Buffer = fs.readFileSync(`${__dirname}/static/appCharacterList.json`); const appCharacterList: CharacterDto[] = JSON.parse(appCharacterListJson.toString()); const remoteCharacterJson: Buffer = fs.readFileSync(`${__dirname}/static/oneCharacter.json`); const remoteCharacter: RemoteCharacterObjectDto = JSON.parse(remoteCharacterJson.toString()); const remoteCharactersJson: Buffer = fs.readFileSync(`${__dirname}/static/characters.json`); const remoteCharacterList: RemoteCharacterObjectDto[] = JSON.parse(remoteCharactersJson.toString()); const processedCharactersJson: Buffer = fs.readFileSync(`${__dirname}/static/processedCharacters.json`); const processedCharacters: CharactersDto = JSON.parse(processedCharactersJson.toString()); const order: string = 'asc'; let sort: string = 'name'; let filter: string|null|undefined = null; describe('CharacterService', () => { let characterService: CharacterService; let requestService: RequestService; let utilsService: UtilsService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [CharacterService, RequestService, UtilsService], }).compile(); characterService = module.get<CharacterService>(CharacterService); requestService = module.get<RequestService>(RequestService); utilsService = module.get<UtilsService>(UtilsService); }); afterAll(() => requestService.closeRedisInstance()); it('should be defined', () => { expect(characterService).toBeDefined(); expect(requestService).toBeDefined(); expect(utilsService).toBeDefined(); }); it('should sort characters by name', () => { sort = 'name'; const response: CharacterDto[] = characterService.applyCharacterSortAndFilter(appCharacterList, sort, order, filter); expect(response[appCharacterList.length - 1].name).toBe(remoteCharacter.name); expect(response[0].name).toBe('C-3PO'); }); it('should sort characters by gender', () => { sort = 'gender'; const response: CharacterDto[] = characterService.applyCharacterSortAndFilter(appCharacterList, sort, order, filter); expect(response[0].name).toBe('Leia Organa'); }); it('should sort characters by height', () => { sort = 'height'; const response: CharacterDto[] = characterService.applyCharacterSortAndFilter(appCharacterList, sort, order, filter); expect(response[0].name).toBe('Leia Organa'); }); it('should filter characters by gender', () => { filter = 'female'; const response: CharacterDto[] = characterService.applyCharacterSortAndFilter(appCharacterList, sort, order, filter); expect(response[0].name).toBe('Leia Organa'); }); it('should retrieve the character fields we are concerned with', () => { const response: CharacterDto = characterService.retrieveCharacterFields(remoteCharacter); expect(response).toEqual({ name: '<NAME>', gender: 'male', height: 172 }); }); it('should convert centimeters to feet', () => { const response: FeetDto = characterService.convertCmToFeet(184); expect(response).toEqual({ feet: 6, inches: 0 }); }); it('should calculate the height of all the characters in centimeters', () => { const characterList: CharacterDto[] = remoteCharacterList.map(ch => characterService.retrieveCharacterFields(ch)); const response: number = characterService.calculateHeightInCm(characterList); expect(response).toBe(664); }); it('should return the height in feet in the required format', () => { const response: string = characterService.formatFeet({ feet: 6, inches: 0 }); expect(response).toEqual('6ft. 0in.'); }); it('should return the characters in the required format', () => { filter = 'female'; const sortedAndFIlteredCharacters: CharacterDto[] = characterService.applyCharacterSortAndFilter(appCharacterList, sort, order, filter); const response: CharactersDto = characterService.getResponseFormat(sortedAndFIlteredCharacters, sortedAndFIlteredCharacters.length, 200); expect(response.metadata).toEqual({ total: 1, totalHeight: { cm: '200cm', feet: '6ft. 7in.' }}); }); it('should convert a gender string to lowercase', () => { let response: string = characterService.formatGender('MALE'); expect(response).toBe('male'); response = characterService.formatGender('fEmaLE'); expect(response).toBe('female'); }); it('should return true for characters that fit a given gender and false otherwise', () => { let response: boolean = characterService.filterMethod(appCharacter, 'male'); expect(response).toBe(true); response = characterService.filterMethod(appCharacter, 'female'); expect(response).toBe(false); }); it('should return a list of processed characters', async () => { jest.spyOn(characterService, 'getCharactersFromUrls').mockResolvedValue(remoteCharacterList); const characterUrls: string[] = [ 'https://swapi.co/api/people/1/', 'https://swapi.co/api/people/2/', 'https://swapi.co/api/people/3/', 'https://swapi.co/api/people/4/', ]; const response: CharactersDto = await characterService.getCharacters(characterUrls); expect(response.metadata).toEqual(processedCharacters.metadata); expect(response.characters).toEqual(expect.arrayContaining(processedCharacters.characters)); }); it('should return one character', async () => { jest.spyOn(characterService, 'getCharacter').mockResolvedValue(appCharacter); const response: string | CharacterDto = await characterService.getCharacter('https://swapi.co/api/people/1/'); expect(response).toEqual(appCharacter); }); });