repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
maplecloudy/shopizer-admin
src/app/pages/shipping/transferlistbox/transferlistbox.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { stringify } from '@angular/compiler/src/util'; import { ToastrService } from 'ngx-toastr'; import { TranslateService } from '@ngx-translate/core'; import { StorageService } from '../../shared/services/storage.service'; import { SharedService } from '../services/shared.service'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-transferlistbox', templateUrl: './transferlistbox.component.html', styleUrls: ['./transferlistbox.component.scss'] }) export class TransferlistboxComponent implements OnInit { @Input("leftAreaList") leftAreaList: any[]; @Input("rightAreaList") rightAreaList: any[]; @Input("code") code: string; @Input("label") label: string; @Input("leftAreaLabel") leftAreaLabel: string; @Input("rightAreaLabel") rightAreaLabel: string; @Input("leftAreaId") leftAreaId: string; @Input("rightAreaId") rightAreaId: string; toggleButtonClicked = new EventEmitter<Object>(); leftAreaMap: Map<string, any>; rightAreaMap: Map<string, any> = new Map<string, any>(); shipToCountries: string[] = []; store: string; clickEventsubscription: Subscription; /** *alerts component params */ isSrOnly: boolean = true; message: string = ""; ariaLive: string = "polite"; alertsClass = "default"; alertAriaLive: string = "polite"; /** *end of alerts component params */ showDelete: boolean = true; constructor(private toastr: ToastrService, private translate: TranslateService, private storageService: StorageService, private sharedService: SharedService) { this.clickEventsubscription = this.sharedService.getClickEvent().subscribe(() => { this.saveShipToCountries(); }) this.clickEventsubscription = this.sharedService.getStoreEvent().subscribe(data => { this.store = data; this.generateLocalData(); }) } /** * */ ngOnInit() { this.store = this.storageService.getMerchant(); this.generateLocalData(); // this.fetchShipToCountries(); } // Method to fetch selected shipToCountries // fetchShipToCountries() { // this.sharedService.getExpedition(this.store) // .subscribe(data => { // console.log(data) // this.shipToCountries = data.shipToCountry; // // console.log(this.shipToCountries); // this.generateLocalData(); // }, error => { // // this.loadingList = false; // }); // } //save shipToCountries saveShipToCountries() { let selectedCountries = Array.from(this.rightAreaMap.values()); selectedCountries.forEach(item => { this.shipToCountries.push(item.countryCode); }); let param = { "iternationalShipping": true, "shipToCountry": this.shipToCountries } this.sharedService.saveExpedition(this.store, param) .subscribe(data => { this.shipToCountries = []; this.toastr.success(this.translate.instant('SHIPPING.SHIP_TO_COUNTRIES')); }, error => { // this.loadingList = false; }); } /** * Creates a map based on the array information passed. addes additional properties required down the line */ generateLocalData() { if (this.code == null) { throw Error("code attribute is required") }; if (this.label == null) { throw Error("label attribute is required") }; if (this.leftAreaList == null) { throw Error("leftAreaList attribute is required") }; // console.log(this.leftAreaList) this.leftAreaMap = new Map<string, any>(); this.rightAreaMap = new Map<string, any>(); // if (this.shipToCountries.length > 0) { let availableCountries: any[] = this.leftAreaList; this.shipToCountries = this.rightAreaList; let leftAreaListData = availableCountries.filter(o => !this.shipToCountries.find((countryCode) => o.countryCode === countryCode)); let rightAreaListData = availableCountries.filter(o => this.shipToCountries.some((countryCode) => o.countryCode === countryCode)); //filling available countries leftAreaListData.forEach((item) => { this.leftAreaMap.set(item[this.code], item); }); //filling selected countries rightAreaListData.forEach((item) => { this.rightAreaMap.set(item[this.code], item); }); // console.log(this.leftAreaList); // console.log(this.rightAreaList); // this.shipToCountries = []; // } else { // this.leftAreaList.forEach((item) => { // item.selected = false; // this.leftAreaMap.set(item[this.code], item); // }); // this.rightAreaMap = new Map<string, any>(); // } } /** * Sets the items into map * @param wrapperItem */ itemSelectedOrUnSelected(wrapperItem: any) { if (wrapperItem == null) { return; } let item = wrapperItem.item; switch (wrapperItem.componentId) { case this.leftAreaId: this.leftAreaMap.set(item.key, item.value); break; case this.rightAreaId: this.rightAreaMap.set(item.key, item.value); break; default: return; } } /** * Toggles items from left to right */ toggleLeftToRight() { let counter = 0; this.leftAreaMap.forEach((item: any, key: string) => { if (item.selected == true) { item.selected = false; this.rightAreaMap.set(key, item); this.leftAreaMap.delete(key); ++counter; } }); this.updateMessage(this.leftAreaLabel, this.rightAreaLabel, counter); this.toggleButtonClicked.emit({ "componentId": this.leftAreaId }); } /** * Toggles items from Right to Left */ toggleRightToLeft() { let counter = 0; this.rightAreaMap.forEach((item: any, key: string) => { if (item.selected == true) { item.selected = false; this.leftAreaMap.set(key, item); this.rightAreaMap.delete(key); ++counter; } }); this.updateMessage(this.rightAreaLabel, this.leftAreaLabel, counter); this.toggleButtonClicked.emit({ "componentId": this.rightAreaId }); } updateMessage(from: String, to: string, counter: number) { this.message = counter + " item(s) moved from " + from + " to " + to; } }
maplecloudy/shopizer-admin
src/app/pages/auth/forgotpassword/forgot.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit } from '@angular/core'; import { AuthService } from '../services/auth.service'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { Location, PlatformLocation } from '@angular/common'; // import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'ngx-forgot', templateUrl: './forgot.component.html', styleUrls: ['./forgot.component.scss'] }) export class ForgotPasswordComponent implements OnInit { errorMessage = ''; successMessage = ''; isSubmitted: boolean = false; loadingList: boolean = false; user = { email: '', url: '' } constructor( private authService: AuthService, private router: Router, // private toastr: ToastrService, private translate: TranslateService, private location: Location, private platformLocation: PlatformLocation ) { } ngOnInit() { console.log(this.location.prepareExternalUrl('/')); } onKeyUp() { this.isSubmitted = false; } goToLogin() { this.router.navigate(['auth']); } onSubmit() { this.loadingList = true; this.errorMessage = ''; this.successMessage = ''; this.isSubmitted = true; this.user.url = (this.platformLocation as any).location.origin + this.location.prepareExternalUrl('/') this.authService.forgot(this.user.email, this.user.url) .subscribe(res => { this.loadingList = false; this.user.email = ''; this.successMessage = this.translate.instant('FORGOT_PASSWORD.SENT_LINK'); }, err => { this.loadingList = false; this.errorMessage = this.translate.instant('FORGOT_PASSWORD.USER_NOT_FOUND'); }); } }
maplecloudy/shopizer-admin
src/app/pages/store-management/store-creation/store-creation.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'ngx-store-creation', templateUrl: './store-creation.component.html', styleUrls: ['./store-creation.component.scss'] }) export class StoreCreationComponent implements OnInit { store: any; constructor() { } ngOnInit() { } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/options/options.module.ts
<filename>src/app/pages/catalogue/options/options.module.ts import { NgModule } from '@angular/core'; import { SharedModule } from '../../shared/shared.module'; import { OptionComponent } from './option/option.component'; import { OptionValuesComponent } from './option-values/option-values.component'; import { OptionsListComponent } from './options-list/options-list.component'; import { OptionsValuesListComponent } from './options-values-list/options-values-list.component'; import { OptionsRoutingModule } from './options-routing.module'; import { OptionsComponent } from './options.component'; import { OptionValueImageComponent } from './option-value-image/option-value-image.component'; import { OptionsSetListComponent } from './options-set-list/options-set-list.component'; import { OptionSetComponent } from './options-set/option-set.component'; import { CustomModule } from '../../custom-component/custom.module'; import { VariationsListComponent } from './variations/variations.component'; import { AddVariationsComponent } from './variations/add-variations.component'; @NgModule({ declarations: [ OptionsComponent, OptionComponent, OptionsListComponent, OptionValuesComponent, OptionsValuesListComponent, OptionValueImageComponent, OptionsSetListComponent, OptionSetComponent, VariationsListComponent, AddVariationsComponent ], imports: [ OptionsRoutingModule, SharedModule, CustomModule ] }) export class OptionsModule { }
maplecloudy/shopizer-admin
src/app/pages/shipping/rules/rules.component.ts
import { Component, OnInit } from '@angular/core'; import { QueryBuilderConfig } from 'angular2-query-builder'; import { Router } from '@angular/router'; import { SharedService } from '../services/shared.service'; import { error } from '@angular/compiler/src/util'; import { StoreService } from '../../store-management/services/store.service'; import * as moment from 'moment'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'ngx-rules', templateUrl: './rules.component.html', styleUrls: ['./rules.component.scss'] }) export class RulesComponent implements OnInit { query = { condition: 'and', rules: [ ] }; stores = []; codeExits: boolean; rules = { id: '', enabled: false, code: '', name: '', // timeBased: '', startDate: new Date(), endDate: new Date(), order: 0, store: '', selected_result: '', } actionsData: Array<any> = []; selectedActionsData: Array<any> = []; config: QueryBuilderConfig; rules_time: boolean = false; loadingList: boolean = false shippingResult: Array<any> = []; resultData: Array<any> = []; selectedResult: any; title: any = 'Add Rules' buttonText: any = 'Submit' constructor( private sharedService: SharedService, private storeService: StoreService, public router: Router, private toastr: ToastrService ) { this.getStoreList(); //this.getShippingCondition() this.getRulesCriterias() this.getRulesActions() } ngOnInit() { if (localStorage.getItem('rulesCode')) { // setTimeout(() => { this.sharedService.getShippingRulesDetails(localStorage.getItem('rulesCode')) .subscribe(rulesData => { // let rulesData = JSON.parse(localStorage.getItem('rulesCode')) console.log(rulesData) this.title = 'Update Rules' this.buttonText = 'Update' let j = this.stores.find(x => x.code === rulesData.store); this.rules = rulesData setTimeout(() => { console.log(rulesData.store) this.rules.store = rulesData.store }, 3000); this.rules.endDate = rulesData.endDate && new Date(rulesData.endDate) this.rules.startDate = rulesData.startDate && new Date(rulesData.startDate) this.query = rulesData.ruleSets[0]; // console.log(this.actionsData);\ let array1 = this.actionsData var array3 = array1.filter(function (obj) { return rulesData.actions.find((a) => { if (a.value) { obj.value = a.value return a.code === obj.code } }); }); this.selectedActionsData = array3; }, error => { }); // }, 3000); } } getStoreList() { this.storeService.getListOfMerchantStoreNames({ 'store': '' }) .subscribe(res => { // console.log(res); res.forEach((store) => { this.stores.push({ value: store.code, label: store.code }); }); }); } onChangeCode(e) { this.sharedService.checkCode(e.target.value) .subscribe(res => { console.log(res); this.codeExits = true; }, error => { console.log(error); this.codeExits = false; }); } getRulesCriterias() { let fields = {} this.sharedService.getRulesCriterias() .subscribe(data => { // console.log(data) data.map((value) => { fields[value.code] = { "name": value.name, // "type": value.options.length > 0 ? 'category' : value.format == 'DECIMAL' || value.format == 'NUMERIC' ? 'number' : value.format.toLowerCase(), "type": value.criteriaType == 'text' ? 'string' : 'string', "operators": value.operators, "options": [] } // value.options.map((opt) => { // fields[value.code].options.push({ name: opt.name, value: opt.value }) // }) }); this.config = { fields }; }); } getRulesActions() { this.sharedService.getRulesActions() .subscribe(data => { // console.log(data); this.actionsData = data }); } goToback() { this.router.navigate(['/pages/shipping/rules']); } onAddActions(actions) { console.log('onAddActions') console.log(actions) actions.value = '' this.selectedActionsData.push(actions) } onDeleteIcon(index) { this.selectedActionsData.splice(index, 1); } onSubmit() { this.loadingList = true; console.log(this.query) let actions = []; this.actionsData.map((value) => { actions.push({ code: value.code, value: value.value }) }); let querys = { condition: this.query.condition, rules: [] }; this.query.rules.map((q) => { if (typeof q.value === 'string' || q.value instanceof String) { querys.rules.push({ field: q.field, operator: q.operator, value: [q.value] }) } else { querys.rules.push({ field: q.field, operator: q.operator, value: q.value }) } }); let param = { "name": this.rules.name, "code": this.rules.code, "store": this.rules.store, "enabled": this.rules.enabled, "startDate": moment(this.rules.startDate).utc(), "endDate": moment(this.rules.endDate).utc(), "actions": actions, "ruleSets": [ querys ] } console.log(param); if (this.buttonText === 'Submit') { this.sharedService.createShippingRules(param) .subscribe(data => { console.log(data); this.loadingList = false; this.toastr.success('Rules has been added successfully'); this.goToback() }, error => { this.toastr.error('Rules has been added fail.'); this.loadingList = false; }); } else { this.sharedService.updateShippingRules(this.rules.id, param) .subscribe(data => { console.log(data); this.loadingList = false; this.toastr.success('Rules has been updated successfully'); this.goToback() }, error => { this.toastr.error('Rules has been updated fail.'); this.loadingList = false; }); } } // getShippingCondition() { // this.loadingList = true; // let fields = {} // this.sharedService.getRulesCondition() // .subscribe(data => { // // console.log(data) // data.map((value) => { // fields[value.code] = { // "name": value.name, // "type": value.options.length > 0 ? 'category' : value.format == 'DECIMAL' || value.format == 'NUMERIC' ? 'number' : value.format.toLowerCase(), // "operators": value.operators, // "options": [] // } // value.options.map((opt) => { // fields[value.code].options.push({ name: opt.name, value: opt.value }) // }) // }); // // config: QueryBuilderConfig = { fields: {} } // // console.log(fields); // this.config = { fields }; // this.loadingList = false; // // this.source.load(data); // }, error => { // this.loadingList = false; // }); // this.getShippingResult(); // } // getShippingResult() { // this.sharedService.getRulesResult() // .subscribe(data => { // // console.log(data); // this.shippingResult = data; // }, error => { // }); // this.getShippingRulesDetails() // } // getShippingRulesDetails() { // if (localStorage.getItem('rulesCode')) { // this.sharedService.getShippingRulesDetails(localStorage.getItem('rulesCode')) // .subscribe(data => { // console.log(data) // this.rules = data; // this.rules.startDate = new Date(data.startDate) // this.rules.endDate = new Date(data.endDate) // this.resultData = data.results; // this.query = data.conditions[0] // }, error => { // }); // } // } onClickConfigure() { // console.log(this.selected_result); this.selectedResult = this.rules.selected_result } }
maplecloudy/shopizer-admin
src/app/pages/shared/models/description.ts
export class Description { id?: number; language: string; name: string; highlights?: string; friendlyUrl?: string; description?: string; title?: string; keyWords?: string; metaDescription?: string; }
maplecloudy/shopizer-admin
src/app/pages/catalogue/products-groups/groups-list/active-button.component.ts
import { Component, Input } from '@angular/core'; import { ProductGroupsService } from '../services/product-groups.service'; @Component({ template: `<input type="checkbox" [checked]="value" (click)="clicked() "/>`, }) export class ActiveButtonComponent { @Input() value: boolean; @Input() rowData: any; constructor( private productGroupsService: ProductGroupsService ) { } clicked() { this.value = !this.value; const group = { active: this.value, code: this.rowData.code, }; this.productGroupsService.updateGroupActiveValue(group) .subscribe(res => { }); } }
maplecloudy/shopizer-admin
src/app/pages/tax-management/tax-class/add.component.ts
<filename>src/app/pages/tax-management/tax-class/add.component.ts<gh_stars>10-100 import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; // import { SharedService } from '../services/shared.service'; import { ToastrService } from 'ngx-toastr'; import { TaxService } from '../services/tax.service'; @Component({ selector: 'ngx-tax-class-add', templateUrl: './add.component.html', styleUrls: ['./add.component.scss'], }) export class TaxClassAddComponent implements OnInit { tax = { id: '', code: '', name: '' } loadingList: boolean = false; codeExits: boolean = false; isUpdated: boolean = false; taxClassID: any; isUpdate: boolean = false; constructor( // private sharedService: SharedService, private toastr: ToastrService, private router: Router, private taxService: TaxService ) { } ngOnInit() { if (localStorage.getItem('classId')) { this.taxClassID = localStorage.getItem('classId') this.getTaxClassDetail(); this.isUpdate = true; } } getTaxClassDetail() { this.loadingList = true; this.taxService.getTaxClassesDetails(this.taxClassID) .subscribe(data => { this.loadingList = false; console.log(data) this.tax = data; }, error => { this.loadingList = false; }); } focusOutFunction() { this.taxService.getUniqueTax(this.tax.code) .subscribe(data => { console.log(data) this.codeExits = data.exists; }, error => { // this.source.load([]); }); } // onSelectStore(event) { // } // getPackagesDetails() { // this.sharedService.getPackagingDetails(localStorage.getItem('packagesID')) // .subscribe(res => { // console.log(res); // this.packages = res; // res.type === 'BOX' ? this.packages.type = true : this.packages.type = false // this.loadingList = false; // }, error => { // this.loadingList = false; // }); // } save() { this.loadingList = true; let param = { code: this.tax.code, name: this.tax.name } this.taxService.addTaxClasses(param) .subscribe(res => { this.loadingList = false; this.toastr.success("Tax classes has been added successfully"); this.router.navigate(['pages/tax-management/classes-list']); }, error => { this.loadingList = false; }); } update() { this.loadingList = true; let param = { code: this.tax.code, name: this.tax.name } this.taxService.updateTaxClasses(this.tax.id, param) .subscribe(res => { this.loadingList = false; this.toastr.success("Tax classes has been updated successfully"); this.router.navigate(['pages/tax-management/classes-list']); }, error => { this.loadingList = false; this.toastr.success("Tax classes has been updated fail"); }); } goBack() { this.router.navigate(['pages/tax-management/classes-list']); } }
maplecloudy/shopizer-admin
src/app/pages/content/boxes/add-box.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { LocalDataSource } from 'ng2-smart-table'; import { CrudService } from '../../shared/services/crud.service'; import { ActivatedRoute, Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; import { ImageBrowserComponent } from '../../../@theme/components/image-browser/image-browser.component'; import { NbDialogService } from '@nebular/theme'; import { validators } from '../../shared/validation/validators'; import { TranslateService } from '@ngx-translate/core'; import { ConfigService } from '../../shared/services/config.service'; import { forkJoin } from 'rxjs'; import { Description } from '../../shared/models/description'; declare var jquery: any; declare var $: any; @Component({ selector: 'add-box', templateUrl: './add-box.component.html', styleUrls: ['./add-box.component.scss'], }) export class AddBoxComponent implements OnInit { loader = false; form: FormGroup; content: any; languages = []; uniqueCode: string;//identifier fromroute isCodeExists = false; action: any = 'save' //default selected lang defaultLanguage = localStorage.getItem('lang'); //changed from seo section currentLanguage = localStorage.getItem('lang'); uploadData = new FormData(); description: Array<any> = [] page = { visible: false, mainmenu: false, code: '', order: '', } config = { placeholder: '', tabsize: 2, height: 195, toolbar: [ ['misc', ['codeview', 'fullscreen', 'undo', 'redo']], ['style', ['bold', 'italic', 'underline', 'clear']], ['font', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']], ['fontsize', ['fontname', 'fontsize', 'color']], ['para', ['style', 'ul', 'ol', 'height']], ['insert', ['table', 'link', 'video']], ['customButtons', ['testBtn']] ], buttons: { 'testBtn': this.customButton.bind(this) }, fontNames: ['Helvetica', 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Roboto', 'Times'] }; params = this.param(); public scrollbarOptions = { axis: 'y', theme: 'minimal-dark' }; constructor( private fb: FormBuilder, private crudService: CrudService, public router: Router, private toastr: ToastrService, private configService: ConfigService, private dialogService: NbDialogService, private activatedRoute: ActivatedRoute, private translate: TranslateService ) { } param() { return { store: localStorage.getItem('merchant'), lang: "_all" }; } ngOnInit() { this.loader = true; this.uniqueCode = this.activatedRoute.snapshot.paramMap.get('code'); this.createForm(); const languages = this.configService.getListOfSupportedLanguages(localStorage.getItem('merchant')) .subscribe((languages) => { this.languages = [...languages]; this.addFormArray();//create array if (this.uniqueCode != null) { this.action = 'edit'; this.loadContent(); } else { this.loader = false; } }, error => { this.toastr.error(error.error.message); this.loader = false; }); } private loadContent() { const box = this.crudService.get('/v1/private/content/boxes/' + this.uniqueCode, this.param()).subscribe(data => { this.content = data; this.fillForm(); this.loader = false; }); } private createForm() { this.form = this.fb.group({ id: 0, code: ['', [Validators.required, Validators.pattern(validators.alphanumeric)]], visible: [false], selectedLanguage: [this.defaultLanguage, [Validators.required]], descriptions: this.fb.array([]), }); } private addFormArray() { const control = <FormArray>this.form.controls.descriptions; this.languages.forEach(lang => { control.push( this.fb.group({ language: [lang.code, [Validators.required]], description: [''], name: [''], title: [''], id: 0 }) ); }); } private fillForm() { this.form.patchValue({ id: this.content.id, code: this.content.code, visible: this.content.visible, selectedLanguage: this.defaultLanguage, descriptions: [], }); this.fillFormArray(); this.findInvalidControls(); } private fillFormArray() { this.form.value.descriptions.forEach((desc, index) => { if (this.content != null && this.content.descriptions) { this.content.descriptions.forEach((description) => { if (desc.language === description.language) { (<FormArray>this.form.get('descriptions')).at(index).patchValue({ id: description.id, language: description.language, description: description.description, name: description.name, title: description.title }); } }); } }); } private checkCode(event) { //check if box code already exists const code = event.target.value.trim(); this.crudService.get('/v1/private/content/box/' + code + '/exists', this.param()) .subscribe(res => { this.isCodeExists = res.exists; }); } private save() { this.form.markAllAsTouched(); if (this.findInvalidControls().length > 0) { return; } this.loader = true; //manouver resulting object var object = this.form.value; //remove un necessary delete object.selectedLanguage; /** * TODO revise put in utility */ const tmpObj = { name: '', friendlyUrl: '' }; object.descriptions.forEach((el) => { if (el.name === '') { el.name = object.code; } }); // check required fields if (tmpObj.name === '' || tmpObj.friendlyUrl === '' || object.code === '') { } else { object.descriptions.forEach((el) => { // fill empty fields for (const elKey in el) { if (el.hasOwnProperty(elKey)) { if (el[elKey] === '' && tmpObj[elKey] !== '') { el[elKey] = tmpObj[elKey]; } } } }); // check for undefined object.descriptions.forEach(el => { for (const elKey in el) { if (el.hasOwnProperty(elKey)) { el.name = el.name.trim(); // trim name if (typeof el[elKey] === 'undefined') { el[elKey] = ''; } } } }); } /** let errors = this.findInvalidControls(); if (errors.length > 0) { this.toastr.error(this.translate.instant('COMMON.FILL_REQUIRED_FIELDS')); return; } **/ //for debugging //console.log(JSON.stringify(categoryObject)); //return; //console.log('Content saved ' + JSON.stringify(object)); if (object.id > 0) {//update //set content name required field this.crudService.put('/v1/private/content/box/' + this.content.id, object, this.param()) .subscribe(data => { this.loader = false; this.toastr.success(this.translate.instant('CONTENT.CONTENT_UPDATED')); this.router.navigate(['/pages/content/boxes/list']); }, error => { this.toastr.error(error.error.message); this.loader = false; }); } else { this.crudService.post('/v1/private/content/box', object) .subscribe(data => { this.loader = false; this.toastr.success(this.translate.instant('PRODUCT.PRODUCT_UPDATED')); this.router.navigate(['/pages/content/boxes/list']); }, error => { this.toastr.error(error.error.message); this.loader = false; }); } this.loader = false; } public findInvalidControls() { const invalid = []; const controls = this.form.controls; for (const name in controls) { if (controls[name].invalid) { invalid.push(name); } } return invalid; } get code() { return this.form.get('code'); } get descriptions(): FormArray { return <FormArray>this.form.get('descriptions'); } get selectedLanguage() { return this.form.get('selectedLanguage'); } selectLanguage(lang) { this.form.patchValue({ selectedLanguage: lang, }); this.currentLanguage = lang; } goToback() { this.router.navigate(['/pages/content/boxes/list']); } customButton(context) { const me = this; const ui = $.summernote.ui; const button = ui.button({ contents: '<i class="note-icon-picture"></i>', tooltip: 'Gallery', container: '.note-editor', className: 'note-btn', click: function () { me.dialogService.open(ImageBrowserComponent, {}).onClose.subscribe(name => name && context.invoke('editor.pasteHTML', '<img src="' + name + '">')); } }); return button.render(); } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/options/option-value-image/option-value-image.component.ts
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core'; @Component({ selector: 'ngx-option-value-image', templateUrl: './option-value-image.component.html', styleUrls: ['./option-value-image.component.scss'] }) export class OptionValueImageComponent implements OnInit, OnChanges { @Input() imageUrl; @Output() imageChanged = new EventEmitter<any>(); image: any = {}; constructor() { } ngOnInit() { } ngOnChanges(changes: SimpleChanges) { if (!changes.imageUrl.previousValue && changes.imageUrl.currentValue) { this.image.url = this.imageUrl; } } onSelectFile(event) { const reader = new FileReader(); reader.onload = (e) => { const fileReader = e.target as FileReader; this.image = { name: event.target.files[0].name, url: fileReader.result as string, file: event.target.files[0] }; this.imageChanged.emit({ type: 'add', data: event.target.files[0] }); }; reader.readAsDataURL(event.target.files[0]); } removeImage() { this.image = {}; this.imageChanged.emit({ type: 'remove' }); } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/catalogue-routing.module.ts
<filename>src/app/pages/catalogue/catalogue-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CatalogueComponent } from './catalogue.component'; import { MarketplaceGuard } from '../shared/guards/marketplace.guard'; const routes: Routes = [{ path: '', component: CatalogueComponent, children: [ { path: 'categories', canActivate: [MarketplaceGuard], loadChildren: 'app/pages/catalogue/categories/categories.module#CategoriesModule' }, { path: 'products', loadChildren: 'app/pages/catalogue/products/products.module#ProductsModule' }, { path: 'brands', loadChildren: 'app/pages/catalogue/brands/brands.module#BrandsModule' }, { path: 'catalogues', loadChildren: 'app/pages/catalogue/catalogues/catalogues.module#CataloguesModule' }, { path: 'products-groups', loadChildren: 'app/pages/catalogue/products-groups/products-groups.module#ProductsGroupsModule' }, { path: 'options', loadChildren: 'app/pages/catalogue/options/options.module#OptionsModule' }, { path: 'types', loadChildren: 'app/pages/catalogue/types/types.module#TypesModule' }, ] }]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class CatalogueRoutingModule { }
maplecloudy/shopizer-admin
src/app/pages/shared/services/country.service.ts
import 'rxjs/Rx'; import { map } from 'rxjs/operators';// This is where I import map operator import { Injectable } from '@angular/core'; import { Observable } from "rxjs/Rx" import { HttpClient } from '@angular/common/http'; // import { Http, Response } from "@angular/http" import { CrudService } from './crud.service'; import { Country } from '../models/country'; import { environment } from '../../../../environments/environment'; @Injectable({ providedIn: 'root' }) export class CountryService { url = environment.apiUrl; constructor( private crudService: CrudService, private http: HttpClient ) { } // getListOfCountriesByLanguage(lang: string): Observable<Country[]> { getListOfCountriesByLanguage(lang: string) { //const params = { // 'lang': lang, //}; /** return this.crudService.get(`/v1/country`, params).pipe( map((data: any[]) => data.map((country: any) => new Country( country.id, country.code, country.name, country.zones ))) ); **/ // let countryUrl = this.url + `/v1/country?lang=` + lang; // return this.http.get(countryUrl) // .map(res => res) // .publishReplay(1) // this tells Rx to cache the latest emitted value // .refCount(); // and this tells Rx to keep the Observable alive as long as there are any Subscribers //return this.crudService.get(`/v1/country`, params) //.map(res => res.json()) //.publishReplay(1) // this tells Rx to cache the latest emitted value //.refCount(); // and this tells Rx to keep the Observable alive as long as there are any Subscribers } /** getCountry(lang, code) : Observable<Country> { //let c = this.getListOfCountriesByLanguage(lang) // .subscribe(countries => countries.find(country => country.code == code)); let d = this.getListOfCountriesByLanguage(lang) .map(countries => countries.find(country => country.code == code)); return d } **/ }
maplecloudy/shopizer-admin
src/app/pages/catalogue/options/services/option.service.ts
import { Injectable } from '@angular/core'; import { CrudService } from '../../../shared/services/crud.service'; import { Observable } from 'rxjs'; import { StorageService } from '../../../shared/services/storage.service'; @Injectable({ providedIn: 'root' }) export class OptionService { constructor( private crudService: CrudService, private storageService: StorageService ) { } getListOfOptions(params): Observable<any> { return this.crudService.get(`/v1/private/product/options`, params); } createOption(option): Observable<any> { return this.crudService.post(`/v1/private/product/option`, option); } updateOption(id, option): Observable<any> { return this.crudService.put(`/v1/private/product/option/${id}`, option); } deleteOption(id): Observable<any> { return this.crudService.delete(`/v1/private/product/option/${id}`); } getOptionById(id): Observable<any> { const params = { lang: '_all' }; return this.crudService.get(`/v1/private/product/option/${id}`, params); } checkOptionCode(code): Observable<any> { const params = { 'code': code, }; return this.crudService.get(`/v1/private/product/option/unique`, params); } // Set option API getListOfOptionsSet(): Observable<any> { const params = { store: this.storageService.getMerchant(), lang: this.storageService.getLanguage() }; return this.crudService.get('/v1/private/product/property/set',params); } deleteOptionSet(id): Observable<any> { const reqparams = { store: this.storageService.getMerchant(), lang: this.storageService.getLanguage() }; return this.crudService.delete(`/v1/private/product/property/set/${id}`, reqparams); } checkOptionSetCode(code): Observable<any> { return this.crudService.get('/v1/private/product/property/set/unique?code=' + code); } createSetOption(req): Observable<any> { const reqparams = { store: this.storageService.getMerchant(), lang: this.storageService.getLanguage() }; return this.crudService.post('/v1/private/product/property/set', req, reqparams); } getOptionSetById(id, params): Observable<any> { return this.crudService.get(`/v1/private/product/property/set/${id}`, params); } updateSetOption(id, param): Observable<any> { const reqparams = { store: this.storageService.getMerchant(), lang: this.storageService.getLanguage() }; return this.crudService.put(`/v1/private/product/property/set/${id}`, param, reqparams); } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/brands/brands-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { BrandsComponent } from './brands.component'; import { BrandCreationComponent } from './brand-creation/brand-creation.component'; import { BrandDetailsComponent } from './brand-details/brand-details.component'; import { BrandsListComponent } from './brands-list/brands-list.component'; const routes: Routes = [ { path: '', component: BrandsComponent, children: [ { path: 'create-brand', component: BrandCreationComponent, }, { path: 'brands-list', component: BrandsListComponent, }, { path: 'brand/:id', component: BrandDetailsComponent, }, ], } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class BrandsRoutingModule { }
maplecloudy/shopizer-admin
src/app/pages/payment/methods/methods.component.ts
<reponame>maplecloudy/shopizer-admin import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core'; import { PaymentService } from '../services/payment.service'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { error } from '@angular/compiler/src/util'; @Component({ selector: 'ngx-payment-methods', templateUrl: './methods.component.html', styleUrls: ['./methods.component.scss'] }) export class PaymentMethodsComponent implements OnInit { loadingList = false; paymentData: Array<any> = []; constructor( private paymentService: PaymentService, private router: Router, private translate: TranslateService, ) { this.getPaymentMethodsList() } ngOnInit() { } getPaymentMethodsList() { this.loadingList = true; this.paymentService.getPaymentModules() .subscribe(data => { console.log(data); this.loadingList = false; this.paymentData = data; }, error => { this.loadingList = false; }); } onClickConfigure(value) { this.router.navigate(['pages/payment/configure/' + value]); } }
maplecloudy/shopizer-admin
src/app/pages/payment/payment.module.ts
import { NgModule } from '@angular/core'; import { PaymentComponent } from './payment.component'; import { PaymentRoutingModule } from './payment-routing.module'; import { SharedModule } from '../shared/shared.module'; import { NbDialogModule } from '@nebular/theme'; import { MalihuScrollbarModule } from 'ngx-malihu-scrollbar'; import { CustomModule } from '../custom-component/custom.module'; import { NgxSummernoteModule } from 'ngx-summernote'; import { PaymentMethodsComponent } from './methods/methods.component'; import { ConfigureComponent } from './configure-form/configure.component'; @NgModule({ declarations: [ PaymentComponent, PaymentMethodsComponent, ConfigureComponent ], entryComponents: [ ], imports: [ PaymentRoutingModule, SharedModule, CustomModule, NbDialogModule.forChild(), MalihuScrollbarModule.forRoot(), NgxSummernoteModule ] }) export class PaymentModule { }
maplecloudy/shopizer-admin
src/app/pages/catalogue/categories/categories.module.ts
<reponame>maplecloudy/shopizer-admin<filename>src/app/pages/catalogue/categories/categories.module.ts import { NgModule } from '@angular/core'; import { CategoriesComponent } from './categories.component'; import { CategoriesRoutingModule } from './categories-routing.module'; import { SharedModule } from '../../shared/shared.module'; import { CategoryCreationComponent } from './category-creation/category-creation.component'; import { CategoriesListComponent } from './categories-list/categories-list.component'; import { CategoriesHierarchyComponent } from './categories-hierarchy/categories-hierarchy.component'; import { ButtonRenderComponent } from './categories-list/button-render.component'; import { CategoryFormComponent } from './category-form/category-form.component'; import { CategoryDetailComponent } from './category-detail/category-detail.component'; import { NgxSummernoteModule } from 'ngx-summernote'; import { NbDialogModule } from '@nebular/theme'; import { TreeModule, TreeDraggedElement } from 'angular-tree-component'; @NgModule({ declarations: [ CategoriesComponent, CategoryCreationComponent, CategoriesListComponent, CategoriesHierarchyComponent, ButtonRenderComponent, CategoryFormComponent, CategoryDetailComponent, ], imports: [ CategoriesRoutingModule, SharedModule, NgxSummernoteModule, NbDialogModule.forChild(), TreeModule ], entryComponents: [ButtonRenderComponent], providers: [TreeDraggedElement] }) export class CategoriesModule { }
maplecloudy/shopizer-admin
src/app/pages/content/upload/upload.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, Input } from '@angular/core'; @Component({ selector: 'upload', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent { files: File[] = []; validDrag: Boolean; @Input() multi: string @Input() onUpload = (files: File[]) => { }; onFilesChange() { this.onUpload([...this.files]); this.files.length = 0; } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/options/services/option-values.service.ts
<gh_stars>10-100 import { Injectable } from '@angular/core'; import { CrudService } from '../../../shared/services/crud.service'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class OptionValuesService { constructor( private crudService: CrudService ) { } getListOfOptionValues(params): Observable<any> { return this.crudService.get(`/v1/private/product/options/values`, params); } deleteOptionValue(id): Observable<any> { return this.crudService.delete(`/v1/private/product/option/value/${id}`); } getOptionValueById(id): Observable<any> { const params = { lang: '_all' }; return this.crudService.get(`/v1/private/product/option/value/${id}`, params); } createOptionValue(option): Observable<any> { return this.crudService.post(`/v1/private/product/option/value`, option); } updateOptionValue(id, option): Observable<any> { return this.crudService.put(`/v1/private/product/option/value/${id}`, option); } checkOptionValueCode(code): Observable<any> { const params = { 'code': code, }; return this.crudService.get(`/v1/private/product/option/value/unique`, params); } }
maplecloudy/shopizer-admin
src/app/pages/orders/orders-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { OrdersComponent } from './orders.component'; import { OrderListComponent } from './order-list/order-list.component'; import { NotFoundComponent } from '../shared/components/not-found/not-found.component'; import { OrderDetailsComponent } from './order-details/order-details.component'; const routes: Routes = [ { path: '', component: OrdersComponent, children: [ { path: '', redirectTo: 'order-list', pathMatch: 'full', }, { path: 'order-list', component: OrderListComponent, }, { path: 'order-details', component: OrderDetailsComponent, }, { path: '**', component: NotFoundComponent } ], } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class OrdersRoutingModule { }
maplecloudy/shopizer-admin
src/app/pages/store-management/retailer/retailer.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit } from '@angular/core'; import { StoreService } from '../services/store.service'; @Component({ selector: 'ngx-retailer', templateUrl: './retailer.component.html', styleUrls: ['./retailer.component.scss'] }) export class RetailerComponent implements OnInit { store: any = {}; loading = false; constructor( private storeService: StoreService, ) { } ngOnInit() { this.loading = true; const code = localStorage.getItem('merchant'); this.storeService.getStore(code) .subscribe(res => { this.store = res; this.loading = false; }); } }
maplecloudy/shopizer-admin
src/app/pages/store-management/models/social-networks.ts
export class SocialNetworks { id: number; active: boolean; key: string; value: string; type: string; }
maplecloudy/shopizer-admin
src/app/pages/user-management/user-profile/user-profile.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { UserService } from '../../shared/services/user.service'; import { User } from '../../shared/models/user'; @Component({ selector: 'ngx-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.scss'] }) export class UserProfileComponent implements OnInit { form: FormGroup; user: User; loading = false; constructor( private userService: UserService, ) { } ngOnInit() { this.loading = true; this.userService.getUserProfile() .subscribe(user => { this.user = user; this.loading = false; }); } }
maplecloudy/shopizer-admin
src/app/pages/catalogue/products/inventory/inventory-details/inventory-details.component.ts
<reponame>maplecloudy/shopizer-admin import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { InventoryService } from '../../services/inventory.service'; @Component({ selector: 'ngx-inventory-details', templateUrl: './inventory-details.component.html', styleUrls: ['./inventory-details.component.scss'] }) export class InventoryDetailsComponent implements OnInit { inventory = {}; constructor( private activatedRoute: ActivatedRoute, private inventoryService: InventoryService ) { const productId = this.activatedRoute.snapshot.paramMap.get('productId'); const inventoryId = this.activatedRoute.snapshot.paramMap.get('inventoryId'); this.inventoryService.getInventoryById(productId, inventoryId).subscribe((res) => { this.inventory = { ...res }; }); } ngOnInit() { } }
zhangyuannie/typeddeque
mod.ts
export * from "./Uint8Deque.ts";
zhangyuannie/typeddeque
Uint8Deque.ts
/** A variable length array of 8-bit unsigned integers. */ export class Uint8Deque { #chunks: Uint8Array[] = []; #length = 0; /** * Returns a number value of the element size. `1` in the case of an * `Uint8Deque`. */ static get BYTES_PER_ELEMENT() { return 1; } constructor(array?: Uint8Array) { if (array instanceof Uint8Array) { this.push(array); } else if (typeof array !== "undefined") { throw new TypeError("The provided value is not of type 'Uint8Array'"); } } /** Returns the number of elements held in the `Uint8Deque`. */ get length() { return this.#length; } /** Returns the length (in bytes) of the `Uint8Deque`. */ get byteLength() { return this.#length; } *[Symbol.iterator]() { for (const chunk of this.#chunks) { for (const elem of chunk) { yield elem; } } } /** Removes all elements from the `Uint8Deque`. */ clear(): void { this.#chunks = []; this.#length = 0; } /** * Appends the given array to the end of the `Uint8Deque`, and returns the * new `length` of the `Uint8Deque`. This will not create a new buffer, * changes to the given array will impact the `Uint8Deque` and vice versa. * @param array elements to add to the end of the `Uint8Deque` */ push(array: Uint8Array): number { if (!(array instanceof Uint8Array)) { throw new TypeError("The provided value is not of type 'Uint8Array'"); } this.#chunks.push(array); this.#length += array.length; return this.#length; } /** * Returns the element at the given index. Returns `undefined` if the given * index can not be found. * @param index The index of the element to be returned. A negative index can * be used, indicating an offset from the end of the `Uint8Deque`. */ at(index: number): number | undefined { let searchIdx = Math.trunc(index) || 0; if (searchIdx < 0) { searchIdx += this.#length; } if (searchIdx < 0 || searchIdx >= this.#length) { return undefined; } const [chunkIdx, offset] = this._chunkAt(searchIdx); return this.#chunks[chunkIdx][searchIdx - offset]; } /** * Removes up to the given number of elements from the start of the * `Uint8Deque`. * @param count Number of elements to remove, defaults to `1`. */ shift(count = 1): void { while (this.#chunks.length > 0 && count > 0) { const chunk = this.#chunks[0]; if (chunk.length < count) { this.#chunks.shift(); count -= chunk.length; this.#length -= chunk.length; } else { this.#chunks[0] = chunk.subarray(count); this.#length -= count; return; } } } /** * Removes up to the given number of elements from the end of the * `Uint8Deque`. * @param count Number of elements to remove, defaults to `1`. */ pop(count = 1): void { while (this.#chunks.length > 0 && count > 0) { const chunk = this.#chunks[this.#chunks.length - 1]; if (chunk.length < count) { this.#chunks.pop(); count -= chunk.length; this.#length -= chunk.length; } else { this.#chunks[this.#chunks.length - 1] = chunk.subarray(0, -count); this.#length -= count; return; } } } /** * Returns a new typed array that contains a copy of a portion of the * `Uint8Deque` from `start` up to but not including `end`. * A negative index can be used, indicating an offset from the end. * An empty array is returned if `start >= end`. * @param start The beginning of the specified portion of the array, defaults * to `0`. * @param end The end of the specified portion of the array, defaults to the * end of the `Uint8Deque`. If `end` is greater than `length`, then * `length` is used as `end`. */ slice(start = 0, end = this.#length): Uint8Array { if (start < 0) { start += this.#length; } if (end < 0) { end += this.#length; } if (end > this.#length) { end = this.#length; } if (end <= start) { return new Uint8Array(); } const ret = new Uint8Array(end - start); let offset = 0; if (start === 0 && end === this.#length) { // full copy shortcut for (const chunk of this.#chunks) { ret.set(chunk, offset); offset += chunk.length; } return ret; } const [startIndex, startOffset] = this._chunkAt(start); const [endIndex, endOffset] = this._chunkAt(end - 1); if (startIndex === endIndex) { // same underlying chunk const chunk = this.#chunks[startIndex]; // TypedArray.prototype.slice is incompatible with Buffer.prototype.slice ret.set(chunk.subarray(start - startOffset, end - startOffset)); return ret; } const startSection = this.#chunks[startIndex].subarray(start - startOffset); ret.set(startSection, offset); offset += startSection.length; for (let i = startIndex + 1; i < endIndex; i++) { const chunk = this.#chunks[i]; ret.set(chunk, offset); offset += chunk.length; } const endSection = this.#chunks[endIndex].subarray(0, end - endOffset); ret.set(endSection, offset); return ret; } /** * Returns the first index at which a given element can be found in the * `Uint8Deque`, or -1 if it is not present. * @param searchElement Element to locate * @param fromIndex The index to start the search at, defaults to `0`. * A negative index can be used, indicating an offset from the end. */ indexOf(searchElement: number, fromIndex = 0): number { if (fromIndex < 0) { fromIndex += this.#length; } if (fromIndex >= this.#length) { return -1; } let offset = 0; for (let i = 0; i < this.#chunks.length; i++) { const startIdx = Math.max(fromIndex - offset, 0); const idx = this.#chunks[i].indexOf(searchElement, startIdx); if (idx >= 0) { return offset + idx; } offset += this.#chunks[i].length; } return -1; } /** * Determines whether a `Uint8Deque` includes a certain element. * @param searchElement Element to search for * @param fromIndex The index to start the search at, defaults to `0`. * A negative index can be used, indicating an offset from the end. */ includes(searchElement: number, fromIndex = 0): boolean { return this.indexOf(searchElement, fromIndex) >= 0; } /** * Copy the content of an array into the `Uint8Deque`. * @param array The array fron which to copy values. * @param offset The offset into the `Uint8Deque` at which to begin writing * values. * @throws {RangeError} if the offset is set such as it would store beyond the * end of the `Uint8Deque`. */ set(array: number[] | Uint8Array, offset = 0): void { if (offset < 0 || offset + array.length > this.#length) { throw new RangeError("offset is out of bounds"); } if (array.length === 0) return; let [chunkIdx, chunkOffset] = this._chunkAt(offset); if (offset + array.length < chunkOffset + this.#chunks[chunkIdx].length) { this.#chunks[chunkIdx].set(array, offset - chunkOffset); return; } if (!(array instanceof Uint8Array)) { array = new Uint8Array(array); } const end = array.length; let pos = chunkOffset + this.#chunks[chunkIdx].length - offset; this.#chunks[chunkIdx].set(array.subarray(0, pos), offset - chunkOffset); chunkIdx++; while (pos < end) { const chunk = this.#chunks[chunkIdx]; if (chunk.length < end - pos) { chunk.set(array.subarray(pos, pos + chunk.length)); pos += chunk.length; chunkIdx++; } else { chunk.set(array.subarray(pos)); return; } } } forEach( callbackFn: (value: number, index: number, deque: Uint8Deque) => void, ): void { let i = 0; for (const chunk of this.#chunks) { for (const elem of chunk) { callbackFn(elem, i++, this); } } } toString(): string { return `Uint8Deque(${this.#length}) [${this.length ? " ... " : ""}]`; } private _chunkAt(i: number): [index: number, offset: number] { let chunkIdx = 0; let offset = 0; while (offset + this.#chunks[chunkIdx].length <= i) { offset += this.#chunks[chunkIdx].length; chunkIdx++; } return [chunkIdx, offset]; } }
zhangyuannie/typeddeque
_manifest.ts
export default { name: "typeddeque", version: "0.3.0", license: "MIT", };
zhangyuannie/typeddeque
scripts/bundle_node.ts
<reponame>zhangyuannie/typeddeque<gh_stars>1-10 #!/usr/bin/env -S deno run --allow-all import { dirname, fromFileUrl, } from "https://deno.land/std@0.106.0/path/mod.ts"; import * as esbuild from "https://deno.land/x/esbuild@v0.12.24/mod.js"; import manifest from "../_manifest.ts"; const rootDir = `${dirname(fromFileUrl(import.meta.url))}/..`; const outDir = `${rootDir}/dist`; const src: string[] = []; const includes = new Set(["README.md", "LICENSE"]); const excludes = new Set(["_manifest.ts"]); for (const entry of Deno.readDirSync(rootDir)) { if ( entry.isFile && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts") && !excludes.has(entry.name) ) { src.push(entry.name); } } await Deno.remove(outDir, { recursive: true }).catch(() => {}); const compileCmd = `npx -p typescript tsc -t ESNEXT -m commonjs --strict -d --outDir ${outDir}`; const compile = Deno.run({ cmd: [...compileCmd.split(" "), ...src] }); await compile.status(); const decoder = new TextDecoder(); function removeFromFile(path: string, toRemove: string) { const text = decoder.decode(Deno.readFileSync(path)).replaceAll(toRemove, ""); Deno.writeTextFileSync(path, text); } removeFromFile(`${outDir}/mod.js`, ".ts"); removeFromFile(`${outDir}/mod.d.ts`, ".ts"); // write esm bundle await esbuild.build({ entryPoints: [`${rootDir}/mod.ts`], bundle: true, format: "esm", outfile: `${outDir}/mod.esm.js`, }); esbuild.stop(); const packageJson = { name: manifest.name, version: manifest.version, description: "Variable length TypedArray", main: "./mod.js", module: "./mod.esm.js", exports: { import: "./mod.esm.js", require: "./mod.js", }, types: "./mod.d.ts", repository: { type: "git", url: "git+https://github.com/zhangyuannie/typeddeque.git", }, keywords: ["arraybuffer", "buffer", "uint8array", "queue", "deque", "tcp"], author: "<NAME>", license: manifest.license, bugs: { url: "https://github.com/zhangyuannie/typeddeque/issues", }, homepage: "https://github.com/zhangyuannie/typeddeque#readme", engines: { node: ">=12", }, }; Deno.writeTextFileSync( `${outDir}/package.json`, `${JSON.stringify(packageJson, undefined, 2)}\n`, ); for (const path of includes) { Deno.copyFileSync(`${rootDir}/${path}`, `${outDir}/${path}`); }
zhangyuannie/typeddeque
Uint8Deque.test.ts
<filename>Uint8Deque.test.ts import { assertEquals, assertStrictEquals, assertThrows, } from "https://deno.land/std@0.106.0/testing/asserts.ts"; import { Uint8Deque } from "./Uint8Deque.ts"; Deno.test("BYTES_PER_ELEMENT should return 1", () => { assertEquals(Uint8Deque.BYTES_PER_ELEMENT, 1); }); Deno.test("BYTES_PER_ELEMENT should be read only", () => { assertThrows(() => { // @ts-ignore: invalid Uint8Deque.BYTES_PER_ELEMENT = 2; }); }); Deno.test("constructor should allow no argument", () => { const dq = new Uint8Deque(); assertEquals(dq.slice(), new Uint8Array()); }); Deno.test("constructor should allow an Uint8Array as argument", () => { const arr = new Uint8Array([1, 2, 3]); const dq = new Uint8Deque(arr); assertEquals(dq.slice(), arr); }); Deno.test("constructor should throw if the argument is not Uint8Array", () => { const arr = new Uint16Array([1, 2, 3]); assertThrows(() => { new Uint8Deque(arr as unknown as Uint8Array); }, TypeError); }); Deno.test("length should return the number of elements held", () => { const arr = new Uint8Array([1, 2, 3]); const dq = new Uint8Deque(arr); assertEquals(dq.length, 3); const dq2 = new Uint8Deque(); assertEquals(dq2.length, 0); }); Deno.test("length should be read only", () => { assertThrows(() => { const dq = new Uint8Deque(); // @ts-ignore: invalid dq.length = 2; }); }); Deno.test("byteLength should return the length in bytes", () => { const arr = new Uint8Array([1, 2, 3, 4]); const dq = new Uint8Deque(arr); assertEquals(dq.byteLength, 4); const dq2 = new Uint8Deque(); assertEquals(dq2.byteLength, 0); }); Deno.test("byteLength should be read only", () => { assertThrows(() => { const dq = new Uint8Deque(); // @ts-ignore: invalid dq.byteLength = 2; }); }); Deno.test("clear should reset the queue", () => { const arr = new Uint8Array([1, 2, 3]); const dq = new Uint8Deque(arr); dq.push(new Uint8Array([3])); dq.clear(); assertEquals(dq.length, 0); assertEquals(dq.slice(), new Uint8Array()); }); Deno.test("push should throw if the argument is not Uint8Array", () => { const dq = new Uint8Deque(); assertThrows(() => { dq.push(new Uint16Array([1, 2, 3]) as unknown as Uint8Array); }, TypeError); }); Deno.test("push should update the buffer", () => { const dq = new Uint8Deque(); dq.push(new Uint8Array([1, 2, 3])); assertEquals(dq.length, 3); assertEquals(dq.slice(), new Uint8Array([1, 2, 3])); dq.push(new Uint8Array([11, 12])); assertEquals(dq.length, 5); assertEquals(dq.slice(), new Uint8Array([1, 2, 3, 11, 12])); }); Deno.test("push should return the new length", () => { const dq = new Uint8Deque(); assertEquals(dq.push(new Uint8Array([1, 2, 3])), dq.length); assertEquals(dq.push(new Uint8Array([21, 22])), dq.length); }); Deno.test("at should use the integer part of the argument", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); assertEquals(dq.at(-0.01), 1); assertEquals(dq.at(0.9), 1); assertEquals(dq.at(1.001), 2); }); Deno.test("at", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); const arr = new Uint8Array([1, 2]); for (let i = -3; i < arr.length + 1; i++) { assertEquals(dq.at(i), arr.at(i)); } dq.push(new Uint8Array([11, 12])); const arr2 = new Uint8Array([1, 2, 11, 12]); for (let i = -1; i < arr2.length + 1; i++) { assertEquals(dq.at(i), arr2.at(i)); } }); Deno.test("slice", () => { const dq = new Uint8Deque(new Uint8Array([1, 2, 3])); const arr = new Uint8Array([1, 2, 3]); for (let start = -1; start < arr.length + 2; start++) { for (let end = -1; end < arr.length + 2; end++) { assertEquals(dq.slice(start, end), arr.slice(start, end)); } } dq.push(new Uint8Array([11, 12])); dq.push(new Uint8Array([21, 22])); const arr2 = new Uint8Array([1, 2, 3, 11, 12, 21, 22]); for (let start = -1; start < arr2.length + 2; start++) { for (let end = -1; end < arr2.length + 2; end++) { assertEquals(dq.slice(start, end), arr2.slice(start, end)); } } }); Deno.test("indexOf", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); const arr = new Uint8Array([1, 2]); assertEquals(dq.indexOf(1), arr.indexOf(1)); assertEquals(dq.indexOf(3), arr.indexOf(3)); for (const elem of arr) { for (let i = -3; i < arr.length + 1; i++) { assertEquals(dq.indexOf(elem, i), arr.indexOf(elem, i)); } } dq.push(new Uint8Array([11, 12])); const arr2 = new Uint8Array([1, 2, 11, 12]); for (const elem of arr2) { for (let i = -1; i < arr2.length + 1; i++) { assertEquals(dq.indexOf(elem, i), arr2.indexOf(elem, i)); } } }); Deno.test("includes", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); const arr = new Uint8Array([1, 2]); assertEquals(dq.includes(1), arr.includes(1)); assertEquals(dq.includes(3), arr.includes(3)); for (const elem of arr) { for (let i = -3; i < arr.length + 1; i++) { assertEquals(dq.includes(elem, i), arr.includes(elem, i)); } } dq.push(new Uint8Array([11, 12])); const arr2 = new Uint8Array([1, 2, 11, 12]); for (const elem of arr2) { for (let i = -1; i < arr2.length + 1; i++) { assertEquals(dq.includes(elem, i), arr2.includes(elem, i)); } } }); Deno.test("pop single value", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); const arr = [1, 2]; const pop = () => { dq.pop(); arr.pop(); assertEquals([...dq.slice()], arr); }; pop(); pop(); pop(); dq.push(new Uint8Array([11, 12, 13])); arr.push(11, 12, 13); dq.push(new Uint8Array([21, 22])); arr.push(21, 22); while (arr.length) { pop(); } }); Deno.test("shift single value", () => { const dq = new Uint8Deque(new Uint8Array([1, 2])); const arr = [1, 2]; const shift = () => { dq.shift(); arr.shift(); assertEquals([...dq.slice()], arr); }; shift(); shift(); shift(); dq.push(new Uint8Array([11, 12, 13])); arr.push(11, 12, 13); dq.push(new Uint8Array([21, 22])); arr.push(21, 22); while (arr.length) { shift(); } }); Deno.test("set RangeError", () => { const dq = new Uint8Deque(new Uint8Array([1, 2, 3])); dq.set([], 3); // not throw assertThrows(() => { dq.set([1], 3); }, RangeError); assertThrows(() => { dq.set([1, 2], 2); }, RangeError); assertThrows(() => { dq.set([], -1); }, RangeError); assertEquals(dq.slice(), new Uint8Array([1, 2, 3])); }); Deno.test("set", () => { const testdata = [ { targets: [[1, 2, 3]], source: [10] }, { targets: [[1, 2, 3, 4]], source: [10, 11] }, { targets: [[1, 2, 3, 4], [5, 6, 7], [8]], source: [10] }, { targets: [[1, 2, 3, 4], [5, 6, 7], [8]], source: [10, 11] }, { targets: [[1, 2], [5, 6], [8]], source: [10, 11, 12, 13] }, ]; let count = 0; for (const { targets, source } of testdata) { Object.freeze(source); targets.forEach(Object.freeze); for (const useTypedArray of [true, false]) { const end = targets.flat().length - source.length + 1; for (let i = 0; i < end; i++) { const buffer = new Uint8Deque(); targets.forEach((t) => buffer.push(new Uint8Array(t))); const array = new Uint8Array(targets.flat()); const srcArr = useTypedArray ? new Uint8Array(source) : source; array.set(srcArr, i); buffer.set(srcArr, i); assertEquals(buffer.slice(), array); count++; } } } assertEquals(count, 46); }); Deno.test("@@iterator", () => { const testdata = [[[1, 2, 3, 4, 5]], [[1, 2, 3], [4], [5, 6, 7]]]; for (const targets of testdata) { const buffer = new Uint8Deque(); targets.forEach((t) => buffer.push(new Uint8Array(t))); const array = new Uint8Array(targets.flat()); const received = []; const expected = []; for (const elem of buffer) { received.push(elem); } for (const elem of array) { expected.push(elem); } assertEquals(received, expected); } }); Deno.test("forEach", () => { const testdata = [[[1, 2, 3, 4, 5]], [[1, 2, 3], [4], [5, 6, 7]]]; for (const targets of testdata) { const buffer = new Uint8Deque(); targets.forEach((t) => buffer.push(new Uint8Array(t))); const array = new Uint8Array(targets.flat()); const received: unknown[] = []; const expected: unknown[] = []; buffer.forEach((val, idx, buf) => { received.push([val, idx]); assertStrictEquals(buffer, buf); }); array.forEach((val, idx) => { expected.push([val, idx]); }); assertEquals(received, expected); } }); Deno.test("toString", () => { const dq = new Uint8Deque(); assertEquals(dq.toString(), "Uint8Deque(0) []"); const dq2 = new Uint8Deque(new Uint8Array([1, 2])); assertEquals(dq2.toString(), "Uint8Deque(2) [ ... ]"); });
norbornen/postgres-interval-class
__tests__/index.ts
<gh_stars>0 import PostgresColumnInterval from '../src/index'; import parse from 'postgres-interval'; test('#ctor', async () => { expect.assertions(5); const pi = new PostgresColumnInterval('00:05:00'); expect(pi instanceof PostgresColumnInterval).toBe(true); expect(pi.minutes).toBe(5); expect(pi.years).toBe(0); expect(pi).toEqual(new PostgresColumnInterval(parse('00:05:00'))); expect(pi).toEqual(new PostgresColumnInterval(pi)); }); test('#add', async () => { expect.assertions(3); const pi = new PostgresColumnInterval('00:05:00'); const pi2 = pi.add(new PostgresColumnInterval('00:15:00')); expect(pi2.minutes).toBe(20); console.log(pi2); const d1 = new Date('2014-03-09T01:59:00'); const d2 = pi.add(d1); expect(d1).toEqual(d1); expect(d2).toEqual(new Date('2014-03-09T02:04:00')); }); test('#sub', async () => { expect.assertions(3); const pi = new PostgresColumnInterval('00:05:00'); const pi3 = pi.sub(pi); expect(pi3.minutes).toBe(0); const d1 = new Date('2014-03-09T01:59:00'); const d2 = pi.sub(d1); expect(d1).toEqual(d1); expect(d2).toEqual(new Date('2014-03-09T01:54:00')); }); test('#string', async () => { expect.assertions(1); const pi = new PostgresColumnInterval('00:05:00'); expect(pi.toString()).toBe('5 minutes'); });
norbornen/postgres-interval-class
src/index.ts
<reponame>norbornen/postgres-interval-class import parse, { IPostgresInterval } from 'postgres-interval'; type Interval = Omit<IPostgresInterval, 'toPostgres' | 'toISO' | 'toISOString'>; const column_interval_properties: Array<keyof Interval> = ['years', 'months', 'days', 'hours', 'minutes', 'seconds', 'milliseconds']; export default class PostgresColumnInterval { protected interval: Interval = { years: 0, months: 0, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 }; constructor(value: any) { // string | Interval | PostgresColumnInterval if (typeof value === 'string') { value = parse(value); } if (typeof value === 'object') { if ('interval' in value) { value = value.interval; } const interval = column_interval_properties.reduce((acc, key) => { if (value.hasOwnProperty(key) && value[key] !== null && value[key] !== undefined) { acc[key] = value[key]; } return acc; }, {} as Interval); Object.assign(this.interval, interval); } } get years(): number { return Number(this.interval.years || 0); } get months(): number { return Number(this.interval.months || 0); } get days(): number { return Number(this.interval.days || 0); } get hours(): number { return Number(this.interval.hours || 0); } get minutes(): number { return Number(this.interval.minutes || 0); } get seconds(): number { return Number(this.interval.seconds || 0); } get milliseconds(): number { return Number(this.interval.milliseconds || 0); } public valueOf(): Interval { return this.interval; } public toString(): string { const agg = column_interval_properties.reduce((acc, key) => { if (key in this.interval && this.interval[key] !== undefined && this.interval[key] !== null && this.interval[key]! > 0) { acc.push(`${this[key]} ${key}`); } return acc; }, [] as string[]); return agg.join(' ') || '0'; } public toJSON(): Interval { return this.valueOf(); } public add(d: Date): Date; public add(d: PostgresColumnInterval): PostgresColumnInterval; public add<T extends Date | PostgresColumnInterval>(d: T): T { if (d instanceof Date) { const dn = new Date((d as Date).valueOf()); dn.setMilliseconds(dn.getMilliseconds() + this.milliseconds); dn.setSeconds(dn.getSeconds() + this.seconds); dn.setMinutes(dn.getMinutes() + this.minutes); dn.setHours(dn.getHours() + this.hours); dn.setDate(dn.getDate() + this.days); dn.setMonth(dn.getMonth() + this.months); dn.setFullYear(dn.getFullYear() + this.years); return dn as T; } if (d instanceof PostgresColumnInterval) { const dn = new PostgresColumnInterval(this.valueOf()); dn.interval = Object.keys(dn.interval).reduce((acc, el) => { acc[el] = dn[el] + d[el]; return acc; }, dn.interval); return dn as T; } throw new Error('UNKNOWN ARG TYPE'); } public sub(d: Date): Date; public sub(d: PostgresColumnInterval): PostgresColumnInterval; public sub<T extends Date | PostgresColumnInterval>(d: T): T { if (d instanceof Date) { const dn = new Date((d as Date).valueOf()); dn.setMilliseconds(dn.getMilliseconds() - this.milliseconds); dn.setSeconds(dn.getSeconds() - this.seconds); dn.setMinutes(dn.getMinutes() - this.minutes); dn.setHours(dn.getHours() - this.hours); dn.setDate(dn.getDate() - this.days); dn.setMonth(dn.getMonth() - this.months); dn.setFullYear(dn.getFullYear() - this.years); return dn as T; } if (d instanceof PostgresColumnInterval) { const dn = new PostgresColumnInterval(this.valueOf()); dn.interval = Object.keys(dn.interval).reduce((acc, el) => { acc[el] = dn[el] - d[el]; return acc; }, dn.interval); return dn as T; } throw new Error('UNKNOWN ARG TYPE'); } } export { PostgresColumnInterval, Interval };
SlepoRus/test_angular
src/app/app.component.ts
<gh_stars>0 import { Component } from '@angular/core'; import { ApiService } from './shared'; import '../style/app.less'; @Component({ selector: 'my-app', // <my-app></my-app> templateUrl: './app.component.html', styleUrls: ['./app.component.less'], }) export class AppComponent { title: string; model = []; count = 0; date = "0"; status = "all"; text = ""; limit = 20; page = 1; pages = []; api = undefined; selectByDate(e) { this.date = e; this.resetData() this.search(); } constructor(api: ApiService) { this.api = api; api.getData().done((val) => { this.model = val.data; this.count = val.count; this.getPages(); });; } selectByOpen(e) { this.status = e; this.resetData() this.search(); } selectByInput(e) { this.text = e; this.resetData() this.search(); } resetData() { this.page = 1; this.limit = 20; this.pages = []; } getPages() { const PAGE_RANGE = 2, TOTAL_PAGES = 5; let total_pages = Math.ceil(this.count/this.limit), { page } = this, massive = [], i = page > PAGE_RANGE ? page - PAGE_RANGE : 1; while (total_pages >= i ) { massive.push({text: i, value: i}); i++; if (massive.length == TOTAL_PAGES && page + 2 !== total_pages) { massive.push({text:'...', value:i + 1}); massive.push({text:total_pages, value:total_pages}); break; } } this.pages = massive; } changeLimit(e) { this.limit = e; this.page = 1; this.search(); } changePage(e) { this.page = e; this.search(); } search() { if (this.api) this.api.filterData(this).done((val) => { this.model = val.data; this.count = val.count; this.getPages(); }) } }
SlepoRus/test_angular
src/app/shared/api.service.ts
import { Injectable } from '@angular/core'; var apiPrefix = "http://localhost:9090"; import * as $ from 'jquery'; @Injectable() export class ApiService { getData() { return $.ajax({ url: `${apiPrefix}/all`, }) } filterData({ date, status, text, limit, page }) { return $.ajax({ url: `${apiPrefix}/filter`, data: `date=${date}&status=${status}&text=${text}&limit=${limit}&page=${page}` }) } }
manuel-hegner/conquery
frontend/src/js/previous-queries/list/PreviousQuery.tsx
<filename>frontend/src/js/previous-queries/list/PreviousQuery.tsx<gh_stars>10-100 import { css } from "@emotion/react"; import styled from "@emotion/styled"; import type { StateT } from "app-types"; import { parseISO } from "date-fns"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import type { DatasetIdT, SecondaryId } from "../../api/types"; import DownloadButton from "../../button/DownloadButton"; import IconButton from "../../button/IconButton"; import { formatDate } from "../../common/helpers"; import { exists } from "../../common/helpers/exists"; import ErrorMessage from "../../error-message/ErrorMessage"; import FaIcon from "../../icon/FaIcon"; import WithTooltip from "../../tooltip/WithTooltip"; import PreviousQueriesLabel from "./PreviousQueriesLabel"; import { useRemoveQuery, useRenameQuery } from "./actions"; import { PreviousQueryT } from "./reducer"; const Root = styled("div")<{ own?: boolean; system?: boolean }>` margin: 0; padding: 4px 10px; cursor: pointer; border-radius: ${({ theme }) => theme.borderRadius}; border: 1px solid ${({ theme }) => theme.col.grayLight}; background-color: ${({ theme }) => theme.col.bg}; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2); overflow: hidden; border-left: ${({ theme, own, system }) => own ? `4px solid ${theme.col.orange}` : system ? `4px solid ${theme.col.blueGrayDark}` : `1px solid ${theme.col.grayLight}`}; &:hover { ${({ theme, own, system }) => !own && !system && css` border-left-color: ${theme.col.blueGray}; `}; border-top-color: ${({ theme }) => theme.col.blueGray}; border-right-color: ${({ theme }) => theme.col.blueGray}; border-bottom-color: ${({ theme }) => theme.col.blueGray}; } `; const Gray = styled("div")` color: ${({ theme }) => theme.col.gray}; font-size: ${({ theme }) => theme.font.xs}; `; const TopInfos = styled(Gray)` line-height: 20px; display: flex; align-items: center; justify-content: space-between; `; const OwnerName = styled(Gray)` flex-shrink: 0; padding-left: 5px; `; const TopRight = styled("div")` display: flex; align-items: center; flex-shrink: 0; `; const TopLeft = styled("div")` display: flex; align-items: center; `; const NonBreakingText = styled("span")` white-space: nowrap; `; const LabelRow = styled("div")` display: flex; width: 100%; justify-content: space-between; line-height: 24px; margin: 2px 0; `; const StyledErrorMessage = styled(ErrorMessage)` margin: 0; `; const StyledFaIcon = styled(FaIcon)` margin: 0 6px; `; const StyledWithTooltip = styled(WithTooltip)` margin-left: 10px; `; const SxDownloadButton = styled(DownloadButton)` white-space: nowrap; button { font-size: ${({ theme }) => theme.font.xs}; } `; const FoldersButton = styled(IconButton)` margin-right: 10px; `; interface PropsT { query: PreviousQueryT; datasetId: DatasetIdT; onIndicateDeletion: () => void; onIndicateShare: () => void; onIndicateEditFolders: () => void; } const PreviousQuery = React.forwardRef<HTMLDivElement, PropsT>( function PreviousQueryComponent( { query, datasetId, onIndicateDeletion, onIndicateShare, onIndicateEditFolders, }, ref, ) { const { t } = useTranslation(); const loadedSecondaryIds = useSelector<StateT, SecondaryId[]>( (state) => state.conceptTrees.secondaryIds, ); const renameQuery = useRenameQuery(); const removeQuery = useRemoveQuery(query.id); const mayDeleteQueryRightAway = query.tags.length === 0 && query.isPristineLabel; const onDeleteClick = mayDeleteQueryRightAway ? removeQuery : onIndicateDeletion; const peopleFoundText = exists(query.numberOfResults) ? `${query.numberOfResults} ${t("previousQueries.results")}` : t("previousQuery.notExecuted"); const dateFormat = `${t("inputDateRange.dateFormat")} HH:mm`; const executedAtDate = parseISO(query.createdAt); const executedAt = formatDate(executedAtDate, dateFormat); const isShared = query.shared || (query.groups && query.groups.length > 0); const label = query.label || query.id.toString(); const mayEditQuery = query.own || isShared; const secondaryId = query.secondaryId ? loadedSecondaryIds.find((secId) => query.secondaryId === secId.id) : null; const [isEditingLabel, setIsEditingLabel] = useState<boolean>(false); return ( <Root ref={ref} own={!!query.own} system={!!query.system || (!query.own && !isShared)} > <TopInfos> <TopLeft> {mayEditQuery && ( <WithTooltip text={t("previousQuery.editFolders")}> <FoldersButton icon="folder" tight small bare onClick={onIndicateEditFolders} /> </WithTooltip> )} {query.resultUrls.length > 0 ? ( <WithTooltip text={t("previousQuery.downloadResults")}> <SxDownloadButton tight small bare url={query.resultUrls[0]}> {peopleFoundText} </SxDownloadButton> </WithTooltip> ) : ( <NonBreakingText>{peopleFoundText}</NonBreakingText> )} </TopLeft> <TopRight> {executedAt} {secondaryId && query.queryType === "SECONDARY_ID_QUERY" && ( <StyledWithTooltip text={`${t("queryEditor.secondaryId")}: ${secondaryId.label}`} > <IconButton icon="microscope" bare onClick={() => {}} /> </StyledWithTooltip> )} {query.own && ( <StyledWithTooltip text={isShared ? t("common.shared") : t("common.share")} > <IconButton icon={isShared ? "user-friends" : "upload"} bare onClick={onIndicateShare} /> </StyledWithTooltip> )} {query.loading ? ( <StyledFaIcon icon="spinner" /> ) : ( query.own && ( <StyledWithTooltip text={t("common.delete")}> <IconButton icon="times" bare onClick={onDeleteClick} /> </StyledWithTooltip> ) )} </TopRight> </TopInfos> <LabelRow> <PreviousQueriesLabel mayEditQuery={mayEditQuery} loading={!!query.loading} label={label} selectTextOnMount={true} onSubmit={(label) => renameQuery(datasetId, query.id, label)} isEditing={isEditingLabel} setIsEditing={setIsEditingLabel} /> <OwnerName>{query.ownerName}</OwnerName> </LabelRow> {!!query.error && <StyledErrorMessage message={query.error} />} </Root> ); }, ); export default PreviousQuery;
manuel-hegner/conquery
frontend/src/js/model/table.ts
import type { TableT } from "../api/types"; import { compose, isEmpty } from "../common/helpers"; import { exists } from "../common/helpers/exists"; import type { TableWithFilterValueT } from "../standard-query-editor/types"; import { filtersWithDefaults } from "./filter"; import { objectHasSelectedSelects, selectsWithDefaults } from "./select"; export const tableIsEditable = (table: TableWithFilterValueT) => (!!table.filters && table.filters.length > 0) || (!!table.selects && table.selects.length > 0) || (!!table.dateColumn && table.dateColumn.options.length > 0); export const tablesHaveActiveFilter = (tables: TableWithFilterValueT[]) => tables.some((table) => tableHasActiveFilters(table)); export const tableHasActiveFilters = (table: TableWithFilterValueT) => { const activeSelects = objectHasSelectedSelects(table); const activeDateColumn = tableHasNonDefaultDateColumn(table); const activeFilters = table.filters && table.filters.some( (filter) => !isEmpty(filter.value) && (isEmpty(filter.defaultValue) || filter.value !== filter.defaultValue), ); return activeSelects || activeDateColumn || activeFilters; }; const tableHasNonDefaultDateColumn = (table: TableWithFilterValueT) => exists(table.dateColumn) && table.dateColumn.options.length > 0 && (exists(table.dateColumn.defaultValue) ? table.dateColumn.value !== table.dateColumn.defaultValue : table.dateColumn.value !== table.dateColumn.options[0].value); export function tableIsDisabled( table: TableWithFilterValueT, blocklistedTables?: string[], allowlistedTables?: string[], ) { return ( (!!allowlistedTables && !tableIsAllowlisted(table, allowlistedTables)) || (!!blocklistedTables && tableIsBlocklisted(table, blocklistedTables)) ); } export function tableIsBlocklisted( table: TableWithFilterValueT, blocklistedTables: string[], ) { return blocklistedTables.some( (tableName) => table.id.toLowerCase().indexOf(tableName.toLowerCase()) !== -1, ); } export function tableIsAllowlisted( table: TableWithFilterValueT, allowlistedTables: string[], ) { return allowlistedTables.some( (tableName) => table.id.toLowerCase().indexOf(tableName.toLowerCase()) !== -1, ); } export const resetAllFiltersInTables = (tables: TableWithFilterValueT[]) => { if (!tables) return []; return tablesWithDefaults(tables); }; const tableWithDefaultDateColumn = (table: TableT): TableT => { return { ...table, dateColumn: !!table.dateColumn && !!table.dateColumn.options && table.dateColumn.options.length > 0 ? { ...table.dateColumn, value: table.dateColumn.options[0].value as string, } : null, }; }; const tableWithDefaultFilters = (table: TableT) => ({ ...table, filters: filtersWithDefaults(table.filters), }); const tableWithDefaultSelects = (table: TableT) => ({ ...table, selects: selectsWithDefaults(table.selects), }); export const tableWithDefaults = (table: TableT): TableT => compose( tableWithDefaultDateColumn, tableWithDefaultSelects, tableWithDefaultFilters, )({ ...table, exclude: false, }); export const tablesWithDefaults = (tables?: TableT[]) => tables ? tables.map(tableWithDefaults) : [];
manuel-hegner/conquery
frontend/src/js/concept-trees-open/actions.ts
import type { ConceptIdT } from "../api/types"; import { SET_CONCEPT_OPEN, RESET_ALL_CONCEPT_OPEN, CLOSE_ALL_CONCEPT_OPEN, } from "./actionTypes"; export function setConceptOpen(conceptId: ConceptIdT, open: boolean) { return { type: SET_CONCEPT_OPEN, payload: { conceptId, open, }, }; } export function resetAllConceptOpen() { return { type: RESET_ALL_CONCEPT_OPEN, }; } export function closeAllConceptOpen(rootConceptIds: ConceptIdT[]) { return { type: CLOSE_ALL_CONCEPT_OPEN, payload: { rootConceptIds, }, }; }
manuel-hegner/conquery
frontend/src/js/user/selectors.ts
import { useSelector } from "react-redux"; import type { PermissionsT, GetMeResponseT, DatasetIdT } from "../api/types"; import type { StateT } from "../app/reducers"; interface ContextT { datasetId?: string; } export function selectPermissions( state: StateT, ): Record<DatasetIdT, PermissionsT> | null { return !!state.user.me && !!state.user.me.datasetAbilities ? state.user.me.datasetAbilities : null; } function canDoNothing( permissions: Record<DatasetIdT, PermissionsT>, datasetId: string, ) { return !permissions[datasetId]; } function canDo( state: StateT, canDoWithPermissions: ( permissions: Record<DatasetIdT, PermissionsT>, datasetId: string, ) => boolean, context?: ContextT, ) { const permissions = selectPermissions(state); if (!permissions) return false; const { selectedDatasetId } = state.datasets; const datasetId: string | null = context && context.datasetId ? context.datasetId : selectedDatasetId; if (!datasetId) { return false; } if (canDoNothing(permissions, datasetId)) return false; return canDoWithPermissions(permissions, datasetId); } // Example of another possible permission, including a "context" // export function canDownloadResult(state: StateT, datasetId?: string) { // return canDo( // state, // (permissions, finalDatasetId) => { // return permissions... // }, // { datasetId } // ); // } export function canUploadResult(state: StateT) { return canDo(state, (permissions, datasetId) => { return permissions[datasetId].canUpload === true; }); } export function useHideLogoutButton() { const me = useSelector<StateT, GetMeResponseT | null>( (state) => state.user.me, ); return !!me && (me.hideLogoutButton === undefined || !!me.hideLogoutButton); }
manuel-hegner/conquery
frontend/src/js/ui-components/InputDateRange.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React, { FC, ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { IndexPrefix } from "../common/components/IndexPrefix"; import { formatDateFromState, parseDate, parseDateToState, getDateStringFromShortcut, DateStringMinMax, } from "../common/helpers/dateHelper"; import { exists } from "../common/helpers/exists"; import InfoTooltip from "../tooltip/InfoTooltip"; import BaseInput from "./BaseInput"; import Label from "./Label"; import Labeled from "./Labeled"; import Optional from "./Optional"; const Root = styled("div")<{ center?: boolean }>` text-align: ${({ center }) => (center ? "center" : "left")}; `; const Pickers = styled("div")<{ inline?: boolean; center?: boolean }>` display: flex; flex-direction: ${({ inline }) => (inline ? "row" : "column")}; justify-content: ${({ center }) => (center ? "center" : "flex-start")}; `; const StyledLabel = styled(Label)<{ large?: boolean }>` ${({ theme, large }) => large && css` font-size: ${theme.font.md}; margin: 20px 0 10px; `} `; const SxLabeled = styled(Labeled)` &:first-of-type { margin-right: 10px; } `; interface PropsT { label?: ReactNode; indexPrefix?: number; labelSuffix?: ReactNode; className?: string; inline?: boolean; large?: boolean; center?: boolean; autoFocus?: boolean; tooltip?: string; optional?: boolean; input: { value: DateStringMinMax; onChange: (value: DateStringMinMax) => void; }; } function getDisplayDate( what: "min" | "max", value: DateStringMinMax, dateFormat: string, ) { const dateString = value[what]; if (!dateString) return ""; return formatDateFromState(dateString, dateFormat); } const InputDateRange: FC<PropsT> = ({ large, inline, center, label, indexPrefix, autoFocus, labelSuffix, input: { value, onChange }, optional, tooltip, }) => { const { t } = useTranslation(); const onSetDate = (date: DateStringMinMax) => { onChange(date); }; const onSetWhatDate = (what: "min" | "max", val: string) => { onChange({ ...value, [what]: val, }); }; const onChangeRaw = ( what: "min" | "max", val: string, dateFormat: string, ) => { const potentialDate = parseDate(val, dateFormat); if (potentialDate) { return onSetWhatDate(what, parseDateToState(potentialDate)); } const { min, max } = getDateStringFromShortcut(what, val, dateFormat); if (min && max) { onSetDate({ min, max }); } else if (min) { onSetWhatDate("min", min); } else if (max) { onSetWhatDate("max", max); } else { onSetWhatDate(what, val); } }; const applyDate = (what: "min" | "max", val: string, dateFormat: string) => { if (parseDate(val, dateFormat) === null) { onSetWhatDate(what, ""); } }; // To display the date depending on the locale const displayDateFormat = t("inputDateRange.dateFormat"); const min = getDisplayDate("min", value, displayDateFormat); const max = getDisplayDate("max", value, displayDateFormat); const isMinValid = exists(value.min && parseDate(min, displayDateFormat)); const isMaxValid = exists(value.max && parseDate(max, displayDateFormat)); return ( <Root center={center}> {label && ( <StyledLabel large={large}> {exists(indexPrefix) && <IndexPrefix># {indexPrefix}</IndexPrefix>} {optional && <Optional />} {label} <InfoTooltip html={ <> {exists(tooltip) && ( <> {tooltip} <br /> <br /> </> )} <span dangerouslySetInnerHTML={{ __html: t("inputDateRange.tooltip.possiblePattern"), }} /> </> } /> {labelSuffix && labelSuffix} </StyledLabel> )} <Pickers inline={inline} center={center}> <SxLabeled label={t("inputDateRange.from")}> <BaseInput inputType="text" value={min} valid={isMinValid} invalid={min.length !== 0 && !isMinValid} invalidText={t("common.dateInvalid")} placeholder={displayDateFormat.toUpperCase()} onChange={(val) => onChangeRaw("min", val as string, displayDateFormat) } onBlur={(e) => applyDate("min", e.target.value, displayDateFormat)} inputProps={{ autoFocus, }} /> </SxLabeled> <SxLabeled label={t("inputDateRange.to")}> <BaseInput inputType="text" value={max} valid={isMaxValid} invalid={max.length !== 0 && !isMaxValid} invalidText={t("common.dateInvalid")} placeholder={displayDateFormat.toUpperCase()} onChange={(val) => onChangeRaw("max", val as string, displayDateFormat) } onBlur={(e) => applyDate("max", e.target.value, displayDateFormat)} /> </SxLabeled> </Pickers> </Root> ); }; export default InputDateRange;
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/actions.ts
import { ActionType, createAction } from "typesafe-actions"; import { TimebasedOperatorType, TimebasedResultType } from "./reducer"; export type TimebasedActions = ActionType< | typeof dropTimebasedNode | typeof removeTimebasedNode | typeof setTimebasedNodeTimestamp | typeof setTimebasedConditionOperator | typeof setTimebasedConditionMaxDays | typeof setTimebasedConditionMinDays | typeof setTimebasedConditionMinDaysOrNoEvent | typeof setTimebasedIndexResult | typeof addTimebasedCondition | typeof removeTimebasedCondition | typeof clearTimebasedQuery >; export const dropTimebasedNode = createAction( "timebased-query-editor/DROP_TIMEBASED_NODE", )<{ conditionIdx: number; resultIdx: number; node: TimebasedResultType; moved: boolean; }>(); export const removeTimebasedNode = createAction( "timebased-query-editor/REMOVE_TIMEBASED_NODE", )<{ conditionIdx: number; resultIdx: number; moved: boolean }>(); export const setTimebasedNodeTimestamp = createAction( "timebased-query-editor/SET_TIMEBASED_NODE_TIMESTAMP", )<{ conditionIdx: number; resultIdx: number; timestamp: string; }>(); export const setTimebasedConditionOperator = createAction( "timebased-query-editor/SET_TIMEBASED_CONDITION_OPERATOR", )<{ conditionIdx: number; operator: TimebasedOperatorType }>(); export const setTimebasedConditionMaxDays = createAction( "timebased-query-editor/SET_TIMEBASED_CONDITION_MAX_DAYS", )<{ conditionIdx: number; days: number | null }>(); export const setTimebasedConditionMinDays = createAction( "timebased-query-editor/SET_TIMEBASED_CONDITION_MIN_DAYS", )<{ conditionIdx: number; days: number | null }>(); export const setTimebasedConditionMinDaysOrNoEvent = createAction( "timebased-query-editor/SET_TIME_BASED_CONDITION_MIN_DAYS_OR_NO_EVENT", )<{ conditionIdx: number; days: number | null }>(); export const setTimebasedIndexResult = createAction( "timebased-query-editor/SET_TIMEBASED_INDEX_RESULT", )<{ indexResult: string }>(); export const addTimebasedCondition = createAction( "timebased-query-editor/ADD_TIMEBASED_CONDITION", )(); export const removeTimebasedCondition = createAction( "timebased-query-editor/REMOVE_TIMEBASED_CONDITION", )<{ conditionIdx: number }>(); export const clearTimebasedQuery = createAction( "timebased-query-editor/CLEAR_TIMEBASED_QUERY", )();
manuel-hegner/conquery
frontend/src/js/external-forms/FormsQueryRunner.tsx
import { StateT } from "app-types"; import React, { FC } from "react"; import { useSelector } from "react-redux"; import { isValid, isPristine, getFormValues, FormStateMap } from "redux-form"; import { DatasetIdT } from "../api/types"; import { useDatasetId } from "../dataset/selectors"; import QueryRunner from "../query-runner/QueryRunner"; import { useStartQuery, useStopQuery } from "../query-runner/actions"; import { QueryRunnerStateT } from "../query-runner/reducer"; import { Form } from "./config-types"; import { selectReduxFormState, selectFormConfig, selectQueryRunner, selectRunningQuery, selectActiveFormType, } from "./stateSelectors"; import transformQueryToApi from "./transformQueryToApi"; const isActiveFormValid = (state: StateT) => { const activeForm = selectActiveFormType(state); const reduxFormState = selectReduxFormState(state); if (!activeForm || !reduxFormState) return false; return ( !isPristine(activeForm, () => reduxFormState)(state) && isValid(activeForm, () => reduxFormState)(state) ); }; const selectIsButtonEnabled = ( datasetId: DatasetIdT | null, queryRunner: QueryRunnerStateT | null, ) => (state: StateT) => { if (!queryRunner) return false; return !!( datasetId !== null && !queryRunner.startQuery.loading && !queryRunner.stopQuery.loading && isActiveFormValid(state) ); }; const FormQueryRunner: FC = () => { const datasetId = useDatasetId(); const queryRunner = useSelector<StateT, QueryRunnerStateT | null>( selectQueryRunner, ); const queryId = useSelector<StateT, string | null>(selectRunningQuery); const isQueryRunning = !!queryId; const isButtonEnabled = useSelector<StateT, boolean>( selectIsButtonEnabled(datasetId, queryRunner), ); const formName = useSelector<StateT, string | null>(selectActiveFormType); const reduxFormState = useSelector<StateT, FormStateMap | null>( selectReduxFormState, ); const form = useSelector<StateT, unknown>((state) => formName && reduxFormState ? getFormValues(formName, () => reduxFormState)(state) : {}, ); const formConfig = useSelector<StateT, Form | null>(selectFormConfig); const query = { formName, form }; const formQueryTransformation = formConfig ? transformQueryToApi(formConfig) : () => {}; const startExternalFormsQuery = useStartQuery("externalForms"); const stopExternalFormsQuery = useStopQuery("externalForms"); const startQuery = () => { if (datasetId) { startExternalFormsQuery(datasetId, query, { formQueryTransformation, }); } }; const stopQuery = () => { if (datasetId && queryId) { stopExternalFormsQuery(datasetId, queryId); } }; if (!queryRunner) { return null; } return ( <QueryRunner queryRunner={queryRunner} isButtonEnabled={isButtonEnabled} isQueryRunning={isQueryRunning} startQuery={startQuery} stopQuery={stopQuery} /> ); }; export default FormQueryRunner;
manuel-hegner/conquery
frontend/src/index.ts
import { theme } from "./app-theme"; import conquery from "./js"; import { language, CustomEnvironment } from "./js/environment"; import FormsTab from "./js/external-forms"; import i18next from "./js/localization/i18next"; import { TabT } from "./js/pane/types"; import StandardQueryEditorTab from "./js/standard-query-editor"; import TimebasedQueryEditorTab from "./js/timebased-query-editor"; import translationsDe from "./localization/de.json"; import translationsEn from "./localization/en.json"; i18next.addResourceBundle("de", "translation", translationsDe, true, true); i18next.addResourceBundle("en", "translation", translationsEn, true, true); i18next.changeLanguage(language); const customEnvironment: CustomEnvironment = {}; const tabs: TabT[] = [ StandardQueryEditorTab, TimebasedQueryEditorTab, FormsTab, ]; conquery({ theme, tabs, customEnvironment });
manuel-hegner/conquery
frontend/src/js/external-forms/form-concept-group/FormConceptCopyModal.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import PrimaryButton from "../../button/PrimaryButton"; import TransparentButton from "../../button/TransparentButton"; import { useActiveLang } from "../../localization/useActiveLang"; import Modal from "../../modal/Modal"; import InputCheckbox from "../../ui-components/InputCheckbox"; import InputSelect from "../../ui-components/InputSelect"; import { selectActiveFormValues, useVisibleConceptListFields, } from "../stateSelectors"; const Buttons = styled("div")` display: flex; align-items: center; justify-content: space-between; width: 100%; margin-top: 20px; `; const Options = styled("div")` padding: 8px 0 0 28px; overflow-y: auto; -webkit-overflow-scrolling: touch; max-height: 345px; `; const SelectAllCheckbox = styled(InputCheckbox)` margin: 10px 0 0 8px; `; const SxInputCheckbox = styled(InputCheckbox)` margin: 5px 0; `; type PropsT = { targetFieldname: string; onAccept: (selectedNodes: Object[]) => void; onClose: () => void; }; const FormConceptCopyModal = ({ targetFieldname, onAccept, onClose, }: PropsT) => { const { t } = useTranslation(); const activeLang = useActiveLang(); const formValues = useSelector<StateT, Record<string, any>>((state) => selectActiveFormValues(state), ); const visibleConceptListFields = useVisibleConceptListFields(); const conceptListFieldOptions = visibleConceptListFields .filter((field) => field.name !== targetFieldname) .map((field) => ({ label: field.label[activeLang], value: field.name, })); // Since the modal is only rendered when there exists more than one concept list field // we can assume that `conceptListFieldOptions` still has length >= 1 const [selectedOption, setSelectedOption] = useState<string>( conceptListFieldOptions[0].value, ); const [valuesChecked, setValuesChecked] = useState<{ [key: number]: boolean; }>({}); useEffect(() => { const values = formValues[selectedOption]; const initiallyChecked = values.reduce((checkedValues, value, i) => { checkedValues[i] = false; return checkedValues; }, {}); setValuesChecked(initiallyChecked); }, [selectedOption]); const allConceptsSelected = Object.keys(valuesChecked).every( (key) => valuesChecked[key], ); const isAcceptDisabled = Object.keys(valuesChecked).every( (key) => !valuesChecked[key], ); function idxHasConcepts(idx: number) { const values = formValues[selectedOption]; const concepts = values[idx].concepts.filter((cpt) => !!cpt); return concepts.length > 0; } function getLabelFromIdx(idx: number) { const values = formValues[selectedOption]; const concepts = values[idx].concepts.filter((cpt) => !!cpt); if (concepts.length === 0) return "-"; return ( concepts[0].label + (concepts.length > 1 ? ` + ${concepts.length - 1}` : "") ); } function onToggleAllConcepts(checked: boolean) { const allChecked = Object.keys(valuesChecked).reduce((all, key) => { all[key] = allConceptsSelected ? false : true; return all; }, {}); setValuesChecked(allChecked); } function onToggleConcept(idx: number, checked: boolean) { const nextValues = { ...valuesChecked, [idx]: checked, }; setValuesChecked(nextValues); } function onSubmit() { const selectedValues = Object.keys(valuesChecked) .filter((key) => valuesChecked[key]) .map((key) => formValues[selectedOption][key]); onAccept(selectedValues); onClose(); } return ( <Modal onClose={onClose} closeIcon headline={t("externalForms.copyModal.headline")} > <InputSelect label={t("externalForms.copyModal.selectLabel")} options={conceptListFieldOptions} input={{ onChange: setSelectedOption, value: selectedOption }} /> <SelectAllCheckbox label={t("externalForms.copyModal.selectAll")} input={{ value: allConceptsSelected, onChange: onToggleAllConcepts }} /> <Options> {Object.keys(valuesChecked).map((idx, i) => idxHasConcepts ? ( <SxInputCheckbox key={idx} label={getLabelFromIdx(idx)} input={{ value: valuesChecked[idx], onChange: (checked: boolean) => onToggleConcept(idx, checked), }} /> ) : null, )} </Options> <Buttons> <TransparentButton onClick={onClose}> {t("common.cancel")} </TransparentButton> <PrimaryButton onClick={onSubmit} disabled={isAcceptDisabled}> {t("externalForms.copyModal.accept")} </PrimaryButton> </Buttons> </Modal> ); }; export default FormConceptCopyModal;
manuel-hegner/conquery
frontend/src/js/timebased-query-editor/TimebasedQueryRunner.tsx
import { StateT } from "app-types"; import React, { FC } from "react"; import { useSelector } from "react-redux"; import { DatasetIdT, QueryIdT } from "../api/types"; import QueryRunner from "../query-runner/QueryRunner"; import { useStartQuery, useStopQuery } from "../query-runner/actions"; import { QueryRunnerStateT } from "../query-runner/reducer"; import { allConditionsFilled } from "./helpers"; import { TimebasedQueryStateT } from "./reducer"; const selectIsButtonEnabled = ( datasetId: DatasetIdT | null, queryRunner: QueryRunnerStateT | null, ) => (state: StateT) => { if (!queryRunner) return false; return !!( datasetId !== null && !queryRunner.startQuery.loading && !queryRunner.stopQuery.loading && allConditionsFilled(state.timebasedQueryEditor.timebasedQuery) ); }; const TimebasedQueryRunner = () => { const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); const queryRunner = useSelector<StateT, QueryRunnerStateT>( (state) => state.timebasedQueryEditor.timebasedQueryRunner, ); const isButtonEnabled = useSelector<StateT, boolean>( selectIsButtonEnabled(datasetId, queryRunner), ); const isQueryRunning = !!queryRunner.runningQuery; // Following ones only needed in dispatch functions const queryId = useSelector<StateT, QueryIdT | null>( (state) => state.timebasedQueryEditor.timebasedQueryRunner.runningQuery, ); const query = useSelector<StateT, TimebasedQueryStateT>( (state) => state.timebasedQueryEditor.timebasedQuery, ); const startTimebasedQuery = useStartQuery("timebased"); const stopTimebasedQuery = useStopQuery("timebased"); const startQuery = () => { if (datasetId) { startTimebasedQuery(datasetId, query); } }; const stopQuery = () => { if (datasetId && queryId) { stopTimebasedQuery(datasetId, queryId); } }; return ( <QueryRunner queryRunner={queryRunner} isButtonEnabled={isButtonEnabled} isQueryRunning={isQueryRunning} startQuery={startQuery} stopQuery={stopQuery} /> ); }; export default TimebasedQueryRunner;
manuel-hegner/conquery
frontend/src/js/query-node-editor/actions.ts
<reponame>manuel-hegner/conquery<filename>frontend/src/js/query-node-editor/actions.ts import { createActionTypes } from "./actionTypes"; export const createQueryNodeEditorActions = (type: string) => { const { SET_FOCUSED_INPUT, RESET } = createActionTypes(type); const setFocusedInput = (filterIdx: number) => ({ type: SET_FOCUSED_INPUT, filterIdx, }); const reset = () => ({ type: RESET }); return { setFocusedInput, reset, }; };
manuel-hegner/conquery
frontend/src/js/ui-components/VerticalToggleButton.tsx
import styled from "@emotion/styled"; import React from "react"; type PropsType = { className?: string; onToggle: (value: string) => void; activeValue: string; options: { label: string; value: string; }[]; }; const Btn = styled("p")` margin: 0 auto; `; export const Option = styled("span")<{ active?: boolean }>` font-size: ${({ theme }) => theme.font.xs}; display: block; padding: 2px 8px; cursor: pointer; transition: ${({ theme }) => `color ${theme.transitionTime}, background-color ${theme.transitionTime}`}; color: ${({ theme, active }) => (active ? theme.col.black : theme.col.gray)}; border-left: 1px solid ${({ theme }) => theme.col.blueGray}; border-right: 1px solid ${({ theme }) => theme.col.blueGray}; background-color: ${({ theme, active }) => active ? theme.col.blueGrayVeryLight : "white"}; &:first-of-type { margin-left: 0; /* first childs left border does not overlap */ border-top: 1px solid ${({ theme }) => theme.col.blueGray}; border-top-left-radius: 2px; border-top-right-radius: 2px; } &:last-of-type { border-bottom: 1px solid ${({ theme }) => theme.col.blueGray}; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; } &:hover { background-color: ${({ theme, active }) => active ? theme.col.blueGrayVeryLight : theme.col.grayVeryLight}; } `; const VerticalToggleButton = (props: PropsType) => { return ( <Btn className={props.className}> {props.options.map(({ value, label }, i) => ( <Option key={i} active={props.activeValue === value} onClick={() => { if (value !== props.activeValue) props.onToggle(value); }} > {label} </Option> ))} </Btn> ); }; export default VerticalToggleButton;
manuel-hegner/conquery
frontend/src/js/preview/Cell.ts
import { css } from "@emotion/react"; import styled from "@emotion/styled"; export const Cell = styled("code")<{ isDates?: boolean; isHeader?: boolean }>` padding: 1px 5px; font-size: ${({ theme }) => theme.font.xs}; height: ${({ theme }) => theme.font.xs}; min-width: ${({ isDates }) => (isDates ? "300px" : "100px")}; width: ${({ isDates }) => (isDates ? "auto" : "100px")}; flex-grow: ${({ isDates }) => (isDates ? "1" : "0")}; flex-shrink: 0; background-color: white; margin: 0; position: relative; text-overflow: ellipsis; white-space: nowrap; display: ${({ isDates }) => (isDates ? "flex" : "block")}; align-items: center; overflow: hidden; ${({ isHeader }) => isHeader && css` font-weight: 700; overflow-wrap: break-word; margin: 0 0 5px; text-overflow: initial; white-space: initial; height: initial; `}; `;
manuel-hegner/conquery
frontend/src/js/ui-components/InputMultiSelect/useResolvableSelect.ts
<gh_stars>10-100 import { useEffect } from "react"; import { SelectOptionT } from "../../api/types"; import { getUniqueFileRows } from "../../common/helpers"; import { usePrevious } from "../../common/helpers/usePrevious"; export const useResolvableSelect = ({ defaultValue, onResolve, }: { defaultValue?: SelectOptionT[]; onResolve?: (csvFileLines: string[]) => void; }) => { const previousDefaultValue = usePrevious(defaultValue); useEffect( function resolveDefault() { if (!onResolve) { return; } const hasDefaultValueToLoad = defaultValue && defaultValue.length > 0 && JSON.stringify(defaultValue) !== JSON.stringify(previousDefaultValue); if (hasDefaultValueToLoad) { onResolve(defaultValue.map((v) => String(v.value))); } }, [onResolve, previousDefaultValue, defaultValue], ); const onDropFile = async (file: File) => { const rows = await getUniqueFileRows(file); if (onResolve) { onResolve(rows); } }; return { onDropFile: onResolve ? onDropFile : undefined }; };
manuel-hegner/conquery
frontend/src/js/authorization/WithAuthToken.tsx
import { useKeycloak } from "@react-keycloak/web"; import React, { FC, useContext } from "react"; import { useHistory } from "react-router-dom"; import { isLoginDisabled, isIDPEnabled } from "../environment"; import { AuthTokenContext } from "./AuthTokenProvider"; import { storeAuthToken, getStoredAuthToken } from "./helper"; interface PropsT { location: { search: Object; }; } const WithAuthToken: FC<PropsT> = ({ location, children }) => { const history = useHistory(); const { initialized } = useKeycloak(); const { authToken } = useContext(AuthTokenContext); const goToLogin = () => history.push("/login"); const { search } = location; const params = new URLSearchParams(search); const accessToken = params.get("access_token"); if (accessToken) storeAuthToken(accessToken); if (isIDPEnabled && (!initialized || !authToken)) { return null; } if (!isIDPEnabled && !isLoginDisabled) { const authToken = getStoredAuthToken(); if (!authToken) { goToLogin(); return null; } } return <>{children}</>; }; export default WithAuthToken;
manuel-hegner/conquery
frontend/src/js/ui-components/Labeled.tsx
<reponame>manuel-hegner/conquery<gh_stars>0 import { css } from "@emotion/react"; import styled from "@emotion/styled"; import React, { ReactNode } from "react"; import { IndexPrefix } from "../common/components/IndexPrefix"; import { exists } from "../common/helpers/exists"; import InfoTooltip from "../tooltip/InfoTooltip"; import Label from "./Label"; import Optional from "./Optional"; const Root = styled("label")<{ fullWidth?: boolean }>` ${({ fullWidth }) => fullWidth && css` width: 100%; input { width: 100%; } `}; `; interface Props { label: ReactNode; indexPrefix?: number; className?: string; tinyLabel?: boolean; largeLabel?: boolean; fullWidth?: boolean; children?: React.ReactNode; optional?: boolean; tooltip?: string; htmlFor?: string; } const Labeled = ({ indexPrefix, className, fullWidth, label, tinyLabel, largeLabel, tooltip, optional, htmlFor, children, }: Props) => { return ( <Root className={className} fullWidth={fullWidth} htmlFor={htmlFor}> <Label fullWidth={fullWidth} tiny={tinyLabel} large={largeLabel}> {exists(indexPrefix) && <IndexPrefix># {indexPrefix}</IndexPrefix>} {optional && <Optional />} {label} {exists(tooltip) && <InfoTooltip text={tooltip} />} </Label> {children} </Root> ); }; export default Labeled;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/QueryClearButton.tsx
import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch } from "react-redux"; import IconButton from "../button/IconButton"; import WithTooltip from "../tooltip/WithTooltip"; import { clearQuery } from "./actions"; interface PropsT { className?: string; } const QueryClearButton: FC<PropsT> = ({ className }) => { const dispatch = useDispatch(); const onClearQuery = () => dispatch(clearQuery()); const { t } = useTranslation(); return ( <div className={className}> <WithTooltip text={t("queryEditor.clear")}> <IconButton tiny onClick={onClearQuery} regular icon="trash-alt" /> </WithTooltip> </div> ); }; export default QueryClearButton;
manuel-hegner/conquery
frontend/src/js/query-node-editor/FilterListMultiSelect.tsx
<gh_stars>10-100 import React, { FC, useEffect, useState } from "react"; import { usePostFilterValuesResolve } from "../api/api"; import type { FilterIdT, PostFilterResolveResponseT, SelectOptionT, } from "../api/types"; import { getUniqueFileRows } from "../common/helpers/fileHelper"; import { usePrevious } from "../common/helpers/usePrevious"; import AsyncInputMultiSelect from "../ui-components/AsyncInputMultiSelect"; import InputMultiSelect, { MultiSelectInputProps, } from "../ui-components/InputMultiSelect"; import type { FiltersContextT } from "./TableFilters"; import UploadFilterListModal from "./UploadFilterListModal"; interface FilterContextT extends FiltersContextT { filterId: FilterIdT; } interface PropsT { context: FilterContextT; label: string; indexPrefix?: number; options: SelectOptionT[]; disabled?: boolean; tooltip?: string; allowDropFile?: boolean; isLoading?: boolean; onLoad?: (prefix: string) => void; input: MultiSelectInputProps; } const FilterListMultiSelect: FC<PropsT> = ({ context, input, label, indexPrefix, options, disabled, allowDropFile, onLoad, isLoading, }) => { const [resolved, setResolved] = useState<PostFilterResolveResponseT | null>( null, ); const [loading, setLoading] = useState<boolean>(false); const [error, setError] = useState<boolean>(false); const [isModalOpen, setIsModalOpen] = useState<boolean>(false); const postFilterValuesResolve = usePostFilterValuesResolve(); const previousDefaultValue = usePrevious(input.defaultValue); // Can be both, an auto-completable (async) multi select or a regular one const Component = !!onLoad ? AsyncInputMultiSelect : InputMultiSelect; const onDropFile = async (file: File) => { setLoading(true); const rows = await getUniqueFileRows(file); try { const r = await postFilterValuesResolve( context.datasetId, context.treeId, context.tableId, context.filterId, rows, ); setResolved(r); setIsModalOpen(!!r.unknownCodes && r.unknownCodes.length > 0); if ( r.resolvedFilter && r.resolvedFilter.value && r.resolvedFilter.value.length > 0 ) { input.onChange(r.resolvedFilter.value); } } catch (e) { setError(true); } setLoading(false); }; useEffect(() => { async function resolveDefaultValue() { const hasDefaultValueToLoad = input.defaultValue && input.defaultValue.length > 0 && JSON.stringify(input.defaultValue) !== JSON.stringify(previousDefaultValue); if (hasDefaultValueToLoad) { const r = await postFilterValuesResolve( context.datasetId, context.treeId, context.tableId, context.filterId, input.defaultValue as string[], ); if ( r.resolvedFilter && r.resolvedFilter.value && r.resolvedFilter.value.length > 0 ) { input.onChange(r.resolvedFilter.value); } } } resolveDefaultValue(); }, [ context.datasetId, context.filterId, context.tableId, context.treeId, previousDefaultValue, input, postFilterValuesResolve, ]); return ( <> {allowDropFile && isModalOpen && ( <UploadFilterListModal resolved={resolved} loading={loading} error={error} onClose={() => setIsModalOpen(false)} /> )} <Component input={input} label={label} options={options} isLoading={isLoading || loading} disabled={disabled} indexPrefix={indexPrefix} onLoad={onLoad} onDropFile={onDropFile} allowDropFile={allowDropFile} /> </> ); }; export default FilterListMultiSelect;
manuel-hegner/conquery
frontend/src/js/query-node-editor/ResetAllFiltersButton.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import IconButton from "../button/IconButton"; import WithTooltip from "../tooltip/WithTooltip"; const SxWithTooltip = styled(WithTooltip)` text-transform: uppercase; white-space: nowrap; `; interface Props { compact?: boolean; onClick: () => void; } const ResetAllFiltersButton: FC<Props> = ({ compact, onClick }) => { const { t } = useTranslation(); return ( <SxWithTooltip text={compact ? t("queryNodeEditor.resetSettings") : undefined} > <IconButton active onClick={onClick} icon="undo"> {!compact && t("queryNodeEditor.resetSettings")} </IconButton> </SxWithTooltip> ); }; export default ResetAllFiltersButton;
manuel-hegner/conquery
frontend/src/js/external-forms/form-components/DropzoneList.tsx
<filename>frontend/src/js/external-forms/form-components/DropzoneList.tsx<gh_stars>10-100 import styled from "@emotion/styled"; import React, { ReactNode } from "react"; import { DropTargetMonitor } from "react-dnd"; import IconButton from "../../button/IconButton"; import InfoTooltip from "../../tooltip/InfoTooltip"; import Dropzone, { ChildArgs, PossibleDroppableObject, } from "../../ui-components/Dropzone"; import DropzoneWithFileInput, { DragItemFile, } from "../../ui-components/DropzoneWithFileInput"; import Label from "../../ui-components/Label"; import Optional from "../../ui-components/Optional"; const ListItem = styled("div")` position: relative; padding: 5px; box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1); background-color: white; border-radius: ${({ theme }) => theme.borderRadius}; margin-bottom: 5px; `; const StyledIconButton = styled(IconButton)` position: absolute; top: 0; right: 0; `; const Row = styled("div")` display: flex; align-items: center; `; interface PropsT<DroppableObject> { className?: string; label?: ReactNode; tooltip?: string; optional?: boolean; dropzoneChildren: (args: ChildArgs) => ReactNode; items: ReactNode[]; acceptedDropTypes: string[]; onDrop: ( props: DroppableObject | DragItemFile, monitor: DropTargetMonitor, ) => void; onDropFile?: (file: File) => void; onDelete: (idx: number) => void; disallowMultipleColumns?: boolean; } const DropzoneList = <DroppableObject extends PossibleDroppableObject>( props: PropsT<DroppableObject>, ) => { // allow at least one column const showDropzone = (props.items && props.items.length === 0) || !props.disallowMultipleColumns; const DropzoneClass = props.onDropFile ? DropzoneWithFileInput : Dropzone; return ( <div className={props.className}> <Row> {props.label && ( <Label> {props.optional && <Optional />} {props.label} </Label> )} {props.tooltip && <InfoTooltip text={props.tooltip} />} </Row> {props.items && props.items.length > 0 && ( <div> {props.items.map((item, i) => ( <ListItem key={i}> <StyledIconButton icon="times" onClick={() => props.onDelete(i)} /> {item} </ListItem> ))} </div> )} {showDropzone && ( <DropzoneClass acceptedDropTypes={props.acceptedDropTypes} onDrop={props.onDrop} onSelectFile={props.onDropFile!} > {props.dropzoneChildren} </DropzoneClass> )} </div> ); }; export default DropzoneList;
manuel-hegner/conquery
frontend/src/js/app/Content.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import { StateT } from "app-types"; import React from "react"; import { useSelector } from "react-redux"; import SplitPane from "react-split-pane"; import type { TabT } from "../pane/types"; import ActivateTooltip from "../tooltip/ActivateTooltip"; import Tooltip from "../tooltip/Tooltip"; import DndProvider from "./DndProvider"; import LeftPane from "./LeftPane"; import RightPane from "./RightPane"; // ADDING TO react-split-pane STYLES // Because otherwise, vertical panes don't expand properly in Safari const reactSplitPaneSafariFix = css` .vertical { height: 100%; } `; const Root = styled("div")` width: 100%; height: 100%; position: relative; ${reactSplitPaneSafariFix}; `; export interface ContentPropsT { rightTabs: TabT[]; } const Content = ({ rightTabs }: ContentPropsT) => { const displayTooltip = useSelector<StateT, boolean>( (state) => state.tooltip.displayTooltip, ); return ( <DndProvider> <Root> <SplitPane split="vertical" allowResize={displayTooltip} minSize={displayTooltip ? 200 : 30} maxSize={600} defaultSize={displayTooltip ? "18%" : 30} className={!displayTooltip ? "SplitPane--tooltip-fixed" : ""} > {displayTooltip ? <Tooltip /> : <ActivateTooltip />} <SplitPane split="vertical" minSize={350} maxSize={-300} defaultSize="39%" > <LeftPane /> <RightPane tabs={rightTabs} /> </SplitPane> </SplitPane> </Root> </DndProvider> ); }; // export default withRouter(DragDropContext(HTML5Backend)(ConnectedContent)); export default Content;
manuel-hegner/conquery
frontend/src/js/upload-concept-list-modal/actions.ts
import { useDispatch } from "react-redux"; import { ActionType, createAction, createAsyncAction } from "typesafe-actions"; import { usePostConceptsListToResolve } from "../api/api"; import type { ConceptIdT, PostConceptResolveResponseT } from "../api/types"; import { errorPayload, ErrorObject } from "../common/actions"; import { exists } from "../common/helpers/exists"; import { useDatasetId } from "../dataset/selectors"; export type UploadConceptListModalActions = ActionType< | typeof resolveConcepts | typeof selectConceptRootNode | typeof initUploadConceptListModal | typeof resetUploadConceptListModal >; export const resolveConcepts = createAsyncAction( "upload-concept-list-modal/RESOLVE_CONCEPTS_START", "upload-concept-list-modal/RESOLVE_CONCEPTS_SUCCESS", "upload-concept-list-modal/RESOLVE_CONCEPTS_ERROR", )< undefined, { data: PostConceptResolveResponseT; }, ErrorObject >(); export const selectConceptRootNode = createAction( "upload-concept-list-modal/SELECT_CONCEPT_ROOT_NODE", )<{ conceptId: ConceptIdT }>(); export const useSelectConceptRootNodeAndResolveCodes = () => { const dispatch = useDispatch(); const postConceptsListToResolve = usePostConceptsListToResolve(); const datasetId = useDatasetId(); return (treeId: string | null, conceptCodes: string[]) => { if (exists(treeId)) { dispatch(selectConceptRootNode({ conceptId: treeId })); } else { return dispatch(selectConceptRootNode({ conceptId: "" })); } if (!datasetId) { return; } dispatch(resolveConcepts.request()); return postConceptsListToResolve(datasetId, treeId, conceptCodes).then( (r) => dispatch(resolveConcepts.success({ data: r })), (e) => dispatch(resolveConcepts.failure(errorPayload(e, {}))), ); }; }; export const initUploadConceptListModal = createAction( "upload-concept-list-modal/INIT", )<{ rows: string[]; filename: string; }>(); export const resetUploadConceptListModal = createAction( "upload-concept-list-modal/RESET", )();
manuel-hegner/conquery
frontend/src/js/pane/Pane.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import PaneTabNavigation from "./PaneTabNavigation"; import { TabNavigationTab } from "./TabNavigation"; const Root = styled("div")<{ left?: boolean; right?: boolean }>` width: 100%; height: 100%; padding: ${({ left, right }) => (left || right ? "40px 0 10px" : "0")}; `; const Container = styled("div")` height: 100%; overflow: hidden; display: flex; flex-direction: column; position: relative; `; interface PropsT { tabs: TabNavigationTab[]; right?: boolean; left?: boolean; } const Pane: FC<PropsT> = ({ tabs, left, right, children }) => { const paneType = left ? "left" : "right"; return ( <Root left={left} right={right}> <Container> <PaneTabNavigation tabs={tabs} paneType={paneType} /> <Container>{children}</Container> </Container> </Root> ); }; export default Pane;
manuel-hegner/conquery
frontend/src/js/query-runner/QueryRunningProgress.tsx
<gh_stars>10-100 import styled from "@emotion/styled"; import React, { FC } from "react"; const ProgressText = styled("div")` font-size: ${({ theme }) => theme.font.lg}; margin-right: 10px; font-weight: 700; color: ${({ theme }) => theme.col.blueGray}; `; // progress is between 0 and 1 interface Props { progress: number; } const QueryRunningProgress: FC<Props> = ({ progress }) => { return <ProgressText>{Math.round(progress * 100)} %</ProgressText>; }; export default QueryRunningProgress;
manuel-hegner/conquery
frontend/src/js/small-tab-navigation/SmallTabNavigation.tsx
import React, { FC } from "react"; import InfoTooltip from "../tooltip/InfoTooltip"; import SmallTabNavigationButton from "./SmallTabNavigationButton"; export interface TabOption { label: string; value: string; tooltip?: string; } interface PropsT { className?: string; size?: "M" | "L"; options: TabOption[]; selectedTab: string; onSelectTab: (tab: string) => void; } const SmallTabNavigation: FC<PropsT> = ({ className, size = "M", options, selectedTab, onSelectTab, }) => { return ( <div className={className}> {options.map((option) => ( <SmallTabNavigationButton key={option.value} value={option.value} size={size} isSelected={selectedTab === option.value} onClick={() => onSelectTab(option.value)} > {option.label} {option.tooltip && <InfoTooltip text={option.tooltip} />} </SmallTabNavigationButton> ))} </div> ); }; export default SmallTabNavigation;
manuel-hegner/conquery
frontend/src/js/model/filter.ts
<gh_stars>10-100 import type { BigMultiSelectFilterT, FilterT, MultiSelectFilterT, } from "../api/types"; const filterWithDefaults = (filter: FilterT) => { switch (filter.type) { case "MULTI_SELECT": case "BIG_MULTI_SELECT": return { ...filter, value: filter.defaultValue || [], }; default: return { ...filter, value: filter.defaultValue || null, }; } }; export const filtersWithDefaults = (filters?: FilterT[]) => filters ? filters.map(filterWithDefaults) : []; export const isMultiSelectFilter = ( filter: FilterT, ): filter is BigMultiSelectFilterT | MultiSelectFilterT => filter.type === "MULTI_SELECT" || filter.type === "BIG_MULTI_SELECT";
manuel-hegner/conquery
frontend/src/js/previous-queries/list/PreviousQueriesTab.tsx
<reponame>manuel-hegner/conquery<gh_stars>10-100 import { css } from "@emotion/react"; import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import SplitPane from "react-split-pane"; import type { DatasetIdT } from "../../api/types"; import { usePrevious } from "../../common/helpers/usePrevious"; import EmptyList from "../../list/EmptyList"; import { canUploadResult } from "../../user/selectors"; import PreviousQueriesFilter from "../filter/PreviousQueriesFilter"; import type { PreviousQueriesFilterStateT } from "../filter/reducer"; import { toggleFoldersOpen } from "../folderFilter/actions"; import PreviousQueriesSearchBox from "../search/PreviousQueriesSearchBox"; import UploadQueryResults from "../upload/UploadQueryResults"; import PreviousQueries from "./PreviousQueries"; import PreviousQueriesFolderButton from "./PreviousQueriesFolderButton"; import PreviousQueriesFolders from "./PreviousQueriesFolders"; import { useLoadQueries } from "./actions"; import type { PreviousQueryT } from "./reducer"; import { selectPreviousQueries } from "./selector"; const ScrollContainer = styled("div")` overflow-y: auto; -webkit-overflow-scrolling: touch; font-size: ${({ theme }) => theme.font.sm}; `; const Row = styled("div")` display: flex; align-items: flex-start; margin: 0 10px; `; const FoldersAndQueries = styled(Row)` flex-grow: 1; margin-top: 8px; overflow: hidden; position: relative; `; const SxPreviousQueriesSearchBox = styled(PreviousQueriesSearchBox)` flex-grow: 1; `; const SxPreviousQueriesFilter = styled(PreviousQueriesFilter)` margin-top: 5px; display: flex; align-items: flex-start; `; const SxUploadQueryResults = styled(UploadQueryResults)` margin-left: 5px; `; const SxPreviousQueriesFolders = styled(PreviousQueriesFolders)` padding: 8px 8px 8px 0; `; const Expand = styled("div")<{ areFoldersOpen?: boolean }>` flex-grow: 1; display: flex; flex-direction: column; height: 100%; ${({ areFoldersOpen }) => areFoldersOpen && css` padding-left: 8px; `} `; interface PropsT { datasetId: DatasetIdT | null; } const PreviousQueryEditorTab = ({ datasetId }: PropsT) => { const { t } = useTranslation(); const allQueries = useSelector<StateT, PreviousQueryT[]>( (state) => state.previousQueries.queries, ); const searchTerm = useSelector<StateT, string | null>( (state) => state.previousQueriesSearch.searchTerm, ); const filter = useSelector<StateT, PreviousQueriesFilterStateT>( (state) => state.previousQueriesFilter, ); const folders = useSelector<StateT, string[]>( (state) => state.previousQueriesFolderFilter.folders, ); const noFoldersActive = useSelector<StateT, boolean>( (state) => state.previousQueriesFolderFilter.noFoldersActive, ); const queries = selectPreviousQueries( allQueries, searchTerm, filter, folders, noFoldersActive, ); const loading = useSelector<StateT, boolean>( (state) => state.previousQueries.loading, ); const hasPermissionToUpload = useSelector<StateT, boolean>((state) => canUploadResult(state), ); const loadQueries = useLoadQueries(); useEffect(() => { if (datasetId) { loadQueries(datasetId); } }, [datasetId]); const areFoldersOpen = useSelector<StateT, boolean>( (state) => state.previousQueriesFolderFilter.areFoldersOpen, ); const wereFoldersOpen = usePrevious(areFoldersOpen); const dispatch = useDispatch(); const onToggleFoldersOpen = () => dispatch(toggleFoldersOpen()); const [leftPaneSize, setLeftPaneSize] = useState<number | string>(0); const [storedPaneSize, setStoredPaneSize] = useState<number | string>(0); useEffect(() => { if (areFoldersOpen === wereFoldersOpen) { return; } if (!areFoldersOpen) { setStoredPaneSize(leftPaneSize); setLeftPaneSize(0); } else { setLeftPaneSize(storedPaneSize || "25%"); } }, [leftPaneSize, storedPaneSize, areFoldersOpen, wereFoldersOpen]); return ( <> <Row> <PreviousQueriesFolderButton active={areFoldersOpen} onClick={onToggleFoldersOpen} /> <SxPreviousQueriesSearchBox /> {hasPermissionToUpload && ( <SxUploadQueryResults datasetId={datasetId} /> )} </Row> <FoldersAndQueries> <SplitPane split="vertical" allowResize={true} minSize={100} size={leftPaneSize} maxSize={600} defaultSize={"25%"} onDragFinished={(newSize) => setLeftPaneSize(newSize)} resizerStyle={{ zIndex: 0, // To set below overlaying dropdowns marginTop: "35px", display: areFoldersOpen ? "inherit" : "none", }} > <SxPreviousQueriesFolders /> <Expand areFoldersOpen={areFoldersOpen}> <SxPreviousQueriesFilter /> <ScrollContainer> {queries.length === 0 && !loading && ( <EmptyList emptyMessage={t("previousQueries.noQueriesFound")} /> )} </ScrollContainer> <PreviousQueries queries={queries} datasetId={datasetId} /> </Expand> </SplitPane> </FoldersAndQueries> </> ); }; export default PreviousQueryEditorTab;
manuel-hegner/conquery
frontend/src/js/external-forms/form-configs/search/FormConfigsSearchBox.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import { StateT } from "app-types"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import ReactSelect from "../../../ui-components/ReactSelect"; import { setFormConfigsSearch } from "./actions"; const Root = styled("div")` margin: 0 10px 5px; position: relative; `; const FormConfigsSearchBox: React.FC = () => { const { t } = useTranslation(); const search = useSelector<StateT, string[]>( (state) => state.formConfigsSearch, ); const options = useSelector<StateT, string[]>( (state) => state.formConfigs.names, ); const dispatch = useDispatch(); const onSearch = (values: string[]) => dispatch(setFormConfigsSearch(values)); return ( <Root> <ReactSelect creatable isMulti name="input" value={search.map((t) => ({ label: t, value: t }))} options={options ? options.map((t) => ({ label: t, value: t })) : []} onChange={(values) => onSearch(values ? values.map((v) => v.value) : []) } placeholder={t("inputSelect.searchPlaceholder")} noOptionsMessage={() => t("inputSelect.empty")} formatCreateLabel={(inputValue) => t("common.create") + `: "${inputValue}"` } /> </Root> ); }; export default FormConfigsSearchBox;
manuel-hegner/conquery
frontend/.storybook/preview.tsx
<reponame>manuel-hegner/conquery<gh_stars>10-100 import { ThemeProvider } from "@emotion/react"; import { addDecorator } from "@storybook/react"; import React from "react"; import { theme } from "../src/app-theme"; import GlobalStyles from "../src/js/GlobalStyles"; import DndProvider from "../src/js/app/DndProvider"; import i18next from "../src/js/localization/i18next"; import translationsDe from "../src/localization/de.json"; i18next.addResourceBundle("de", "translation", translationsDe, true, true); i18next.changeLanguage("de"); export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, controls: { matchers: { color: /(background|color)$/i, date: /Date$/, }, }, }; addDecorator((Story) => { return ( <ThemeProvider theme={theme}> <DndProvider> <GlobalStyles /> <Story /> </DndProvider> </ThemeProvider> ); });
manuel-hegner/conquery
frontend/src/js/previous-queries/list/actions.ts
<reponame>manuel-hegner/conquery import { StateT } from "app-types"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { ActionType, createAction, createAsyncAction } from "typesafe-actions"; import { useGetQueries, usePatchQuery, useGetQuery, useDeleteQuery, } from "../../api/api"; import { DatasetIdT, GetQueriesResponseT, GetQueryResponseT, QueryIdT, } from "../../api/types"; import { ErrorObject, errorPayload } from "../../common/actions"; import { useDatasetId } from "../../dataset/selectors"; import { setMessage } from "../../snack-message/actions"; import { PreviousQueryIdT } from "./reducer"; export type PreviousQueryListActions = ActionType< | typeof loadQueries | typeof loadQuery | typeof renameQuery | typeof retagQuery | typeof shareQuerySuccess | typeof deleteQuerySuccess >; export const loadQueries = createAsyncAction( "queries/LOAD_QUERIES_START", "queries/LOAD_QUERIES_SUCCESS", "queries/LOAD_QUERIES_ERROR", )<undefined, { data: GetQueriesResponseT }, ErrorObject>(); export const useLoadQueries = () => { const { t } = useTranslation(); const dispatch = useDispatch(); const getQueries = useGetQueries(); return async (datasetId: DatasetIdT) => { dispatch(loadQueries.request()); try { const data = await getQueries(datasetId); return dispatch(loadQueries.success({ data })); } catch (e) { dispatch(setMessage({ message: t("previousQueries.error") })); return dispatch(loadQueries.failure(errorPayload(e, {}))); } }; }; interface QueryContext { queryId: QueryIdT; } export const loadQuery = createAsyncAction( "queries/LOAD_QUERY_START", "queries/LOAD_QUERY_SUCCESS", "queries/LOAD_QUERY_ERROR", )< QueryContext, QueryContext & { data: GetQueryResponseT }, QueryContext & ErrorObject >(); export const useLoadQuery = () => { const dispatch = useDispatch(); const getQuery = useGetQuery(); const { t } = useTranslation(); return (datasetId: DatasetIdT, queryId: PreviousQueryIdT) => { dispatch(loadQuery.request({ queryId })); return getQuery(datasetId, queryId).then( (r) => dispatch(loadQuery.success({ queryId, data: r })), () => dispatch( loadQuery.failure({ queryId, message: t("previousQuery.loadError"), }), ), ); }; }; export const renameQuery = createAsyncAction( "queries/RENAME_QUERY_START", "queries/RENAME_QUERY_SUCCESS", "queries/RENAME_QUERY_ERROR", )<QueryContext, QueryContext & { label: string }, QueryContext & ErrorObject>(); export const useRenameQuery = () => { const dispatch = useDispatch(); const patchQuery = usePatchQuery(); const { t } = useTranslation(); return (datasetId: DatasetIdT, queryId: PreviousQueryIdT, label: string) => { dispatch(renameQuery.request({ queryId })); return patchQuery(datasetId, queryId, { label }).then( () => dispatch(renameQuery.success({ queryId, label })), () => dispatch( renameQuery.failure({ queryId, message: t("previousQuery.renameError"), }), ), ); }; }; export const retagQuery = createAsyncAction( "queries/RETAG_QUERY_START", "queries/RETAG_QUERY_SUCCESS", "queries/RETAG_QUERY_ERROR", )< QueryContext, QueryContext & { tags: string[] }, QueryContext & ErrorObject >(); export const useRetagQuery = () => { const dispatch = useDispatch(); const patchQuery = usePatchQuery(); const datasetId = useDatasetId(); const { t } = useTranslation(); return (queryId: PreviousQueryIdT, tags: string[]) => { if (!datasetId) { return Promise.resolve(); } dispatch(retagQuery.request({ queryId })); return patchQuery(datasetId, queryId, { tags }).then( () => { dispatch(retagQuery.success({ queryId, tags })); }, () => dispatch( retagQuery.failure({ queryId, message: t("previousQuery.retagError"), }), ), ); }; }; export const shareQuerySuccess = createAction( "queries/TOGGLE_SHARE_QUERY_SUCCESS", )<{ queryId: string; groups: PreviousQueryIdT[]; }>(); export const deleteQuerySuccess = createAction("queries/DELETE_QUERY_SUCCESS")<{ queryId: string; }>(); export const useRemoveQuery = ( queryId: PreviousQueryIdT, onSuccess?: () => void, ) => { const { t } = useTranslation(); const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); const dispatch = useDispatch(); const deleteQuery = useDeleteQuery(); return async () => { if (!datasetId) return; try { await deleteQuery(datasetId, queryId); dispatch(deleteQuerySuccess({ queryId })); if (onSuccess) { onSuccess(); } } catch (e) { dispatch(setMessage({ message: t("previousQuery.deleteError") })); } }; };
manuel-hegner/conquery
frontend/src/keycloak.ts
import Keycloak from "keycloak-js"; import { idpUrl, idpRealm, idpClientId } from "./js/environment"; // Setup Keycloak instance as needed // Pass initialization options as required or leave blank to load from 'keycloak.json' const keycloak = Keycloak({ url: idpUrl, realm: idpRealm, clientId: idpClientId, }); export default keycloak;
manuel-hegner/conquery
frontend/src/js/previous-queries/folderFilter/reducer.ts
<gh_stars>10-100 import { getType } from "typesafe-actions"; import type { Action } from "../../app/actions"; import { getUserSettings, storeUserSettings } from "../../user/userSettings"; import { addFolderToFilter, removeFolderFromFilter, setFolderFilter, toggleFoldersOpen, toggleNoFoldersFilter, } from "./actions"; export type PreviousQueriesFolderFilterStateT = { folders: string[]; noFoldersActive: boolean; areFoldersOpen: boolean; }; const initialState: PreviousQueriesFolderFilterStateT = { folders: [], noFoldersActive: false, areFoldersOpen: getUserSettings().arePreviousQueriesFoldersOpen, }; const reducer = ( state: PreviousQueriesFolderFilterStateT = initialState, action: Action, ): PreviousQueriesFolderFilterStateT => { switch (action.type) { case getType(setFolderFilter): return { ...state, noFoldersActive: false, folders: action.payload }; case getType(addFolderToFilter): return { ...state, noFoldersActive: false, folders: [...state.folders, action.payload], }; case getType(removeFolderFromFilter): const { folders } = state; const idx = folders.indexOf(action.payload); if (idx === -1) return state; return { ...state, noFoldersActive: false, folders: [...folders.slice(0, idx), ...folders.slice(idx + 1)], }; case getType(toggleNoFoldersFilter): return { ...state, noFoldersActive: !state.noFoldersActive, folders: [] }; case getType(toggleFoldersOpen): storeUserSettings({ arePreviousQueriesFoldersOpen: !state.areFoldersOpen, }); return { ...state, areFoldersOpen: !state.areFoldersOpen }; default: return state; } }; export default reducer;
manuel-hegner/conquery
frontend/src/js/external-forms/form/Form.tsx
<filename>frontend/src/js/external-forms/form/Form.tsx<gh_stars>10-100 import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { useMemo, useCallback } from "react"; import { TFunction, useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import { reduxForm, formValueSelector } from "redux-form"; import type { SelectOptionT } from "../../api/types"; import type { DatasetT } from "../../dataset/reducer"; import { useActiveLang } from "../../localization/useActiveLang"; import FormConfigSaver from "../FormConfigSaver"; import FormHeader from "../FormHeader"; import type { Form as FormType, FormField as FormFieldType, } from "../config-types"; import { collectAllFormFields, isFormField, isOptionalField } from "../helper"; import { selectReduxFormState } from "../stateSelectors"; import { validateRequired, validateDateRange, validatePositive, validateConceptGroupFilled, validateDateRangeRequired, } from "../validators"; import Field from "./Field"; const DEFAULT_VALUE_BY_TYPE = { STRING: "", NUMBER: null, CHECKBOX: false, CONCEPT_LIST: [], RESULT_GROUP: null, MULTI_RESULT_GROUP: [], SELECT: null, TABS: null, DATASET_SELECT: null, MULTI_SELECT: null, DATE_RANGE: { min: null, max: null, }, }; const DEFAULT_VALIDATION_BY_TYPE = { STRING: null, NUMBER: null, CHECKBOX: null, CONCEPT_LIST: null, RESULT_GROUP: null, MULTI_RESULT_GROUP: null, SELECT: null, TABS: null, DATASET_SELECT: null, MULTI_SELECT: null, DATE_RANGE: validateDateRange, }; const SxFormHeader = styled(FormHeader)` margin: 5px 0 15px; `; function getNotEmptyValidation(fieldType: string) { switch (fieldType) { case "CONCEPT_LIST": return validateConceptGroupFilled; case "DATE_RANGE": return validateDateRangeRequired; default: return validateRequired; } } function getPossibleValidations(fieldType: string) { return { NOT_EMPTY: getNotEmptyValidation(fieldType), GREATER_THAN_ZERO: validatePositive, }; } function getInitialValue( field: FormFieldType, context: { availableDatasets: SelectOptionT[] }, ) { if (field.type === "DATASET_SELECT" && context.availableDatasets.length > 0) { return context.availableDatasets[0].value; } return field.defaultValue || DEFAULT_VALUE_BY_TYPE[field.type]; } function getErrorForField(t: TFunction, field: FormFieldType, value: any) { const defaultValidation = DEFAULT_VALIDATION_BY_TYPE[field.type]; let error = defaultValidation ? defaultValidation(t, value) : null; if (!!field.validations && field.validations.length > 0) { for (let validation of field.validations) { const validateFn = getPossibleValidations(field.type)[validation]; if (validateFn) { error = error || validateFn(t, value); } else { console.error( "Validation configured that is not supported: ", validation, "for field", field.name, ); } } } return error; } interface ConfiguredFormPropsType { config: FormType; } interface Props { config: FormType; availableDatasets: SelectOptionT[]; } const Form = React.memo(({ config, availableDatasets }: Props) => { // TODO: THIS REALLY ISN'T IDEAL, // AS THE WHOLE FORM HAS TO RERENDER ON EVERY STATE CHANGE // WE WILL NEED TO MIGRATE AWAY FROM REDUX-FORM SOON const state = useSelector<StateT, StateT>((state) => state); const getFieldValue = useCallback( (fieldname: string) => { const fieldValueSelector = formValueSelector( config.type, selectReduxFormState, ); return fieldValueSelector(state, fieldname); }, [state, config.type], ); const activeLang = useActiveLang(); return ( <form> {config.description && config.description[activeLang] && ( <SxFormHeader description={config.description[activeLang]!} /> )} <FormConfigSaver /> {config.fields.map((field, i) => { const key = isFormField(field) ? field.name : field.type + i; const optional = isOptionalField(field); return ( <Field key={key} formType={config.type} getFieldValue={() => isFormField(field) ? getFieldValue(field.name) : null } field={field} availableDatasets={availableDatasets} locale={activeLang} optional={optional} /> ); })} </form> ); }); // This is the generic form component that receives a form config // and builds all fields from there. // // Note: The config contains the fields in a hierarchical structure, // because one of the fields is a "TAB", which contains subfields // depending on the tab, that is selected const ConfiguredForm = ({ config, ...props }: ConfiguredFormPropsType) => { const { t } = useTranslation(); const availableDatasets = useSelector<StateT, DatasetT[]>( (state) => state.datasets.data, ); const datasetOptions = useMemo( () => availableDatasets.map((dataset) => ({ label: dataset.label, value: dataset.id, })), [availableDatasets], ); const allFields = collectAllFormFields(config.fields); const ReduxFormConnectedForm = reduxForm({ form: config.type, getFormState: selectReduxFormState, initialValues: Object.fromEntries( allFields.map((field) => [ field.name, getInitialValue(field, { availableDatasets: datasetOptions }), ]), ), destroyOnUnmount: false, validate: (values) => Object.keys(values).reduce((errors, name) => { const field = allFields.find((field) => field.name === name); // Note: For some reason, redux form understands, that: // EVEN IF we add errors for ALL fields – // including those fields that are not shown, // because their tab is hidden – as long as those // fields are not "rendered", the form seems to be valid // // => Otherwise, we'd have to check which tab is selected here, // and which errors to add const error = getErrorForField(t, field, values[name]); if (error) { errors[name] = error; } return errors; }, {}), })(Form); return ( <ReduxFormConnectedForm {...props} config={config} availableDatasets={datasetOptions} /> ); }; export default ConfiguredForm;
manuel-hegner/conquery
frontend/src/js/external-forms/form-configs/FormConfig.tsx
import { css } from "@emotion/react"; import styled from "@emotion/styled"; import type { StateT } from "app-types"; import { parseISO } from "date-fns"; import React, { useState, useRef } from "react"; import { useDrag } from "react-dnd"; import { useTranslation } from "react-i18next"; import { useSelector, useDispatch } from "react-redux"; import { usePatchFormConfig } from "../../api/api"; import { getWidthAndHeight } from "../../app/DndProvider"; import IconButton from "../../button/IconButton"; import { FORM_CONFIG } from "../../common/constants/dndTypes"; import { useFormatDateDistance } from "../../common/helpers"; import { useDatasetId } from "../../dataset/selectors"; import SelectableLabel from "../../highlightable-label/HighlightableLabel"; import FaIcon from "../../icon/FaIcon"; import { setMessage } from "../../snack-message/actions"; import WithTooltip from "../../tooltip/WithTooltip"; import EditableTags from "../../ui-components/EditableTags"; import EditableText from "../../ui-components/EditableText"; import { useFormLabelByType } from "../stateSelectors"; import FormConfigTags from "./FormConfigTags"; import { patchFormConfigSuccess } from "./actions"; import { FormConfigT } from "./reducer"; import { useIsLabelHighlighted } from "./selectors"; const Root = styled("div")<{ own: boolean; system: boolean; shared: boolean }>` margin: 0; padding: 5px 10px; cursor: pointer; border-radius: ${({ theme }) => theme.borderRadius}; border: 1px solid ${({ theme }) => theme.col.grayLight}; background-color: ${({ theme }) => theme.col.bg}; box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2); border-left: ${({ theme, own, system }) => own ? `4px solid ${theme.col.orange}` : system ? `4px solid ${theme.col.blueGrayDark}` : `1px solid ${theme.col.grayLight}`}; &:hover { ${({ theme, own, system }) => !own && !system && css` border-left-color: ${theme.col.blueGray}; `}; border-top-color: ${({ theme }) => theme.col.blueGray}; border-right-color: ${({ theme }) => theme.col.blueGray}; border-bottom-color: ${({ theme }) => theme.col.blueGray}; } `; const Gray = styled("div")` color: ${({ theme }) => theme.col.gray}; `; const TopInfos = styled(Gray)` line-height: 24px; `; const MiddleRight = styled(Gray)` text-align: right; `; const TopRight = styled("div")` float: right; `; const SharedIndicator = styled("span")` margin-left: 10px; color: ${({ theme }) => theme.col.blueGray}; `; const StyledSelectableLabel = styled(SelectableLabel)` margin: 0; font-weight: 400; word-break: break-word; `; const StyledEditableText = styled(EditableText)` margin: 0; font-weight: 400; word-break: break-word; `; const MiddleRow = styled("div")` display: flex; width: 100%; justify-content: space-between; line-height: 24px; `; const StyledFaIcon = styled(FaIcon)` margin: 0 6px; `; const StyledWithTooltip = styled(WithTooltip)` margin-left: 10px; `; export interface DragItemFormConfig { width: number; height: number; type: "FORM_CONFIG"; id: string; label: string; } interface PropsT { config: FormConfigT; onIndicateDeletion: () => void; onIndicateShare: () => void; } const FormConfig: React.FC<PropsT> = ({ config, onIndicateDeletion, onIndicateShare, }) => { const { t } = useTranslation(); const datasetId = useDatasetId(); const ref = useRef<HTMLDivElement | null>(null); const formLabel = useFormLabelByType(config.formType); const availableTags = useSelector<StateT, string[]>( (state) => state.formConfigs.tags, ); const formatDateDistance = useFormatDateDistance(); const createdAt = config.createdAt ? formatDateDistance(parseISO(config.createdAt), new Date(), true) : ""; const [isLoading, setIsLoading] = useState<boolean>(false); const [isEditingLabel, setIsEditingLabel] = useState<boolean>(false); const [isEditingTags, setIsEditingTags] = useState<boolean>(false); const label = config.label || config.id.toString(); const isLabelHighlighted = useIsLabelHighlighted(label); const mayEdit = config.own || config.shared; const isNotEditing = !(isEditingLabel || isEditingTags); const dispatch = useDispatch(); const patchFormConfig = usePatchFormConfig(); const onPatchFormConfig = async ( attributes: { shared?: boolean; label?: string; tags?: string[]; }, errorMessage: string, ) => { if (!datasetId) return; setIsLoading(true); try { await patchFormConfig(datasetId, config.id, attributes); dispatch(patchFormConfigSuccess(config.id, attributes)); } catch (e) { dispatch(setMessage({ message: errorMessage })); } setIsLoading(false); }; const onRenameFormConfig = async (label: string) => { await onPatchFormConfig({ label }, t("formConfig.renameError")); setIsEditingLabel(false); }; const onRetagFormConfig = async (tags: string[]) => { await onPatchFormConfig({ tags }, t("formConfig.retagError")); setIsEditingTags(false); }; const item: DragItemFormConfig = { height: 0, width: 0, type: FORM_CONFIG, id: config.id, label: config.label, }; const [, drag] = useDrag<DragItemFormConfig, void, {}>({ item, begin: () => ({ ...item, ...getWidthAndHeight(ref), }), }); return ( <Root ref={(instance) => { ref.current = instance; if (isNotEditing) { drag(instance); } }} own={!!config.own} shared={!!config.shared} system={!!config.system || (!config.own && !config.shared)} > <TopInfos> <div> {formLabel} {config.own && config.shared && ( <SharedIndicator onClick={onIndicateShare}> {t("common.shared")} </SharedIndicator> )} <TopRight> {createdAt} {mayEdit && !isEditingTags && (!config.tags || config.tags.length === 0) && ( <StyledWithTooltip text={t("common.addTag")}> <IconButton icon="tags" bare onClick={() => setIsEditingTags(!isEditingTags)} /> </StyledWithTooltip> )} {config.own && !config.shared && ( <StyledWithTooltip text={t("common.share")}> <IconButton icon="upload" bare onClick={onIndicateShare} /> </StyledWithTooltip> )} {isLoading ? ( <StyledFaIcon icon="spinner" /> ) : ( config.own && ( <StyledWithTooltip text={t("common.delete")}> <IconButton icon="times" bare onClick={onIndicateDeletion} /> </StyledWithTooltip> ) )} </TopRight> </div> </TopInfos> <MiddleRow> {mayEdit ? ( <StyledEditableText isHighlighted={isLabelHighlighted} loading={isLoading} text={label} selectTextOnMount={true} editing={isEditingLabel} onSubmit={onRenameFormConfig} onToggleEdit={() => setIsEditingLabel(!isEditingLabel)} /> ) : ( <StyledSelectableLabel>{label}</StyledSelectableLabel> )} <MiddleRight>{config.ownerName}</MiddleRight> </MiddleRow> {mayEdit ? ( <EditableTags tags={config.tags} isEditing={isEditingTags} setIsEditing={setIsEditingTags} loading={isLoading} onSubmit={onRetagFormConfig} tagComponent={<FormConfigTags tags={config.tags} />} availableTags={availableTags} /> ) : ( <FormConfigTags tags={config.tags} /> )} </Root> ); }; export default FormConfig;
manuel-hegner/conquery
frontend/src/js/previous-queries/list/PreviousQueryDragContainer.tsx
import React, { FC, useRef } from "react"; import { useDrag } from "react-dnd"; import { DatasetIdT } from "../../api/types"; import { getWidthAndHeight } from "../../app/DndProvider"; import { PREVIOUS_QUERY, PREVIOUS_SECONDARY_ID_QUERY, } from "../../common/constants/dndTypes"; import type { DragItemQuery } from "../../standard-query-editor/types"; import PreviousQuery from "./PreviousQuery"; import { PreviousQueryT } from "./reducer"; interface PropsT { query: PreviousQueryT; datasetId: DatasetIdT; onIndicateDeletion: () => void; onIndicateShare: () => void; onIndicateEditFolders: () => void; } const PreviousQueryDragContainer: FC<PropsT> = ({ query, ...props }) => { const ref = useRef<HTMLDivElement | null>(null); const dragType = query.queryType === "CONCEPT_QUERY" ? PREVIOUS_QUERY : PREVIOUS_SECONDARY_ID_QUERY; const item: DragItemQuery = { width: 0, height: 0, type: dragType, id: query.id, label: query.label, isPreviousQuery: true, canExpand: query.canExpand, tags: query.tags, own: query.own, shared: query.shared, }; const [, drag] = useDrag<DragItemQuery, void, {}>({ item, begin: () => ({ ...item, ...getWidthAndHeight(ref), }), }); return ( <PreviousQuery ref={(instance) => { ref.current = instance; drag(instance); }} query={query} {...props} /> ); }; export default PreviousQueryDragContainer;
manuel-hegner/conquery
frontend/src/js/external-forms/form/Field.tsx
<filename>frontend/src/js/external-forms/form/Field.tsx import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; import { Field as RxFormField } from "redux-form"; import type { SelectOptionT } from "../../api/types"; import { nodeIsInvalid } from "../../model/node"; import InputCheckbox from "../../ui-components/InputCheckbox"; import InputDateRange from "../../ui-components/InputDateRange"; import InputPlain from "../../ui-components/InputPlain"; import InputSelect from "../../ui-components/InputSelect"; import ToggleButton from "../../ui-components/ToggleButton"; import FormField from "../common/FormField"; import type { GeneralField } from "../config-types"; import { Description } from "../form-components/Description"; import { Headline } from "../form-components/Headline"; import FormConceptGroup from "../form-concept-group/FormConceptGroup"; import { FormQueryDropzone, FormMultiQueryDropzone, } from "../form-query-dropzone"; import FormTabNavigation from "../form-tab-navigation/FormTabNavigation"; import { isFormField, isOptionalField } from "../helper"; const TabsField = styled("div")``; // Pre-set field components to avoid re-rendering, // => Avoids losing input focus. const Plain = FormField(InputPlain); const QueryDropzone = FormField(FormQueryDropzone); const MultiQueryDropzone = FormField(FormMultiQueryDropzone); const DateRange = FormField(InputDateRange); const ConceptGroup = FormField(FormConceptGroup); const Select = FormField(InputSelect); const Checkbox = FormField(InputCheckbox); const Tabs = FormField(TabsField); const SxToggleButton = styled(ToggleButton)` margin-bottom: 5px; `; const NestedFields = styled("div")` padding: 10px; box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.2); `; interface PropsT { formType: string; field: GeneralField; getFieldValue: () => any; locale: "de" | "en"; availableDatasets: SelectOptionT[]; optional?: boolean; } const Field = ({ field, ...commonProps }: PropsT) => { const { formType, optional, locale, availableDatasets, getFieldValue } = commonProps; const { t } = useTranslation(); switch (field.type) { case "HEADLINE": return <Headline>{field.label[locale]}</Headline>; case "DESCRIPTION": return ( <Description dangerouslySetInnerHTML={{ __html: field.label[locale] || "" }} /> ); case "STRING": return ( <RxFormField name={field.name} component={Plain} props={{ inputType: "text", label: field.label[locale], placeholder: (field.placeholder && field.placeholder[locale]) || "", fullWidth: field.style ? field.style.fullWidth : false, tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "NUMBER": return ( <RxFormField name={field.name} component={Plain} props={{ inputType: "number", label: field.label[locale], placeholder: (field.placeholder && field.placeholder[locale]) || "", inputProps: { step: field.step || "1", pattern: field.pattern, min: field.min, max: field.max, }, tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "DATE_RANGE": return ( <RxFormField name={field.name} component={DateRange} props={{ inline: true, label: field.label[locale], tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "RESULT_GROUP": return ( <RxFormField name={field.name} component={QueryDropzone} props={{ label: field.label[locale], dropzoneText: field.dropzoneLabel[locale], tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "MULTI_RESULT_GROUP": return ( <RxFormField name={field.name} component={MultiQueryDropzone} props={{ label: field.label[locale], dropzoneChildren: () => field.dropzoneLabel[locale], tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "CHECKBOX": return ( <RxFormField name={field.name} component={Checkbox} props={{ label: field.label[locale], infoTooltip: field.tooltip ? field.tooltip[locale] : undefined, }} /> ); case "SELECT": return ( <RxFormField name={field.name} component={Select} props={{ label: field.label[locale], options: field.options.map((option) => ({ label: option.label[locale], value: option.value, })), tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "DATASET_SELECT": const defaultValue = availableDatasets.length > 0 ? availableDatasets[0].value : undefined; return ( <RxFormField name={field.name} component={Select} defaultValue={defaultValue} props={{ label: field.label[locale], options: availableDatasets, tooltip: field.tooltip ? field.tooltip[locale] : undefined, optional, }} /> ); case "TABS": const tabToShow = field.tabs.find((tab) => tab.name === getFieldValue()); return ( <Tabs> <RxFormField name={field.name} component={FormTabNavigation} props={{ options: field.tabs.map((tab) => ({ label: tab.title[locale], value: tab.name, tooltip: tab.tooltip ? tab.tooltip[locale] : undefined, })), }} /> {tabToShow && tabToShow.fields.length > 0 && ( <NestedFields> {tabToShow.fields.map((f, i) => { const key = isFormField(f) ? f.name : f.type + i; const nestedFieldOptional = isOptionalField(f); return ( <Field key={key} field={f} {...commonProps} optional={nestedFieldOptional} /> ); })} </NestedFields> )} </Tabs> ); case "CONCEPT_LIST": return ( <RxFormField name={field.name} component={ConceptGroup} props={{ fieldName: field.name, label: field.label[locale], tooltip: field.tooltip ? field.tooltip[locale] : undefined, conceptDropzoneText: field.conceptDropzoneLabel ? field.conceptDropzoneLabel[locale] : t("externalForms.default.conceptDropzoneLabel"), attributeDropzoneText: field.conceptColumnDropzoneLabel ? field.conceptColumnDropzoneLabel[locale] : t("externalForms.default.conceptDropzoneLabel"), formType, enableDropFile: true, disallowMultipleColumns: !field.isTwoDimensional, isSingle: field.isSingle, blocklistedTables: field.blocklistedConnectors, allowlistedTables: field.allowlistedConnectors, blocklistedSelects: field.blocklistedSelects, allowlistedSelects: field.allowlistedSelects, defaults: field.defaults, optional, isValidConcept: (item: Object) => !nodeIsInvalid( item, field.blocklistedConceptIds, field.allowlistedConceptIds, ), // What follows is VERY custom // Concept Group supports rendering a prefix field // That's specifically required by one of the forms: "PSM Form" // So the following looks like it wants to be generic, // but it's really implemented for one field newValue: field.rowPrefixField ? { concepts: [], connector: "OR", [field.rowPrefixField.name]: field.rowPrefixField.defaultValue, } : { concepts: [], connector: "OR" }, renderRowPrefix: field.rowPrefixField && ((input, feature, i) => ( <SxToggleButton options={field.rowPrefixField.options.map((option) => ({ label: option.label[locale], value: option.value, }))} input={{ value: feature[field.rowPrefixField.name], onChange: (value) => input.onChange([ ...input.value.slice(0, i), { ...input.value[i], [field.rowPrefixField.name]: value, }, ...input.value.slice(i + 1), ]), }} /> )), }} /> ); default: return null; } }; export default Field;
manuel-hegner/conquery
frontend/src/js/api/api.ts
import { apiUrl } from "../environment"; import type { FormConfigT, BaseFormConfigT, } from "../external-forms/form-configs/reducer"; import type { QueryToUploadT } from "../previous-queries/upload/CSVColumnPicker"; import { transformFormQueryToApi } from "./apiExternalFormsHelper"; import { transformQueryToApi } from "./apiHelper"; import type { DatasetIdT, QueryIdT, ConceptIdT, GetFrontendConfigResponseT, GetConceptsResponseT, GetConceptResponseT, PostQueriesResponseT, GetQueryResponseT, GetQueriesResponseT, PostConceptResolveResponseT, PostFilterResolveResponseT, PostFilterSuggestionsResponseT, GetFormQueriesResponseT, GetMeResponseT, PostLoginResponseT, PostFormConfigsResponseT, GetFormConfigsResponseT, GetFormConfigResponseT, GetDatasetsResponseT, UploadQueryResponseT, } from "./types"; import { useApi, useApiUnauthorized } from "./useApi"; const PROTECTED_PREFIX = "/api"; function getProtectedUrl(url: string) { return apiUrl + PROTECTED_PREFIX + url; } export const useGetFrontendConfig = () => { return useApi<GetFrontendConfigResponseT>({ url: getProtectedUrl("/config/frontend"), }); }; export const useGetDatasets = () => { return useApi<GetDatasetsResponseT>({ url: getProtectedUrl(`/datasets`) }); }; export const useGetConcepts = () => { const api = useApi<GetConceptsResponseT>({}); return (datasetId: DatasetIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/concepts`), }); }; export const useGetConcept = () => { const api = useApi<GetConceptResponseT>({}); return (datasetId: DatasetIdT, conceptId: ConceptIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/concepts/${conceptId}`), }); }; // Same signature as postFormQueries export const usePostQueries = () => { const api = useApi<PostQueriesResponseT>(); return ( datasetId: DatasetIdT, query: Object, options: { queryType: string; selectedSecondaryId?: string | null }, ) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries`), method: "POST", data: transformQueryToApi(query, options), // Into backend-compatible format }); }; // Same signature as postQueries, plus a form query transformator export const usePostFormQueries = () => { const api = useApi<PostQueriesResponseT>(); return ( datasetId: DatasetIdT, query: { form: any; formName: string }, { formQueryTransformation }: { formQueryTransformation: Function }, ) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries`), method: "POST", data: transformFormQueryToApi(query, formQueryTransformation), // Into backend-compatible format }); }; export const useGetQuery = () => { const api = useApi<GetQueryResponseT>(); return (datasetId: DatasetIdT, queryId: QueryIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries/${queryId}`), }); }; export const usePostQueryCancel = () => { const api = useApi<null>(); return (datasetId: DatasetIdT, queryId: QueryIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries/${queryId}/cancel`), method: "POST", }); }; export const usePostQueryUpload = () => { const api = useApi<UploadQueryResponseT>(); return (datasetId: DatasetIdT, data: QueryToUploadT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries/upload`), method: "POST", data, }); }; export const useDeleteQuery = () => { const api = useApi<null>(); return (datasetId: DatasetIdT, queryId: QueryIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries/${queryId}`), method: "DELETE", }); }; export const useGetForms = () => { const api = useApi<GetFormQueriesResponseT>(); return (datasetId: DatasetIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/form-queries`), }); }; export const useGetQueries = () => { const api = useApi<GetQueriesResponseT>(); return (datasetId: DatasetIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries`), }); }; export const usePatchQuery = () => { const api = useApi<null>(); return (datasetId: DatasetIdT, queryId: QueryIdT, attributes: Object) => api({ url: getProtectedUrl(`/datasets/${datasetId}/queries/${queryId}`), method: "PATCH", data: attributes, }); }; export interface PostPrefixForSuggestionsParams { datasetId: DatasetIdT; conceptId: string; tableId: string; filterId: string; prefix: string; } export const usePostPrefixForSuggestions = () => { const api = useApi<PostFilterSuggestionsResponseT>(); return ({ datasetId, conceptId, tableId, filterId, prefix, }: PostPrefixForSuggestionsParams) => api({ url: getProtectedUrl( `/datasets/${datasetId}/concepts/${conceptId}/tables/${tableId}/filters/${filterId}/autocomplete`, ), method: "POST", data: { text: prefix }, }); }; export const usePostConceptsListToResolve = () => { const api = useApi<PostConceptResolveResponseT>(); return (datasetId: DatasetIdT, conceptId: string, concepts: string[]) => api({ url: getProtectedUrl( `/datasets/${datasetId}/concepts/${conceptId}/resolve`, ), method: "POST", data: { concepts }, }); }; export const usePostFilterValuesResolve = () => { const api = useApi<PostFilterResolveResponseT>(); return ( datasetId: DatasetIdT, conceptId: string, tableId: string, filterId: string, values: string[], ) => api({ url: getProtectedUrl( `/datasets/${datasetId}/concepts/${conceptId}/tables/${tableId}/filters/${filterId}/resolve`, ), method: "POST", data: { values }, }); }; export const useGetMe = () => { return useApi<GetMeResponseT>({ url: getProtectedUrl(`/me`) }); }; export const usePostLogin = () => { const api = useApiUnauthorized<PostLoginResponseT>({ url: apiUrl + "/auth", method: "POST", }); return (user: string, password: string) => api({ data: { user, password, }, }); }; export const usePostFormConfig = () => { const api = useApi<PostFormConfigsResponseT>(); return (datasetId: DatasetIdT, data: BaseFormConfigT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/form-configs`), method: "POST", data, }); }; export const useGetFormConfig = () => { const api = useApi<GetFormConfigResponseT>(); return (datasetId: DatasetIdT, formConfigId: string) => api({ url: getProtectedUrl( `/datasets/${datasetId}/form-configs/${formConfigId}`, ), }); }; export const usePatchFormConfig = () => { const api = useApi<GetFormConfigResponseT>(); return ( datasetId: DatasetIdT, formConfigId: string, data: Partial<FormConfigT>, ) => api({ url: getProtectedUrl( `/datasets/${datasetId}/form-configs/${formConfigId}`, ), method: "PATCH", data, }); }; export const useGetFormConfigs = () => { const api = useApi<GetFormConfigsResponseT>(); return (datasetId: DatasetIdT) => api({ url: getProtectedUrl(`/datasets/${datasetId}/form-configs`), }); }; export const useDeleteFormConfig = () => { const api = useApi<null>(); return (datasetId: DatasetIdT, formConfigId: string) => api({ url: getProtectedUrl( `/datasets/${datasetId}/form-configs/${formConfigId}`, ), method: "DELETE", }); };
manuel-hegner/conquery
frontend/src/js/previous-queries/upload/UploadQueryResults.tsx
import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { usePostQueryUpload } from "../../api/api"; import type { DatasetIdT, QueryUploadConfigT, UploadQueryResponseT, } from "../../api/types"; import IconButton from "../../button/IconButton"; import { setMessage } from "../../snack-message/actions"; import WithTooltip from "../../tooltip/WithTooltip"; import { useLoadQueries } from "../list/actions"; import { QueryToUploadT } from "./CSVColumnPicker"; import UploadQueryResultsModal from "./UploadQueryResultsModal"; const SxIconButton = styled(IconButton)` padding: 8px 6px; `; interface PropsT { className?: string; datasetId: DatasetIdT | null; } const UploadQueryResults = ({ className, datasetId }: PropsT) => { const { t } = useTranslation(); const [isModalOpen, setIsModalOpen] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false); const [uploadResult, setUploadResult] = useState<UploadQueryResponseT | null>( null, ); const dispatch = useDispatch(); const postQueryUpload = usePostQueryUpload(); const loadQueries = useLoadQueries(); const queryUploadConfig = useSelector<StateT, QueryUploadConfigT>( (state) => state.startup.config.queryUpload, ); const onCloseModal = () => { setIsModalOpen(false); setUploadResult(null); }; const onUpload = async (query: QueryToUploadT) => { if (!datasetId) return; try { setUploadResult(null); setLoading(true); const result = await postQueryUpload(datasetId, query); setUploadResult(result); loadQueries(datasetId); } catch (e) { if (e.status === 400) { setUploadResult(e); } else { dispatch( setMessage({ message: t("uploadQueryResultsModal.uploadFailed") }), ); } } setLoading(false); }; return ( <> <WithTooltip text={t("uploadQueryResults.uploadResults")} className={className} > <SxIconButton frame icon="upload" onClick={() => setIsModalOpen(true)} /> </WithTooltip> {isModalOpen && ( <UploadQueryResultsModal loading={loading} uploadResult={uploadResult} config={queryUploadConfig} onClearUploadResult={() => setUploadResult(null)} onClose={onCloseModal} onUpload={onUpload} /> )} </> ); }; export default UploadQueryResults;
manuel-hegner/conquery
frontend/src/test/standard-query-editor/reducer.spec.ts
import { setFilterValue, loadFilterSuggestions, } from "../../js/standard-query-editor/actions"; import reducer from "../../js/standard-query-editor/queryReducer"; const createQueryStateWithOneBigMultiSelect = () => [ { elements: [ { id: "elm0", tables: [ { id: "elm0.tbl0", filters: [ { id: "col0", type: "BIG_MULTI_SELECT", options: [], }, ], }, ], hasActiveFilters: false, isEditing: true, // This is the element we want to manipulate }, ], }, ]; describe("standard query editor", () => { describe("setting a filter value", () => { it("sets the value to what is given", () => { const state = createQueryStateWithOneBigMultiSelect(); state[0].elements[0].tables[0].filters[0].options = [ { value: 1, label: "1" }, ]; state[0].elements[0].tables[0].filters[0].value = [1]; const action = setFilterValue({ andIdx: 0, orIdx: 0, tableIdx: 0, filterIdx: 0, value: [], }); const updatedState = reducer(state, action); expect(updatedState[0].elements[0].tables[0].filters[0].value).toEqual( [], ); }); }); describe("receiving a list of autocomplete suggestions", () => { it("updates the filter's options list", () => { const state = createQueryStateWithOneBigMultiSelect(); const options = [ { value: "0", label: "0" }, { value: "1", label: "1" }, { value: "2", label: "2" }, ]; const action = loadFilterSuggestions.success({ data: options, andIdx: 0, orIdx: 0, tableIdx: 0, filterIdx: 0, }); const updatedState = reducer(state, action); expect(updatedState[0].elements[0].tables[0].filters[0].options).toEqual( options, ); }); it("leaves filter's options list unmodified when receiving empty suggestions list", () => { const options = [ { value: "0", label: "0" }, { value: "1", label: "1" }, { value: "2", label: "2" }, ]; const state = createQueryStateWithOneBigMultiSelect(); state[0].elements[0].tables[0].filters[0].options = options; const newOptions = []; const action = loadFilterSuggestions.success({ data: newOptions, andIdx: 0, orIdx: 0, tableIdx: 0, filterIdx: 0, }); const updatedState = reducer(state, action); expect(updatedState[0].elements[0].tables[0].filters[0].options).toEqual( options, ); }); }); });
manuel-hegner/conquery
frontend/src/js/concept-trees-open/useOpenableConcept.ts
<gh_stars>10-100 import { StateT } from "app-types"; import { useSelector, useDispatch } from "react-redux"; import { ConceptIdT } from "../api/types"; import { setConceptOpen } from "./actions"; interface PropsT { conceptId: ConceptIdT; openInitially?: boolean; } export const useOpenableConcept = ({ conceptId, openInitially = false, }: PropsT) => { const conceptOpen = useSelector<StateT, boolean>( (state) => state.conceptTreesOpen[conceptId], ); const open = conceptOpen == null ? openInitially : conceptOpen; const dispatch = useDispatch(); const onToggleOpen = () => dispatch(setConceptOpen(conceptId, !open)); return { open, onToggleOpen, }; };
manuel-hegner/conquery
frontend/src/js/file/csv.ts
<gh_stars>10-100 import Papa, { ParseResult } from "papaparse"; export function parseCSV(file: File, delimiter?: string) { return new Promise<{ result: ParseResult<string[]>; file?: File }>( (resolve) => { Papa.parse<string[]>(file, { header: false, delimiter: delimiter || ";", skipEmptyLines: true, complete: (results, file) => resolve({ result: results, file, }), }); }, ); } export function loadCSV( url: string, ): Promise<{ result: ParseResult<unknown>; file?: File }> { return new Promise((resolve) => { Papa.parse(url, { download: true, delimiter: ";", skipEmptyLines: true, complete: (results, file) => resolve({ result: results, file, }), }); }); } export function toCSV(data: string[][], delimiter: string = ";") { return Papa.unparse(data, { delimiter, newline: "\r\n" }); }
manuel-hegner/conquery
frontend/src/js/tooltip/reducer.ts
<reponame>manuel-hegner/conquery<filename>frontend/src/js/tooltip/reducer.ts<gh_stars>10-100 import { ActionType, getType } from "typesafe-actions"; import type { DateRangeT } from "../api/types"; import type { Action } from "../app/actions"; import { displayAdditionalInfos, toggleAdditionalInfos, toggleDisplayTooltip, } from "./actions"; type InfoType = { key: string; value: string; }; export type AdditionalInfosType = { label: string | null; description?: string; isFolder: boolean; matchingEntries: number | null; matchingEntities: number | null; dateRange?: DateRangeT; infos?: InfoType[]; }; export type TooltipStateT = { displayTooltip: boolean; toggleAdditionalInfos: boolean; additionalInfos: AdditionalInfosType; }; const additionalInfosInitialState: AdditionalInfosType = { label: null, description: undefined, isFolder: false, matchingEntries: null, matchingEntities: null, dateRange: undefined, infos: undefined, }; const initialState: TooltipStateT = { displayTooltip: true, toggleAdditionalInfos: false, additionalInfos: additionalInfosInitialState, }; const setAdditionalInfos = ( state: TooltipStateT, { additionalInfos }: ActionType<typeof displayAdditionalInfos>["payload"], ) => { if (state.toggleAdditionalInfos) return { ...state, }; return { ...state, additionalInfos: additionalInfos || additionalInfosInitialState, }; }; const tooltip = ( state: TooltipStateT = initialState, action: Action, ): TooltipStateT => { switch (action.type) { case getType(displayAdditionalInfos): return setAdditionalInfos(state, action.payload); case getType(toggleAdditionalInfos): return { ...state, toggleAdditionalInfos: !state.toggleAdditionalInfos, }; case getType(toggleDisplayTooltip): return { ...state, displayTooltip: !state.displayTooltip, }; default: return state; } }; export default tooltip;
manuel-hegner/conquery
frontend/src/js/user/userSettings.ts
// Putting localStorage into an own constant to type annotate it. const localStorage: Storage = window.localStorage; interface UserSettings { arePreviousQueriesFoldersOpen: boolean; } const initialState: UserSettings = { arePreviousQueriesFoldersOpen: false, }; export const getUserSettings = (): UserSettings => { const storedSettings = localStorage.getItem("userSettings"); return storedSettings ? JSON.parse(storedSettings) : initialState; }; export const storeUserSettings = ( nextSettings: Partial<UserSettings>, ): void => { const settings = getUserSettings(); localStorage.setItem( "userSettings", JSON.stringify({ ...settings, ...nextSettings }), ); }; export const deleteUserSettings = (): void => { localStorage.removeItem("userSettings"); };
manuel-hegner/conquery
frontend/src/js/previous-queries/filter/actions.ts
import { ActionType, createAction } from "typesafe-actions"; import type { PreviousQueriesFilterStateT } from "./reducer"; export type PreviousQueriesFilterActions = ActionType< typeof setPreviousQueriesFilter >; export const setPreviousQueriesFilter = createAction( "previous-queries/SET_FILTER", )<PreviousQueriesFilterStateT>();
manuel-hegner/conquery
frontend/src/js/user/reducer.ts
import type { GetMeResponseT } from "../api/types"; import { LOAD_ME_START, LOAD_ME_ERROR, LOAD_ME_SUCCESS } from "./actionTypes"; export type UserStateT = { loading: boolean; error: string | null; me: GetMeResponseT | null; }; const initialState: UserStateT = { loading: false, error: null, me: null, }; const startup = (state: UserStateT = initialState, action: any): UserStateT => { switch (action.type) { case LOAD_ME_START: return { ...state, loading: true, }; case LOAD_ME_ERROR: return { ...state, loading: false, error: action.payload.message, }; case LOAD_ME_SUCCESS: return { ...state, loading: false, me: action.payload.data, }; default: return state; } }; export default startup;
manuel-hegner/conquery
frontend/src/js/external-forms/form-components/Headline.tsx
<filename>frontend/src/js/external-forms/form-components/Headline.tsx import styled from "@emotion/styled"; export const Headline = styled("h3")` font-size: 14px; margin: 10px 0 0; `;
manuel-hegner/conquery
frontend/src/js/previous-queries/list/SharePreviousQueryModal.tsx
import styled from "@emotion/styled"; import { StateT } from "app-types"; import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import { usePatchQuery } from "../../api/api"; import type { DatasetIdT, UserGroupT } from "../../api/types"; import PrimaryButton from "../../button/PrimaryButton"; import TransparentButton from "../../button/TransparentButton"; import { exists } from "../../common/helpers/exists"; import { usePrevious } from "../../common/helpers/usePrevious"; import Modal from "../../modal/Modal"; import { setMessage } from "../../snack-message/actions"; import InputMultiSelect from "../../ui-components/InputMultiSelect"; import { useLoadQuery, shareQuerySuccess } from "./actions"; import { PreviousQueryT } from "./reducer"; const Buttons = styled("div")` width: 100%; display: flex; align-items: center; justify-content: space-between; `; const SxPrimaryButton = styled(PrimaryButton)` margin-left: 20px; `; const SxInputMultiSelect = styled(InputMultiSelect)` display: block; margin-bottom: 20px; `; const QueryName = styled("p")` margin: -15px 0 20px; `; interface SelectValueT { label: string; value: string; } interface PropsT { previousQueryId: string; onClose: () => void; onShareSuccess: () => void; } const getUserGroupsValue = ( userGroups: UserGroupT[], previousQuery?: PreviousQueryT, ) => { return previousQuery && previousQuery.groups ? userGroups .filter((group) => previousQuery.groups?.includes(group.id)) .map((group) => ({ label: group.label, value: group.id, })) : []; }; const SharePreviousQueryModal = ({ previousQueryId, onClose, onShareSuccess, }: PropsT) => { const { t } = useTranslation(); const datasetId = useSelector<StateT, DatasetIdT | null>( (state) => state.datasets.selectedDatasetId, ); const userGroups = useSelector<StateT, UserGroupT[]>((state) => state.user.me ? state.user.me.groups : [], ); const previousQuery = useSelector<StateT, PreviousQueryT | undefined>( (state) => state.previousQueries.queries.find( (query) => query.id === previousQueryId, ), ); const initialUserGroupsValue = getUserGroupsValue(userGroups, previousQuery); const [userGroupsValue, setUserGroupsValue] = useState<SelectValueT[]>( initialUserGroupsValue, ); const previousPreviousQueryId = usePrevious(previousQueryId); const patchQuery = usePatchQuery(); const dispatch = useDispatch(); const loadQuery = useLoadQuery(); useEffect(() => { if ( exists(datasetId) && !exists(previousPreviousQueryId) && exists(previousQueryId) ) { loadQuery(datasetId, previousQueryId); } }, [datasetId, previousPreviousQueryId, previousQueryId]); useEffect(() => { setUserGroupsValue(getUserGroupsValue(userGroups, previousQuery)); }, [userGroups, previousQuery]); const onSetUserGroupsValue = (value: SelectValueT[] | null) => { setUserGroupsValue(value ? value : []); }; if (!previousQuery) { return null; } const userGroupOptions = userGroups.map((group) => ({ label: group.label, value: group.id, })); async function onShareClicked() { if (!datasetId) return; const userGroupsToShare = userGroupsValue.map((group) => group.value); try { await patchQuery(datasetId, previousQueryId, { groups: userGroupsToShare, }); dispatch( shareQuerySuccess({ queryId: previousQueryId, groups: userGroupsToShare, }), ); onShareSuccess(); } catch (e) { dispatch(setMessage({ message: t("previousQuery.shareError") })); } } return ( <Modal onClose={onClose} headline={t("sharePreviousQueryModal.headline")}> <QueryName>{previousQuery.label}</QueryName> <SxInputMultiSelect input={{ value: userGroupsValue, onChange: onSetUserGroupsValue }} label={t("sharePreviousQueryModal.groupsLabel")} options={userGroupOptions} closeMenuOnSelect /> <Buttons> <TransparentButton onClick={onClose}> {t("common.cancel")} </TransparentButton> <SxPrimaryButton onClick={onShareClicked}> {previousQuery.shared && userGroupsValue.length === 0 ? t("sharePreviousQueryModal.unshare") : t("common.share")} </SxPrimaryButton> </Buttons> </Modal> ); }; export default SharePreviousQueryModal;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/QueryNode.tsx
<filename>frontend/src/js/standard-query-editor/QueryNode.tsx import styled from "@emotion/styled"; import { StateT } from "app-types"; import React, { useRef, FC } from "react"; import { useDrag } from "react-dnd"; import { useTranslation } from "react-i18next"; import { useSelector } from "react-redux"; import { getWidthAndHeight } from "../app/DndProvider"; import { QUERY_NODE } from "../common/constants/dndTypes"; import ErrorMessage from "../error-message/ErrorMessage"; import { nodeHasActiveFilters } from "../model/node"; import { isQueryExpandable } from "../model/query"; import AdditionalInfoHoverable from "../tooltip/AdditionalInfoHoverable"; import QueryNodeActions from "./QueryNodeActions"; import { getRootNodeLabel } from "./helper"; import { StandardQueryNodeT, DragItemQuery, PreviousQueryQueryNodeType, DragItemNode, } from "./types"; const Root = styled("div")<{ hasActiveFilters?: boolean; }>` position: relative; width: 100%; margin: 0 auto; background-color: white; display: flex; flex-direction: row; align-items: flex-start; padding: 7px; font-size: ${({ theme }) => theme.font.sm}; cursor: pointer; text-align: left; border-radius: ${({ theme }) => theme.borderRadius}; transition: border ${({ theme }) => theme.transitionTime}; border: ${({ theme, hasActiveFilters }) => hasActiveFilters ? `2px solid ${theme.col.blueGrayDark}` : `1px solid ${theme.col.grayMediumLight}`}; &:hover { border: ${({ theme, hasActiveFilters }) => hasActiveFilters ? `2px solid ${theme.col.blueGrayDark}` : `1px solid ${theme.col.blueGrayDark}`}; } `; const Node = styled("div")` flex-grow: 1; padding-top: 2px; `; const Label = styled("p")` margin: 0; word-break: break-word; line-height: 1.2; font-size: ${({ theme }) => theme.font.md}; `; const Description = styled("p")` margin: 3px 0 0; word-break: break-word; line-height: 1.2; text-transform: uppercase; font-size: ${({ theme }) => theme.font.xs}; `; const PreviousQueryLabel = styled("p")` margin: 0 0 3px; line-height: 1.2; font-size: ${({ theme }) => theme.font.xs}; text-transform: uppercase; font-weight: 700; color: ${({ theme }) => theme.col.blueGrayDark}; `; const StyledErrorMessage = styled(ErrorMessage)` margin: 0; `; const RootNode = styled("p")` margin: 0 0 4px; line-height: 1; text-transform: uppercase; font-weight: 700; font-size: ${({ theme }) => theme.font.xs}; color: ${({ theme }) => theme.col.blueGrayDark}; word-break: break-word; `; interface PropsT { node: StandardQueryNodeT; andIdx: number; orIdx: number; onDeleteNode: () => void; onEditClick: () => void; onToggleTimestamps: () => void; onToggleSecondaryIdExclude: () => void; onExpandClick: (q: PreviousQueryQueryNodeType) => void; } const nodeHasActiveSecondaryId = ( node: StandardQueryNodeT, activeSecondaryId: string | null, ) => { if (!activeSecondaryId) { return false; } if (node.isPreviousQuery) { return ( !!node.availableSecondaryIds && node.availableSecondaryIds.includes(activeSecondaryId) ); } else { return node.tables.some( (table) => !table.exclude && table.supportedSecondaryIds && table.supportedSecondaryIds.includes(activeSecondaryId), ); } }; const QueryNode: FC<PropsT> = ({ node, andIdx, orIdx, onExpandClick, onEditClick, onDeleteNode, onToggleTimestamps, onToggleSecondaryIdExclude, }) => { const { t } = useTranslation(); const rootNodeLabel = getRootNodeLabel(node); const ref = useRef<HTMLDivElement | null>(null); const activeSecondaryId = useSelector<StateT, string | null>( (state) => state.queryEditor.selectedSecondaryId, ); const hasActiveFilters = !node.error && nodeHasActiveFilters(node); const hasActiveSecondaryId = nodeHasActiveSecondaryId( node, activeSecondaryId, ); const item = { // Return the data describing the dragged item // NOT using `...node` since that would also spread `children` in. // This item may stem from either: // 1) A concept (dragged from ConceptTreeNode) // 2) A previous query (dragged from PreviousQueries) moved: true, andIdx, orIdx, type: QUERY_NODE, label: node.label, excludeTimestamps: node.excludeTimestamps, excludeFromSecondaryIdQuery: node.excludeFromSecondaryIdQuery, loading: node.loading, error: node.error, ...(node.isPreviousQuery ? { id: node.id, query: node.query, isPreviousQuery: true, } : { ids: node.ids, description: node.description, tree: node.tree, tables: node.tables, selects: node.selects, additionalInfos: node.additionalInfos, matchingEntries: node.matchingEntries, matchingEntities: node.matchingEntities, dateRange: node.dateRange, }), }; const [, drag] = useDrag<DragItemNode, void, {}>({ item, begin: () => ({ ...item, ...getWidthAndHeight(ref), }), }); return ( <AdditionalInfoHoverable node={node}> <Root ref={(instance) => { ref.current = instance; drag(instance); }} hasActiveFilters={hasActiveFilters} onClick={!!node.error ? () => {} : onEditClick} > <Node> {node.isPreviousQuery && ( <PreviousQueryLabel> {t("queryEditor.previousQuery")} </PreviousQueryLabel> )} {node.error ? ( <StyledErrorMessage message={node.error} /> ) : ( <> {rootNodeLabel && <RootNode>{rootNodeLabel}</RootNode>} <Label>{node.label || node.id}</Label> {node.description && (!node.ids || node.ids.length === 1) && ( <Description>{node.description}</Description> )} </> )} </Node> <QueryNodeActions excludeTimestamps={node.excludeTimestamps} onDeleteNode={onDeleteNode} onToggleTimestamps={onToggleTimestamps} isExpandable={isQueryExpandable(node)} hasActiveSecondaryId={hasActiveSecondaryId} excludeFromSecondaryIdQuery={node.excludeFromSecondaryIdQuery} onToggleSecondaryIdExclude={onToggleSecondaryIdExclude} onExpandClick={() => { if (!node.query) return; onExpandClick(node.query); }} previousQueryLoading={node.loading} error={node.error} /> </Root> </AdditionalInfoHoverable> ); }; export default QueryNode;
manuel-hegner/conquery
frontend/src/js/localization/i18next.ts
import i18next from "i18next"; import LanguageDetector from "i18next-browser-languagedetector"; import { initReactI18next } from "react-i18next"; i18next .use(initReactI18next) .use(LanguageDetector) .init({ lng: "de", fallbackLng: "de", debug: true, resources: { de: { translation: {} }, en: { translation: {} }, }, }); export default i18next;
manuel-hegner/conquery
frontend/src/js/button/DownloadButton.tsx
import styled from "@emotion/styled"; import React, { ReactNode, FC, useContext } from "react"; import { AuthTokenContext } from "../authorization/AuthTokenProvider"; import IconButton, { IconButtonPropsT } from "./IconButton"; const SxIconButton = styled(IconButton)` white-space: nowrap; `; interface PropsT extends Omit<IconButtonPropsT, "icon" | "onClick"> { url: string; className?: string; children?: ReactNode; } const DownloadButton: FC<PropsT> = ({ url, className, children, ...restProps }) => { const { authToken } = useContext(AuthTokenContext); const href = `${url}?access_token=${encodeURIComponent( authToken, )}&charset=ISO_8859_1`; const icon = "download"; return ( <a href={href} className={className}> <SxIconButton {...restProps} icon={icon} onClick={() => {}}> {children} </SxIconButton> </a> ); }; export default DownloadButton;
manuel-hegner/conquery
frontend/src/js/ui-components/EditableTagsForm.tsx
import styled from "@emotion/styled"; import React, { FC, useState, useRef, FormEvent } from "react"; import { useTranslation } from "react-i18next"; import IconButton from "../button/IconButton"; import { useClickOutside } from "../common/helpers/useClickOutside"; import WithTooltip from "../tooltip/WithTooltip"; import ReactSelect from "./ReactSelect"; interface PropsT { className?: string; tags?: string[]; loading?: boolean; onSubmit: (tags: string[]) => void; onCancel: () => void; availableTags: string[]; } interface ValueT { label: string; value: string; } const Form = styled("form")` display: flex; align-items: flex-start; `; const SxIconButton = styled(IconButton)` padding: 10px 10px; margin-left: 3px; `; const SxReactSelect = styled(ReactSelect)` z-index: 2; flex-grow: 1; `; const EditableTagsForm: FC<PropsT> = ({ className, tags, loading, onSubmit, onCancel, availableTags, }) => { const { t } = useTranslation(); const ref = useRef(null); const [values, setValues] = useState<ValueT[]>( tags ? tags.map((t) => ({ label: t, value: t })) : [], ); useClickOutside(ref, onCancel); function submit(e: FormEvent) { e.preventDefault(); onSubmit(values ? values.map((v) => v.value) : []); } return ( <Form ref={ref} className={className} onSubmit={submit}> <SxReactSelect creatable name="input" value={values} options={availableTags.map((t) => ({ label: t, value: t, }))} onChange={setValues} isMulti isClearable autoFocus={true} placeholder={t("inputMultiSelect.tagPlaceholder")} noOptionsMessage={() => t("inputSelect.empty")} formatCreateLabel={(inputValue: string) => t("common.create") + `: "${inputValue}"` } /> <WithTooltip text={t("common.save")}> <SxIconButton type="submit" frame disabled={!!loading} icon={loading ? "spinner" : "check"} /> </WithTooltip> </Form> ); }; export default EditableTagsForm;
manuel-hegner/conquery
frontend/src/js/app/RightPane.tsx
<filename>frontend/src/js/app/RightPane.tsx import styled from "@emotion/styled"; import type { StateT } from "app-types"; import React, { FC, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { useDispatch, useSelector } from "react-redux"; import Pane from "../pane/Pane"; import { clickPaneTab } from "../pane/actions"; import type { TabT } from "../pane/types"; interface PropsT { tabs: TabT[]; } const Tab = styled("div")<{ isActive: boolean }>` height: 100%; flex-grow: 1; display: flex; flex-direction: column; display: ${({ isActive }) => (isActive ? "flex" : "none")}; `; const RightPane: FC<PropsT> = ({ tabs }) => { const { t } = useTranslation(); const dispatch = useDispatch(); const activeTab = useSelector<StateT, string | null>( (state) => state.panes.right.activeTab, ); useEffect(() => { dispatch(clickPaneTab("right", tabs[0].key)); }, [dispatch, tabs]); return ( <Pane right tabs={tabs.map((tab) => ({ key: tab.key, label: t(tab.labelKey), // TODO: Somehow make this non-dynamic tooltip: t(tab.tooltipKey), // TODO: Somehow make this non-dynamic }))} > {tabs.map((tab) => { const isActive = tab.key === activeTab; const tabComponent = React.createElement(tab.component); return ( <Tab key={tab.key} isActive={isActive}> {tabComponent} </Tab> ); })} </Pane> ); }; export default RightPane;
manuel-hegner/conquery
frontend/src/js/pane/reducer.ts
import { CLICK_PANE_TAB } from "./actionTypes"; export type LeftPaneTab = "conceptTrees" | "previousQueries" | "formConfigs"; export interface PanesStateT { left: { activeTab: LeftPaneTab }; right: { activeTab: string | null }; } const initialState: PanesStateT = { left: { activeTab: "conceptTrees", }, right: { activeTab: null, }, }; const reducer = ( state: PanesStateT = initialState, action: any, ): PanesStateT => { switch (action.type) { case CLICK_PANE_TAB: const { paneType, tab } = action.payload; return { ...state, [paneType]: { ...state[paneType], activeTab: tab, }, }; default: return state; } }; export default reducer;
manuel-hegner/conquery
frontend/src/test/setup.ts
import axios from "axios"; import httpAdapter from "axios/lib/adapters/http"; import { initializeEnvironment } from "../js/environment"; axios.defaults.adapter = httpAdapter; initializeEnvironment({});
manuel-hegner/conquery
frontend/src/js/common/helpers/useResizeObserver.ts
<filename>frontend/src/js/common/helpers/useResizeObserver.ts import { useEffect } from "react"; import ResizeObserver from "resize-observer-polyfill"; export function useResizeObserver( callback: (entry: ResizeObserverEntry) => void, element: Element | null, ) { useEffect(() => { if (!element) return; const observer = new ResizeObserver((entries: ResizeObserverEntry[]) => { const observedElement = entries[0]; callback(observedElement); }); observer.observe(element); return () => observer.unobserve(element); }, [callback, element]); }
manuel-hegner/conquery
frontend/src/js/concept-trees/ProgressBar.tsx
<filename>frontend/src/js/concept-trees/ProgressBar.tsx import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; import FaIcon from "../icon/FaIcon"; import { getConceptById } from "./globalTreeStoreHelper"; import type { TreesT } from "./reducer"; const Root = styled("div")` margin: 10px; `; const Row = styled("div")` display: flex; align-items: center; `; const Text = styled("p")` margin: 0 10px; `; const Bar = styled("div")` width: 100%; height: 7px; margin: 10px 0; background-color: #ccc; border-radius: ${({ theme }) => theme.borderRadius}; box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.1); `; const BarProgress = styled("div")` height: 100%; background-color: ${({ theme }) => theme.col.blueGrayDark}; border-radius: ${({ theme }) => theme.borderRadius}; `; type PropsT = { trees: TreesT; }; const ProgressBar = ({ trees }: PropsT) => { const { t } = useTranslation(); const treeIds = Object.keys(trees); const doneCount = treeIds.map(getConceptById).filter((c) => !!c).length; const donePercent = (doneCount / treeIds.length) * 100; return ( <Root> <Row> <FaIcon icon="spinner" /> <Text> {t("conceptTreeList.loading")} {doneCount} / {treeIds.length} </Text> </Row> <Bar> <BarProgress style={{ width: `${donePercent}%` }} /> </Bar> </Root> ); }; export default ProgressBar;
manuel-hegner/conquery
frontend/src/js/ui-components/InputRange.tsx
import styled from "@emotion/styled"; import React from "react"; import { useTranslation } from "react-i18next"; import type { CurrencyConfigT } from "../api/types"; import { exists } from "../common/helpers/exists"; import InputPlain from "./InputPlain"; import InputRangeHeader from "./InputRangeHeader"; import ToggleButton from "./ToggleButton"; import { InputProps } from "./types"; const Container = styled("div")` width: 100%; display: flex; flex-direction: row; margin-top: -3px; `; const SxInputPlain = styled(InputPlain)` input { width: 100%; min-width: 50px; } &:last-of-type { padding-left: 5px; } `; interface ValueT { min?: number | null; max?: number | null; exact?: number | null; } export type ModeT = "range" | "exact"; interface PropsType extends InputProps<ValueT | null> { moneyRange?: boolean; label: string; indexPrefix?: number; unit?: string; limits?: { min?: number; max?: number; }; disabled: boolean; mode: "range" | "exact"; stepSize?: number; placeholder: string; onSwitchMode: (mode: ModeT) => void; tooltip?: string; pattern?: string; currencyConfig?: CurrencyConfigT; } function getMinMaxExact(value: ValueT | null) { if (!value) return { min: null, max: null, exact: null }; return { min: exists(value.min) ? value.min : null, max: exists(value.max) ? value.max : null, exact: exists(value.exact) ? value.exact : null, }; } const InputRange = ({ limits, stepSize, currencyConfig, pattern, mode, moneyRange, placeholder, disabled, label, indexPrefix, unit, tooltip, onSwitchMode, input: { value, defaultValue, onChange }, }: PropsType) => { const { t } = useTranslation(); // Make sure undefined / null is never set as a value, but an empty string instead const val = getMinMaxExact(value); const defaultVal = defaultValue || {}; const isRangeMode = mode === "range"; const inputProps = { step: stepSize || null, min: (limits && limits.min) || null, max: (limits && limits.max) || null, pattern: pattern, }; const onChangeValue = (type: "exact" | "max" | "min", newValue: number) => { const nextValue = newValue >= 0 ? newValue : null; if (type === "exact") { if (nextValue === null) { onChange(null); } else { onChange({ exact: nextValue }); } } else if (type === "min" || type === "max") { if ( nextValue === null && ((value && value.min === null && type === "max") || (value && value.max === null && type === "min")) ) { onChange(null); } else { onChange({ min: value ? value.min : null, max: value ? value.max : null, [type]: nextValue, }); } } else { onChange(null); } }; return ( <div> <InputRangeHeader disabled={disabled} label={label} indexPrefix={indexPrefix} unit={unit} tooltip={tooltip} /> <ToggleButton input={{ value: mode || "range", onChange: (mode) => onSwitchMode(mode), }} options={[ { value: "range", label: t("inputRange.range") }, { value: "exact", label: t("inputRange.exact") }, ]} /> <Container> {isRangeMode ? ( <> <SxInputPlain<number> inputType="number" currencyConfig={currencyConfig} money={moneyRange} placeholder={placeholder} label={t("inputRange.minLabel")} tinyLabel={true} input={{ value: val.min, defaultValue: defaultVal.min, onChange: (value) => onChangeValue("min", value), }} inputProps={inputProps} /> <SxInputPlain<number> inputType="number" currencyConfig={currencyConfig} money={moneyRange} placeholder={placeholder} label={t("inputRange.maxLabel")} tinyLabel={true} input={{ value: val.max, defaultValue: defaultVal.max, onChange: (value) => onChangeValue("max", value), }} inputProps={inputProps} /> </> ) : ( <InputPlain<number> inputType="number" currencyConfig={currencyConfig} money={moneyRange} placeholder={placeholder} label={t("inputRange.exactLabel")} tinyLabel={true} input={{ value: val.exact, defaultValue: defaultVal.exact, onChange: (value) => onChangeValue("exact", value), }} inputProps={inputProps} /> )} </Container> </div> ); }; export default InputRange;
manuel-hegner/conquery
frontend/src/js/ui-components/InputRangeHeader.tsx
import styled from "@emotion/styled"; import React, { FC } from "react"; import { IndexPrefix } from "../common/components/IndexPrefix"; import { exists } from "../common/helpers/exists"; import InfoTooltip from "../tooltip/InfoTooltip"; interface PropsT { className?: string; label: string; indexPrefix?: number; unit?: string; tooltip?: string; disabled?: boolean; } const Container = styled("p")<{ disabled?: boolean }>` font-size: ${({ theme }) => theme.font.sm}; margin: 6px 0 3px; color: ${({ theme, disabled }) => (disabled ? theme.col.gray : "initial")}; display: flex; align-items: center; `; const InputRangeHeader: FC<PropsT> = ({ label, indexPrefix, unit, className, tooltip, disabled, }) => { return ( <Container className={className} disabled={disabled}> {exists(indexPrefix) && <IndexPrefix># {indexPrefix}</IndexPrefix>} {label} {unit && ` ( ${unit} )`} {tooltip && <InfoTooltip text={tooltip} />} </Container> ); }; export default InputRangeHeader;
manuel-hegner/conquery
frontend/src/js/query-node-editor/actionTypes.ts
import { toUpperCaseUnderscore } from "../common/helpers"; export const createActionTypes = (type: string) => { const uppercasedType = toUpperCaseUnderscore(type); return { SET_FOCUSED_INPUT: `query-node-editor/SET_${uppercasedType}_FOCUSED_INPUT`, UPDATE_NAME: `query-node-editor/UPDATE_${uppercasedType}_NAME`, RESET: `query-node-editor/RESET_${uppercasedType}`, RESOLVE_FILTER_VALUES: `query-node-editor/RESOLVE_${uppercasedType}_FILTER_VALUES`, }; };
manuel-hegner/conquery
frontend/src/js/common/components/IndexPrefix.ts
<filename>frontend/src/js/common/components/IndexPrefix.ts import styled from "@emotion/styled"; export const IndexPrefix = styled("span")` flex-shrink: 0; display: inline-block; margin-right: 7px; border-radius: ${({ theme }) => theme.borderRadius}; background-color: ${({ theme }) => theme.col.blueGrayVeryLight}; padding: 3px; line-height: 1; font-size: ${({ theme }) => theme.font.tiny}; `;
manuel-hegner/conquery
frontend/src/js/standard-query-editor/QueryGroupActions.tsx
<reponame>manuel-hegner/conquery import styled from "@emotion/styled"; import React, { FC } from "react"; import { useTranslation } from "react-i18next"; import IconButton from "../button/IconButton"; import { Icon } from "../icon/FaIcon"; import WithTooltip from "../tooltip/WithTooltip"; const Actions = styled("div")` margin: 0 0 6px; text-align: left; height: 18px; // To provide enough space when only --right is available `; const Right = styled("div")` position: absolute; right: 7px; top: 5px; `; const StyledIconButton = styled(IconButton)` margin-right: 5px; padding: 0 3px; text-decoration: ${({ active }) => (active ? "underline" : "initial")}; `; const RedIconButton = styled(IconButton)` margin-right: 5px; padding: 0 3px; color: ${({ active, theme }) => (active ? theme.col.red : theme.col.black)}; ${Icon} { color: ${({ active, theme }) => (active ? theme.col.red : theme.col.black)}; } &:hover { opacity: 0.7; color: ${({ active, theme }) => (active ? theme.col.red : theme.col.black)}; ${Icon} { color: ${({ active, theme }) => active ? theme.col.red : theme.col.black}; } } `; interface PropsT { excludeActive: boolean; dateActive: boolean; onExcludeClick: () => void; onDeleteGroup: () => void; onDateClick: () => void; } const QueryGroupActions: FC<PropsT> = ({ excludeActive, dateActive, onExcludeClick, onDeleteGroup, onDateClick, }) => { const { t } = useTranslation(); return ( <Actions> <div> <WithTooltip text={t("help.queryEditorExclude")} lazy> <RedIconButton red tight active={excludeActive} icon="ban" onClick={onExcludeClick} > {t("queryEditor.exclude")} </RedIconButton> </WithTooltip> <WithTooltip text={t("help.queryEditorDate")} lazy> <StyledIconButton active={dateActive} regular tight icon="calendar" onClick={onDateClick} > {t("queryEditor.date")} </StyledIconButton> </WithTooltip> </div> <Right> <WithTooltip text={t("queryEditor.removeColumn")}> <IconButton tiny icon="times" onClick={onDeleteGroup} /> </WithTooltip> </Right> </Actions> ); }; export default QueryGroupActions;
manuel-hegner/conquery
frontend/src/js/startup/reducer.ts
<reponame>manuel-hegner/conquery import { getType } from "typesafe-actions"; import type { GetFrontendConfigResponseT } from "../api/types"; import type { Action } from "../app/actions"; import { loadConfig } from "./actions"; export type StartupStateT = { loading: boolean; error: string | null; config: GetFrontendConfigResponseT; }; const initialState: StartupStateT = { loading: false, error: null, config: { version: "No version loaded", queryUpload: { ids: [], }, currency: { prefix: "€", thousandSeparator: ".", decimalSeparator: ",", decimalScale: 2, }, }, }; const startup = ( state: StartupStateT = initialState, action: Action, ): StartupStateT => { switch (action.type) { case getType(loadConfig.request): return { ...state, loading: true, }; case getType(loadConfig.failure): return { ...state, loading: false, error: action.payload.message || null, }; case getType(loadConfig.success): return { ...state, loading: false, config: action.payload.data, }; default: return state; } }; export default startup;
manuel-hegner/conquery
frontend/src/js/common/helpers/useDebounce.ts
<reponame>manuel-hegner/conquery<filename>frontend/src/js/common/helpers/useDebounce.ts import { useEffect, useRef } from "react"; type Timeout = ReturnType<typeof setTimeout>; // Note: No need to add callbacks used inside `fn` to the debounceTriggers // because fn will be saved in a ref / will always be up to date export const useDebounce = ( fn: (...args: any) => any, ms: number, debounceTriggers: any[], ) => { const handle = useRef<Timeout | null>(null); const fnRef = useRef<(...args: any) => any>(fn); const msRef = useRef<number>(ms); useEffect(() => { fnRef.current = fn; }, [fn]); useEffect(() => { msRef.current = ms; }, [ms]); useEffect(() => { if (handle.current) clearTimeout(handle.current); handle.current = setTimeout( fnRef.current.bind(null, ...debounceTriggers), msRef.current, ); return () => { if (handle.current) clearTimeout(handle.current); }; // Yes, dependencies can't be statically verified, // but this way, useDebounce almost works like useEffect // eslint-disable-next-line }, debounceTriggers); };
manuel-hegner/conquery
frontend/src/js/previous-queries/folderFilter/actions.ts
<filename>frontend/src/js/previous-queries/folderFilter/actions.ts import { ActionType, createAction } from "typesafe-actions"; export type FolderFilterActions = ActionType< | typeof addFolderToFilter | typeof removeFolderFromFilter | typeof setFolderFilter | typeof toggleNoFoldersFilter | typeof toggleFoldersOpen >; export const addFolderToFilter = createAction( "previous-queries/ADD_FOLDER_FILTER", )<string>(); export const removeFolderFromFilter = createAction( "previous-queries/REMOVE_FOLDER_FILTER", )<string>(); export const setFolderFilter = createAction( "previous-queries/SET_FOLDER_FILTER", )<string[]>(); export const toggleNoFoldersFilter = createAction( "previous-queries/TOGGLE_NO_FOLDERS_FILTER", )(); export const toggleFoldersOpen = createAction( "previous-queries/TOGGLE_FOLDERS_OPEN", )();
manuel-hegner/conquery
frontend/src/js/previous-queries/search/reducer.ts
import { getType } from "typesafe-actions"; import { Action } from "../../app/actions"; import { clearQueriesSearch, setQueriesSearch } from "./actions"; export interface QueriesSearchStateT { searchTerm: string | null; result: Record<string, number> | null; words: string[]; } const initialState: QueriesSearchStateT = { searchTerm: null, result: null, words: [], }; const previousQueriesSearch = ( state: QueriesSearchStateT = initialState, action: Action, ): QueriesSearchStateT => { switch (action.type) { case getType(setQueriesSearch): return { ...state, ...action.payload }; case getType(clearQueriesSearch): return initialState; default: return state; } }; export default previousQueriesSearch;
manuel-hegner/conquery
frontend/src/js/external-forms/transformQueryToApi.ts
import { transformElementsToApi } from "../api/apiHelper"; import { Form } from "./config-types"; function transformElementGroupsToApi(elementGroups) { return elementGroups.map(({ concepts, connector, ...rest }) => concepts.length > 1 ? { type: connector, children: transformElementsToApi(concepts), ...rest, } : { ...transformElementsToApi(concepts)[0], ...rest }, ); } function transformFieldToApi(fieldConfig, form) { const formValue = form[fieldConfig.name]; switch (fieldConfig.type) { case "RESULT_GROUP": // A RESULT_GROUP field may allow null / be optional return formValue ? formValue.id : null; case "MULTI_RESULT_GROUP": return formValue.map((group) => group.id); case "DATE_RANGE": return { min: formValue.min, max: formValue.max, }; case "CONCEPT_LIST": return transformElementGroupsToApi(formValue); case "TABS": const selectedTab = fieldConfig.tabs.find( (tab) => tab.name === formValue, ); return { value: formValue, // Only include field values from the selected tab ...transformFieldsToApi(selectedTab.fields, form), }; default: return formValue; } } function transformFieldsToApi(fields, form) { return fields.reduce((all, fieldConfig) => { all[fieldConfig.name] = transformFieldToApi(fieldConfig, form); return all; }, {}); } const transformQueryToApi = (formConfig: Form) => (form: Object) => { return { type: formConfig.type, ...transformFieldsToApi(formConfig.fields, form), }; }; export default transformQueryToApi;
manuel-hegner/conquery
frontend/src/js/startup/useStartup.ts
<filename>frontend/src/js/startup/useStartup.ts import { useEffect } from "react"; import { useDispatch } from "react-redux"; import { useLoadDatasets } from "../dataset/actions"; import { resetMessage } from "../snack-message/actions"; import { useLoadMe } from "../user/actions"; import { useLoadConfig } from "./actions"; export const useStartup = () => { const dispatch = useDispatch(); const loadConfig = useLoadConfig(); const loadDatasets = useLoadDatasets(); const loadMe = useLoadMe(); useEffect(() => { dispatch(resetMessage()); loadConfig(); loadDatasets(); loadMe(); }, [dispatch]); };