repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
predominant/builder
components/builder-web/app/util.test.ts
<reponame>predominant/builder // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as util from './util'; describe('util', () => { describe('packageString', () => { describe('with a fully qualified identifier', () => { it('returns the string', () => { expect(util.packageString({ origin: 'testorigin', name: 'testname', version: '1.0.0', release: '197001010000', }) ).toEqual('testorigin/testname/1.0.0/197001010000'); }); }); describe('with a missing parts', () => { it('returns the partial string', () => { expect(util.packageString({ origin: 'testorigin', name: 'testname', }) ).toEqual('testorigin/testname'); }); }); }); describe('parseKey', () => { describe('with an invalid key', () => { it('has a valid:false property', () => { expect(util.parseKey('').valid).toEqual(false); }); }); describe('with a valid key', () => { let keyString; beforeEach(() => { keyString = `SIG-PUB-1 <KEY>`; }); it('has a name property', () => { expect(util.parseKey(keyString).name).toEqual( 'core-20160423193745' ); }); it('has a valid:true property', () => { expect(util.parseKey(keyString).valid).toEqual(true); }); it('has an origin property', () => { expect(util.parseKey(keyString).origin).toEqual('core'); }); it('has a text property', () => { expect(util.parseKey(keyString).text).toEqual(keyString); }); describe('with a private key', () => { beforeEach(() => { keyString = `SIG-SEC-1 core-20160423193745 NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN==`; }); it('has an uploadPath property', () => { expect(util.parseKey(keyString).uploadPath) .toEqual('core/secret_keys/20160423193745'); }); }); describe('with a public key', () => { it('has a type property', () => { expect(util.parseKey(keyString).type).toEqual('SIG-PUB-1'); }); it('has an uploadPath property', () => { expect(util.parseKey(keyString).uploadPath) .toEqual('core/keys/20160423193745'); }); }); }); }); });
predominant/builder
components/builder-web/app/shared/channels/channels.component.ts
<filename>components/builder-web/app/shared/channels/channels.component.ts<gh_stars>10-100 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Input, Output, EventEmitter } from '@angular/core'; import { MatDialog } from '@angular/material'; import { SimpleConfirmDialog } from '../../shared/dialog/simple-confirm/simple-confirm.dialog'; @Component({ selector: 'hab-channels', template: require('./channels.component.html') }) export class ChannelsComponent { @Input() channels: string[]; @Input() canDemote: boolean = false; @Output() onDemote: EventEmitter<string> = new EventEmitter<string>(); constructor( private confirmDialog: MatDialog, ) { } demotable(channel) { return this.canDemote && channel !== 'unstable'; } outerClick(e) { e.stopPropagation(); } demote(channel) { this.confirmDialog .open(SimpleConfirmDialog, { width: '480px', data: { heading: 'Confirm demote', body: `Are you sure you want to remove this package from the ${channel} channel?`, action: 'demote it' } }) .afterClosed() .subscribe((confirmed) => { if (confirmed) { this.onDemote.emit(channel); } }); } }
predominant/builder
components/builder-web/cypress/integration/search.spec.ts
describe('Search', () => { const results = () => cy.get('.results-component li'); const summary = () => cy.get('.more'); const moreLink = () => cy.get('.more a'); const none = () => cy.get('.results-component .none'); beforeEach(() => { cy.server(); cy.fixture(`search/page-1`).as('page1'); cy.fixture(`search/page-2`).as('page2'); cy.fixture(`search/param`).as('search'); cy.fixture('search/none').as('none'); cy.route('GET', `/v1/depot/pkgs/core?range=0&distinct=true`, '@page1'); cy.route('GET', `/v1/depot/pkgs/core?range=50&distinct=true`, '@page2'); cy.route('GET', `/v1/depot/pkgs/search/ac?range=0&distinct=true`, '@search'); cy.route('GET', `/v1/depot/pkgs/search/nope?range=0&distinct=true`, '@none'); }); describe('given an origin in the URL path', () => { beforeEach(() => { cy.visit('/#/pkgs/core'); }); it('renders the first page of results from the that origin', () => { results().should('have.length', 50); }); }); describe('given a querystring param', () => { beforeEach(() => { cy.visit('/#/pkgs/core;q=ac'); }); it('renders results based on that param', () => { results().should('have.length', 2); }); }); describe('when more than one page of results exists', () => { beforeEach(() => { cy.visit('/#/pkgs/core'); }); it('renders the first page', () => { results().should('have.length', 50); summary().should('contain', 'Showing 50 of 690 packages.'); moreLink().should('contain', 'Load 50 more.'); }); describe('and I click to load more', () => { beforeEach(() => { cy.get('.more a').click(); }); it('renders the second page', () => { results().should('have.length', 100); summary().should('contain', 'Showing 100 of 690 packages.'); moreLink().should('contain', 'Load 50 more.'); }); }); }); describe('when no results are found', () => { beforeEach(() => { cy.visit('/#/pkgs/core;q=nope'); }); it('shows a not-found message', () => { results().should('have.length', 0); none().should('contain', 'No packages found.'); }); }); });
predominant/builder
components/builder-web/app/shared/shared.module.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DomSanitizer } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { MatCheckbox, MatCheckboxModule, MatIconModule, MatIconRegistry, MatRadioModule, MatRadioGroup, MatRadioButton, MatSlideToggleModule, MatSlideToggle, MatTooltipModule, MatTabsModule, MatButtonModule } from '@angular/material'; import { AutoBuildSettingsComponent } from './auto-build-settings/auto-build-settings.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BreadcrumbsComponent } from './breadcrumbs/breadcrumbs.component'; import { ChannelsComponent } from './channels/channels.component'; import { CheckingInputComponent } from './checking-input/checking-input.component'; import { CopyableComponent } from './copyable/copyable.component'; import { DockerExportSettingsComponent } from './docker-export-settings/docker-export-settings.component'; import { DockerExportSettingsDialog } from './docker-export-settings/dialog/docker-export-settings.dialog'; import { DisconnectConfirmDialog } from './project-settings/dialog/disconnect-confirm/disconnect-confirm.dialog'; import { IconComponent } from './icon/icon.component'; import { JobCancelDialog } from './dialog/job-cancel/job-cancel.dialog'; import { JobStatusComponent } from './job-status/job-status.component'; import { JobStatusIconComponent } from './job-status-icon/job-status-icon.component'; import { JobStatusLabelComponent } from './job-status-label/job-status-label.component'; import { PackageListComponent } from './package-list/package-list.component'; import { ProjectSettingsComponent } from './project-settings/project-settings.component'; import { PlatformIconComponent } from './platform-icon/platform-icon.component'; import { VisibilityIconComponent } from './visibility-icon/visibility-icon.component'; import { VisibilitySelectorComponent } from './visibility-selector/visibility-selector.component'; import { KeysPipe } from './pipes/keys.pipe'; import { SimpleConfirmDialog } from './dialog/simple-confirm/simple-confirm.dialog'; import { BuilderEnabledGuard } from './guards/builder-enabled.guard'; import { OriginMemberGuard } from './guards/origin-member.guard'; import { SignedInGuard } from './guards/signed-in.guard'; import { JobNoticeComponent } from './job-notice/job-notice.component'; @NgModule({ imports: [ BrowserAnimationsModule, CommonModule, FormsModule, MatCheckboxModule, MatIconModule, MatTabsModule, MatRadioModule, MatSlideToggleModule, MatTooltipModule, MatButtonModule, ReactiveFormsModule, RouterModule ], declarations: [ AutoBuildSettingsComponent, BreadcrumbsComponent, ChannelsComponent, CheckingInputComponent, CopyableComponent, DisconnectConfirmDialog, DockerExportSettingsComponent, DockerExportSettingsDialog, IconComponent, JobCancelDialog, JobStatusComponent, JobStatusIconComponent, JobStatusLabelComponent, PackageListComponent, ProjectSettingsComponent, PlatformIconComponent, VisibilityIconComponent, VisibilitySelectorComponent, SimpleConfirmDialog, JobNoticeComponent, KeysPipe ], entryComponents: [ DisconnectConfirmDialog, DockerExportSettingsDialog, JobCancelDialog, SimpleConfirmDialog ], exports: [ BreadcrumbsComponent, ChannelsComponent, CheckingInputComponent, CopyableComponent, DisconnectConfirmDialog, DockerExportSettingsComponent, IconComponent, JobStatusComponent, JobStatusIconComponent, JobStatusLabelComponent, MatCheckbox, MatRadioGroup, MatRadioButton, MatSlideToggle, PackageListComponent, VisibilityIconComponent, VisibilitySelectorComponent, ProjectSettingsComponent, PlatformIconComponent, KeysPipe, SimpleConfirmDialog, JobNoticeComponent ], providers: [ BuilderEnabledGuard, OriginMemberGuard, SignedInGuard ] }) export class SharedModule { constructor(private matIconRegistry: MatIconRegistry, private sanitizer: DomSanitizer) { // At the time of this monkeypatching, the SVG settings applied by MatIconRegistry // were missing the `viewBox` attribute, which is responsible for mapping the coordinate space // of an SVG image to that of the viewport, enabling proper scaling. While we await resolution // of the issue below, we'll go ahead and plow right over Angular's implementation, // 'cause JavaScript is awesome. // https://github.com/angular/material2/issues/5188 // https://github.com/angular/material2/blob/bef6271c617f6904cc360454805ea080e2212f2a/src/lib/icon/icon-registry.ts#L424-L436 matIconRegistry['_setSvgAttributes'] = (svg: SVGElement): SVGElement => { if (!svg.getAttribute('xmlns')) { svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); } svg.setAttribute('fit', ''); svg.setAttribute('height', '100%'); svg.setAttribute('width', '100%'); svg.setAttribute('viewBox', '0 0 24 24'); // This is the one we care about. svg.setAttribute('preserveAspectRatio', 'xMidYMid meet'); svg.setAttribute('focusable', 'false'); return svg; }; matIconRegistry.addSvgIconSet( sanitizer.bypassSecurityTrustResourceUrl('/assets/images/icons/all.svg') ); } }
predominant/builder
components/builder-web/app/shared/docker-export-settings/docker-export-settings.component.ts
<gh_stars>10-100 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Input, OnChanges, OnDestroy, SimpleChanges } from '@angular/core'; import { MatDialog } from '@angular/material'; import { DockerExportSettingsDialog } from './dialog/docker-export-settings.dialog'; import { fetchProjectIntegration } from '../../actions/projects'; import { AppStore } from '../../app.store'; @Component({ selector: 'hab-docker-export-settings', template: require('./docker-export-settings.component.html') }) export class DockerExportSettingsComponent implements OnChanges, OnDestroy { @Input() origin: string; @Input() package: string; @Input() integrations: any; @Input() current: any; @Input() enabled: boolean = false; private name: string; private docker_hub_repo_name: string = ''; private custom_tag: string; private latest_tag: boolean = true; private version_tag: boolean = true; private version_release_tag: boolean = true; private unsubscribe: Function; constructor( private store: AppStore, private dialog: MatDialog ) { } get configured() { return Object.keys(this.integrations).length > 0; } get settings(): any { return { valid: this.valid, name: this.name, enabled: this.enabled, settings: { docker_hub_repo_name: this.docker_hub_repo_name, custom_tag: this.custom_tag, latest_tag: this.latest_tag, version_tag: this.version_tag, version_release_tag: this.version_release_tag } }; } get repoPlaceholder() { return this.store.getState().projects.current.name || `${this.username}/example-repo`; } get token() { return this.store.getState().session.token; } get username() { return this.store.getState().users.current.profile.name; } get valid() { if (this.docker_hub_repo_name && this.docker_hub_repo_name.trim() !== '') { return true; } return false; } applySettings(name, settings) { this.name = name; this.docker_hub_repo_name = settings.docker_hub_repo_name; this.custom_tag = settings.custom_tag; this.latest_tag = settings.latest_tag; this.version_tag = settings.version_tag; this.version_release_tag = settings.version_release_tag; } configure(integration) { this.name = integration; const integrations = this.store.getState().projects.current.settings; const settings = integrations.get(integration) || {}; this.dialog .open(DockerExportSettingsDialog, { data: { repoPlaceholder: this.repoPlaceholder, docker_hub_repo_name: settings.docker_hub_repo_name, custom_tag: settings.custom_tag, latest_tag: settings.latest_tag, version_tag: settings.version_tag, version_release_tag: settings.version_release_tag }, width: '480px' }) .afterClosed() .subscribe((result) => { if (result) { this.applySettings(integration, result); } else if (!this.settingsFor(integration)) { this.name = null; } }); } decode(s) { return decodeURIComponent(s); } ngOnChanges(changes: SimpleChanges) { const i: any = changes['integrations']; if (i && i.currentValue) { const integrations = i.currentValue; Object.keys(integrations).forEach(key => { integrations[key].forEach(name => { this.store.dispatch(fetchProjectIntegration(this.origin, this.package, name, this.token)); }); }); this.unsubscribe = this.store.subscribe(state => { state.projects.current.settings.forEach((v, k) => { this.applySettings(k, v); this.unsubscribe(); return false; }); }); } } ngOnDestroy() { if (this.unsubscribe) { this.unsubscribe(); } } onChange(name) { const settings = this.settingsFor(name); this.applySettings(name, settings || {}); if (!settings) { this.configure(name); } } settingsFor(integration) { return this.store.getState().projects.current.settings.get(integration); } }
predominant/builder
components/builder-web/app/package/package-detail/package-detail.component.spec.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { TestBed, ComponentFixture } from '@angular/core/testing'; import { DebugElement } from '@angular/core'; import { By } from '@angular/platform-browser'; import { of } from 'rxjs'; import { MockComponent } from 'ng2-mock-component'; import { Package } from '../../records/Package'; import { AppStore } from '../../app.store'; import { PackageDetailComponent } from './package-detail.component'; class MockAppStore { getState() { return { origins: { mine: [] }, packages: { currentChannels: [] } }; } dispatch() { } } class MockRoute { params = of({ origin: 'core', name: 'nginx' }); } describe('PackageDetailComponent', () => { let fixture: ComponentFixture<PackageDetailComponent>; let component: PackageDetailComponent; let element: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ PackageDetailComponent, MockComponent({ selector: 'hab-platform-icon', inputs: ['platform'] }), MockComponent({ selector: 'hab-channels', inputs: ['channels', 'canDemote'], outputs: ['demote'] }), MockComponent({ selector: 'hab-package-list', inputs: ['currentPackage', 'packages'] }), MockComponent({ selector: 'hab-package-promote', inputs: ['origin', 'name', 'version', 'release', 'target', 'channel'] }), MockComponent({ selector: 'hab-copyable', inputs: ['text', 'style'] }) ], providers: [ { provide: AppStore, useClass: MockAppStore }] }); fixture = TestBed.createComponent(PackageDetailComponent); component = fixture.componentInstance; element = fixture.debugElement; }); describe('given a package', () => { beforeEach(() => { component.package = Package({ ident: { origin: 'core', name: 'nginx', version: '1.11.10', release: '20170829004822' }, checksum: 'some-checksum', channels: ['unstable', 'stable'] }); }); it('renders it', () => { fixture.detectChanges(); function textOf(selector) { return element.query(By.css(`.package-detail-component ${selector}`)).nativeElement.textContent; } expect(textOf('.metadata')).toContain('1.11.10'); expect(textOf('.metadata')).toContain('20170829004822'); expect(textOf('.metadata')).toContain('some-checksum'); }); }); });
predominant/builder
components/builder-web/app/shared/job-status/job-status.component.ts
<reponame>predominant/builder import { Component, Input } from '@angular/core'; @Component({ selector: 'hab-job-status', template: ` <hab-job-status-icon [job]="job" [animate]="true"></hab-job-status-icon> <hab-job-status-label [job]="job"></hab-job-status-label> ` }) export class JobStatusComponent { @Input() job: any; }
predominant/builder
components/builder-web/app/notifications/notifications.component.spec.ts
<filename>components/builder-web/app/notifications/notifications.component.spec.ts<gh_stars>10-100 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { DebugElement } from '@angular/core'; import { TestBed, ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NotificationsComponent } from './notifications.component'; describe('NotificationsComponent', () => { let fixture: ComponentFixture<NotificationsComponent>; let component: NotificationsComponent; let element: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ NotificationsComponent ] }); fixture = TestBed.createComponent(NotificationsComponent); component = fixture.componentInstance; element = fixture.debugElement; }); describe('when one or more notifications are provided', () => { let notifications = [ { type: 'success', title: 'Woohoo!', body: 'It worked.' }, { type: 'danger', title: 'Oh no!', body: 'Something went wrong.' } ]; beforeEach(() => { component.notifications = notifications; component.removeNotification = () => { }; fixture.detectChanges(); }); it('renders them', () => { let items = element.queryAll(By.css('ul.hab-notifications li')); expect(items.length).toBe(2); let first = items[0], second = items[1]; expect(first.query(By.css('small')).nativeElement.textContent) .toBe(notifications[0].type); expect(first.query(By.css('h1')).nativeElement.textContent) .toBe(notifications[0].title); expect(first.query(By.css('p')).nativeElement.textContent) .toBe(notifications[0].body); expect(second.query(By.css('small')).nativeElement.textContent) .toBe(notifications[1].type); }); it('delegates to the supplied dismiss function', () => { spyOn(component, 'removeNotification'); let second = element.queryAll(By.css('ul.hab-notifications li a'))[1]; second.triggerEventHandler('click', {}); fixture.detectChanges(); expect(component.removeNotification).toHaveBeenCalledWith(1); }); }); });
predominant/builder
components/builder-web/app/package/package-promote/package-promote.component.ts
<gh_stars>10-100 import { Component, Input } from '@angular/core'; import { MatDialog } from '@angular/material'; import { AppStore } from '../../app.store'; import { promotePackage } from '../../actions/index'; import { SimpleConfirmDialog } from '../../shared/dialog/simple-confirm/simple-confirm.dialog'; @Component({ selector: 'hab-package-promote', template: require('./package-promote.component.html') }) export class PackagePromoteComponent { @Input() origin: string; @Input() name: string; @Input() version: string; @Input() release: string; @Input() channel: string; @Input() target: string; promoting: boolean = false; constructor( private confirmDialog: MatDialog, private store: AppStore ) { } prompt(evt) { evt.stopPropagation(); this.confirmDialog .open(SimpleConfirmDialog, { width: '480px', data: { heading: 'Confirm promote', body: `Are you sure you want to promote this artifact? Doing so will add the artifact to the ${this.channel} channel.`, action: 'promote it' } }) .afterClosed() .subscribe((confirmed) => { if (confirmed) { this.promoting = true; setTimeout(() => { this.store.dispatch( promotePackage(this.origin, this.name, this.version, this.release, this.target, this.channel, this.store.getState().session.token) ); }, 1000); } }); } }
predominant/builder
components/builder-web/app/package/package.module.ts
<gh_stars>1-10 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { MatTabsModule, MatButtonModule, MatRadioModule } from '@angular/material'; import { JobDetailComponent } from './job-detail/job-detail.component'; import { JobListComponent } from './job-list/job-list.component'; import { PackageJobComponent } from './package-job/package-job.component'; import { PackageComponent } from './package/package.component'; import { PackageJobsComponent } from './package-jobs/package-jobs.component'; import { PackageDetailComponent } from './package-detail/package-detail.component'; import { PackageLatestComponent } from './package-latest/package-latest.component'; import { PackagePromoteComponent } from './package-promote/package-promote.component'; import { PackageSettingsComponent } from './package-settings/package-settings.component'; import { PackageReleaseComponent } from './package-release/package-release.component'; import { PackageSidebarComponent } from './package-sidebar/package-sidebar.component'; import { PackageVersionsComponent } from './package-versions/package-versions.component'; import { SharedModule } from '../shared/shared.module'; import { PackageRoutingModule } from './package-routing.module'; @NgModule({ imports: [ CommonModule, FormsModule, PackageRoutingModule, ReactiveFormsModule, RouterModule, MatTabsModule, MatButtonModule, MatRadioModule, SharedModule, FormsModule, ReactiveFormsModule ], declarations: [ JobDetailComponent, JobListComponent, PackageComponent, PackageJobComponent, PackageJobsComponent, PackageLatestComponent, PackageDetailComponent, PackagePromoteComponent, PackageReleaseComponent, PackageSidebarComponent, PackageSettingsComponent, PackageVersionsComponent ] }) export class PackageModule { }
predominant/builder
components/builder-web/app/package/package-sidebar/package-sidebar.component.ts
<gh_stars>1-10 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AppStore } from '../../app.store'; import { fetchLatestInChannel, fetchPackageVersions, submitJob } from '../../actions/index'; @Component({ selector: 'hab-package-sidebar', template: require('./package-sidebar.component.html') }) export class PackageSidebarComponent implements OnChanges { @Input() origin: string; @Input() name: string; @Input() building: boolean = false; @Input() buildable: boolean = false; constructor(private store: AppStore) { } ngOnChanges(changes: SimpleChanges) { let fetch = false; if (changes['origin']) { this.origin = changes['origin'].currentValue; fetch = true; } if (changes['name']) { this.name = changes['name'].currentValue; fetch = true; } if (fetch) { this.fetchLatestStable(); this.fetchPackageVersions(); } } build() { if (this.buildable) { let token = this.store.getState().session.token; this.store.dispatch(submitJob(this.origin, this.name, token)); } } get buildButtonLabel() { return this.building ? 'Build pending' : 'Build latest version'; } get exportCommand() { return `hab pkg export docker ${this.origin}/${this.name}`; } get isAService() { return this.latestStable && this.latestStable.is_a_service; } get latestStable() { return this.store.getState().packages.latestInChannel.stable; } get loadingLatestStable() { return this.store.getState().packages.ui.latestInChannel.stable.loading; } get project() { return this.store.getState().projects.current; } get runCommand() { return `hab start ${this.origin}/${this.name}`; } get autoBuildSetting() { return this.project.auto_build ? 'enabled' : 'disabled'; } get repoName() { return (this.project.vcs_data.match(/github.com\/(.+)\.git$/) || [''])[1] || ''; } get repoUrl() { return this.project.vcs_data.replace('.git', ''); } get platforms() { let targets = []; let versions = this.store.getState().packages.versions || []; versions.forEach((v) => { v.platforms.forEach((p) => { if (targets.indexOf(p) === -1) { targets.push(p); } }); }); return targets.sort(); } private fetchLatestStable() { this.store.dispatch(fetchLatestInChannel(this.origin, this.name, 'stable')); } private fetchPackageVersions() { this.store.dispatch(fetchPackageVersions(this.origin, this.name)); } }
predominant/builder
components/builder-web/app/actions/gitHub.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'whatwg-fetch'; import { GitHubApiClient } from '../client/github-api'; import { Browser } from '../browser'; export const CLEAR_GITHUB_INSTALLATIONS = 'CLEAR_GITHUB_INSTALLATIONS'; export const CLEAR_GITHUB_REPOSITORIES = 'CLEAR_GITHUB_REPOSITORIES'; export const POPULATE_GITHUB_INSTALLATIONS = 'POPULATE_GITHUB_INSTALLATIONS'; export const POPULATE_GITHUB_REPOSITORIES = 'POPULATE_GITHUB_REPOSITORIES'; export const POPULATE_GITHUB_USER_DATA = 'POPULATE_GITHUB_USER_DATA'; export function fetchGitHubInstallations(username: string) { const token = Browser.getCookie('oauthToken'); return dispatch => { const client = new GitHubApiClient(token); dispatch(clearGitHubInstallations()); client.getUserInstallations(username) .then((results) => { dispatch(populateGitHubInstallations(results)); }) .catch((error) => { console.error(error); }); }; } export function fetchGitHubRepositories(installationID: number) { const token = Browser.getCookie('oauthToken'); return dispatch => { const client = new GitHubApiClient(token); dispatch(clearGitHubRepositories()); client.getAllUserInstallationRepositories(installationID) .then((results) => { dispatch(populateGitHubRepositories(results)); }) .catch((error) => { console.error(error); }); }; } function clearGitHubInstallations() { return { type: CLEAR_GITHUB_INSTALLATIONS }; } function populateGitHubInstallations(payload) { return { type: POPULATE_GITHUB_INSTALLATIONS, payload, }; } function clearGitHubRepositories() { return { type: CLEAR_GITHUB_REPOSITORIES }; } function populateGitHubRepositories(payload) { return { type: POPULATE_GITHUB_REPOSITORIES, payload, }; }
predominant/builder
components/builder-web/app/origin/origin-page/origin-packages-tab/origin-packages-tab.component.ts
<gh_stars>0 // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, OnInit, OnDestroy } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { AppStore } from '../../../app.store'; import { getUniquePackages } from '../../../actions/index'; import config from '../../../config'; @Component({ selector: 'hab-origin-packages-tab', template: require('./origin-packages-tab.component.html') }) export class OriginPackagesTabComponent implements OnInit, OnDestroy { selectingPlan: boolean = false; private sub: Subscription; constructor( private store: AppStore, private router: Router, private route: ActivatedRoute, private title: Title ) { } ngOnInit() { this.sub = this.route.parent.params.subscribe((params) => { this.title.setTitle(`Origins › ${params.origin} › Packages | Habitat`); }); } ngOnDestroy() { if (this.sub) { this.sub.unsubscribe(); } } get builderEnabled() { return config.enable_builder; } get integrations() { return this.store.getState().origins.currentIntegrations.integrations; } get memberOfOrigin() { return !!this.store.getState().origins.mine.find(origin => origin['name'] === this.origin); } get origin() { return this.store.getState().origins.current.name; } get packagesUi() { return this.store.getState().packages.ui.visible; } get perPage() { return this.store.getState().packages.perPage; } get projectsUi() { return this.store.getState().projects.ui.visible; } get projects() { return this.store.getState().projects.visible; } get projectsExist() { return this.projectsUi.exists && this.projects.size > 0; } get packages() { return this.store.getState().packages.visible; } get token() { return this.store.getState().session.token; } get totalCount() { return this.store.getState().packages.totalCount; } get noPackages() { return (!this.packagesUi.exists || this.packages.size === 0) && !this.packagesUi.loading; } fetchMorePackages() { this.store.dispatch( getUniquePackages(this.origin, this.store.getState().packages.nextRange, this.token) ); } saved(project) { this.router.navigate(['/pkgs', project.origin, project.name, 'settings']); } toggled(active) { this.selectingPlan = active; } }
predominant/builder
components/builder-web/app/side-nav/side-nav.component.spec.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { DebugElement } from '@angular/core'; import { TestBed, ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { MockComponent } from 'ng2-mock-component'; import { SideNavComponent } from './side-nav.component'; describe('SideNavComponent', () => { let fixture: ComponentFixture<SideNavComponent>; let element: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule, ], declarations: [ SideNavComponent, MockComponent({ selector: 'hab-icon', inputs: [ 'symbol' ] }), MockComponent({ selector: 'hab-statuspage' }) ] }); fixture = TestBed.createComponent(SideNavComponent); element = fixture.debugElement; }); it('has links', () => { let links = element.queryAll(By.css('ul li a')); expect(links.length).toBeGreaterThan(0); }); });
predominant/builder
components/builder-web/cypress/integration/home.spec.ts
<reponame>predominant/builder describe('The default route', () => { beforeEach(() => { cy.server(); cy.fixture('search/some').as('some'); cy.route('GET', '/v1/depot/pkgs/core?range=0&distinct=true', '@some'); cy.visit('/#/'); }); it('renders the search view', () => { cy.get('header h1').should('contain', 'Search Packages'); cy.get('.results-component li').children().should('have.length.greaterThan', 0); }); });
predominant/builder
components/builder-web/app/origin/origin-page/origin-page-routing.module.ts
<reponame>predominant/builder // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { OriginPageComponent } from '../origin-page/origin-page.component'; import { OriginKeysTabComponent } from './origin-keys-tab/origin-keys-tab.component'; import { OriginMembersTabComponent } from './origin-members-tab/origin-members-tab.component'; import { OriginPackagesTabComponent } from './origin-packages-tab/origin-packages-tab.component'; import { OriginSettingsTabComponent } from './origin-settings-tab/origin-settings-tab.component'; import { OriginIntegrationsTabComponent } from './origin-integrations-tab/origin-integrations-tab.component'; import { OriginJobsTabComponent } from './origin-jobs-tab/origin-jobs-tab.component'; import { OriginJobDetailComponent } from './origin-job-detail/origin-job-detail.component'; import { BuilderEnabledGuard } from '../../shared/guards/builder-enabled.guard'; import { OriginMemberGuard } from '../../shared/guards/origin-member.guard'; import { SignedInGuard } from '../../shared/guards/signed-in.guard'; const routes: Routes = [ { path: 'origins/:origin', component: OriginPageComponent, children: [ { path: '', redirectTo: 'packages', pathMatch: 'full' }, { path: 'packages', component: OriginPackagesTabComponent }, { path: 'keys', component: OriginKeysTabComponent }, { path: 'members', component: OriginMembersTabComponent, canActivate: [SignedInGuard, OriginMemberGuard], }, { path: 'settings', component: OriginSettingsTabComponent, canActivate: [BuilderEnabledGuard, SignedInGuard, OriginMemberGuard], }, { path: 'integrations', component: OriginIntegrationsTabComponent, canActivate: [BuilderEnabledGuard, SignedInGuard, OriginMemberGuard] }, { path: 'jobs', component: OriginJobsTabComponent, canActivate: [BuilderEnabledGuard, SignedInGuard, OriginMemberGuard] }, { path: 'jobs/:id', component: OriginJobDetailComponent, canActivate: [BuilderEnabledGuard, SignedInGuard, OriginMemberGuard] }, { path: '**', redirectTo: 'packages' } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class OriginPageRoutingModule { }
predominant/builder
components/builder-web/app/shared/copyable/copyable.component.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Input, ViewChild } from '@angular/core'; import { MatTooltip } from '@angular/material'; @Component({ selector: 'hab-copyable', template: require('./copyable.component.html') }) export class CopyableComponent { @Input() text: string = ''; @Input() style: string = 'unstyled'; public copied: boolean = false; @ViewChild(MatTooltip) tooltip: MatTooltip; copy(event) { event.stopPropagation(); let el = document.createElement('input'); Object.assign(el.style, { opacity: '0', position: 'fixed', left: '-200px' }); document.body.appendChild(el); el.value = this.text; el.select(); document.execCommand('copy'); document.body.removeChild(el); this.copied = true; setTimeout(() => { this.tooltip.show(); }, 10); setTimeout(() => { this.copied = false; }, 2500); } get symbol() { return this.copied ? 'check' : 'copy'; } get title() { return this.copied ? 'Copied!' : 'Copy to clipboard'; } }
predominant/builder
components/builder-web/app/shared/docker-export-settings/dialog/docker-export-settings.dialog.ts
<reponame>predominant/builder // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; @Component({ template: require('./docker-export-settings.dialog.html') }) export class DockerExportSettingsDialog { private repoPlaceholder: string; private docker_hub_repo_name: string; private custom_tag: string; private latest_tag: boolean; private version_tag: boolean; private version_release_tag: boolean; constructor( private ref: MatDialogRef<DockerExportSettingsDialog>, @Inject(MAT_DIALOG_DATA) private data: any ) { this.repoPlaceholder = data.repoPlaceholder; this.docker_hub_repo_name = data.docker_hub_repo_name; this.custom_tag = data.custom_tag; this.latest_tag = !!data.latest_tag; this.version_tag = !!data.version_tag; this.version_release_tag = !!data.version_release_tag; } get settings() { return { docker_hub_repo_name: this.docker_hub_repo_name, custom_tag: this.custom_tag, latest_tag: this.latest_tag, version_tag: this.version_tag, version_release_tag: this.version_release_tag }; } ok() { this.ref.close(this.settings); } cancel() { this.ref.close(null); } }
predominant/builder
components/builder-web/app/shared/job-status-label/job-status-label.component.ts
import { Component, Input } from '@angular/core'; import { iconForJobState, labelForJobState } from '../../util'; @Component({ selector: 'hab-job-status-label', template: `<span [class]="classFor(job)" [title]="labelFor(job)">{{ labelFor(job) }}</span>` }) export class JobStatusLabelComponent { @Input() job: object; private classFor({ state }) { if (state) { return state.toLowerCase(); } } private labelFor({ state }) { if (state) { return labelForJobState(state); } } }
predominant/builder
components/builder-web/app/reducers/jobs.ts
<reponame>predominant/builder<filename>components/builder-web/app/reducers/jobs.ts // Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { List, Record } from 'immutable'; import * as actionTypes from '../actions/index'; import initialState from '../initial-state'; export default function jobs(state = initialState['jobs'], action) { switch (action.type) { case actionTypes.CLEAR_JOB: return state .setIn(['selected', 'info'], Record({})()) .setIn(['ui', 'selected', 'info', 'loading'], false); case actionTypes.CLEAR_JOB_LOG: state.get('selected').log.content.next([]); return state .setIn(['selected', 'log'], { start: undefined, stop: undefined, content: state.get('selected').log.content, is_complete: undefined }) .setIn(['ui', 'selected', 'log', 'loading'], false); case actionTypes.CLEAR_JOBS: return state .setIn(['visible'], List()) .setIn(['ui', 'loading'], false); case actionTypes.POPULATE_JOB: return state.setIn(['selected', 'info'], action.payload); case actionTypes.POPULATE_JOB_LOG: if (action.error) { return state.setIn(['selected', 'log'], { start: undefined, stop: undefined, content: state.get('selected').log.content, is_complete: undefined }); } else { let payload = action.payload; let content = state.get('selected').log.content; if (payload.start === 0 && !payload.is_complete) { content.next(payload.content || []); } else if (payload.content.length) { content.next(payload.content); } return state.setIn(['selected', 'log'], { start: payload.start, stop: payload.stop, content: content, is_complete: payload.is_complete }); } case actionTypes.POPULATE_JOBS: return state.setIn(['visible'], List(action.payload)); case actionTypes.STREAM_JOB_LOG: return state.setIn(['selected', 'stream'], action.payload); case actionTypes.SET_JOB_LOADING: return state.setIn(['ui', 'selected', 'info', 'loading'], action.payload); case actionTypes.SET_JOBS_LOADING: return state.setIn(['ui', 'loading'], action.payload); case actionTypes.SET_JOB_LOG_LOADING: return state.setIn(['ui', 'selected', 'log', 'loading'], action.payload); case actionTypes.SET_JOB_LOG_NOT_FOUND: return state.setIn(['ui', 'selected', 'log', 'notFound'], action.payload); default: return state; } }
predominant/builder
components/builder-web/app/sign-in-page/sign-in-page.component.ts
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Component, OnDestroy } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { AppStore } from '../app.store'; import { setLayout, signOut } from '../actions/index'; import config from '../config'; @Component({ template: require('./sign-in-page.component.html') }) export class SignInPageComponent implements OnDestroy { constructor(private store: AppStore, private title: Title) { store.dispatch(signOut(false)); this.title.setTitle('Sign In | Habitat'); this.store.dispatch(setLayout('sign-in')); } get providerType() { return this.store.getState().oauth.provider.type; } get providerName() { return this.store.getState().oauth.provider.name; } get loginUrl() { const provider = this.store.getState().oauth.provider; const qs = Object.keys(provider.params) .map(k => `${k}=${encodeURIComponent(provider.params[k])}`) .join('&'); return `${provider.authorizeUrl}?${qs}`; } get signupUrl() { return this.store.getState().oauth.provider.signupUrl; } get wwwUrl() { return config['www_url']; } ngOnDestroy() { this.store.dispatch(setLayout('default')); } }
Hyurl/sfn-schedule-parser
src/util.ts
<filename>src/util.ts import { DateTimeLike, DateTime } from "./types"; import { TimeoutLimit, BigMonths, ReversedProps, Props } from "./consts"; export function ucfirst(str: string): string { return str[0].toUpperCase() + str.substring(1); } export function isWildcard(data: any): boolean { return typeof data == "string" && data[0] == "*"; } export function getNextTick(dateInfo: DateTimeLike, date?: Date): DateTime { date = date || new Date(); let tickInfo: DateTime = {}, shouldForward = true, prevWildcarProp = "", resetPrevProp = (prevProp: string, curProp: string): string => { if (prevProp) { if (prevProp == "date" || prevProp == "month") tickInfo[prevProp] = 1; else tickInfo[prevProp] = 0; } return curProp; }; for (let x of ReversedProps) { if (!(x in dateInfo)) { continue; } else if (typeof dateInfo[x] == "number") { let method: string; if (["seconds", "minutes", "hours", "date", "day", "month"].indexOf(x)) { method = "get" + ucfirst(x); } else { method = "getFullYear"; } let currentValue = date[method](); if (x == "month") currentValue += 1; tickInfo[x] = dateInfo[x]; shouldForward = dateInfo[x] < currentValue; } else { if (shouldForward) prevWildcarProp = resetPrevProp(prevWildcarProp, x); let step = shouldForward ? parseInt(dateInfo[x].split("/")[1] || 1) : 0, num: number; switch (x) { case "seconds": num = date.getSeconds() + step; shouldForward = num >= 60; tickInfo[x] = shouldForward ? num - 60 : num; break; case "minutes": num = date.getMinutes() + step; shouldForward = num >= 60; tickInfo[x] = shouldForward ? num - 60 : num; break; case "hours": num = date.getHours() + step; shouldForward = num >= 24; tickInfo[x] = shouldForward ? num - 24 : num; break; case "date": num = date.getDate() + step; let currentYear = date.getFullYear(), isLeapYear = currentYear % 4 === 0, currentMonth = date.getMonth() + 1, isBigMonth = BigMonths.indexOf(currentMonth) >= 0; if (currentMonth == 2) { // Feb. if (isLeapYear && num > 29 || num > 28) { shouldForward = true; tickInfo[x] = num - (isLeapYear ? 29 : 28); } else { shouldForward = false; tickInfo[x] = num; } } else if (isBigMonth && num > 31 || num > 30) { shouldForward = true; tickInfo[x] = num - (isBigMonth ? 31 : 30); } else { shouldForward = false; tickInfo[x] = num; } break; case "day": num = date.getDay() + (step > 0 ? (step - 1) * 7 : 0); shouldForward = num > 6; tickInfo[x] = shouldForward ? num - 6 : num; break; case "month": num = date.getMonth() + 1 + step; shouldForward = num > 12; tickInfo[x] = shouldForward ? num - 12 : num; break; case "year": tickInfo[x] = date.getFullYear() + step; break; } } } return correctDates(tickInfo, date); } function correctDates(tickInfo: DateTime, date?: Date): DateTime { date = date || new Date(); for (let x of ReversedProps) { if (tickInfo[x] === undefined) { continue; } else if (x == "seconds" && tickInfo[x] >= 60) { if (tickInfo.minutes !== undefined) { tickInfo[x] -= 60; tickInfo.minutes += 1; } else { tickInfo[x] = undefined; } } else if (x == "minutes" && tickInfo[x] >= 60) { if (tickInfo.hours !== undefined) { tickInfo[x] -= 60; tickInfo.hours += 1; } else { tickInfo[x] = undefined; } } else if (x == "hours" && tickInfo[x] >= 24) { if (tickInfo.date !== undefined) { tickInfo[x] -= 24; tickInfo.date += 1; } else { tickInfo[x] = undefined; } } else if (x == "date") { let currentYear = date.getFullYear(), isLeapYear = currentYear % 4 === 0, currentMonth = date.getMonth() + 1, isBigMonth = BigMonths.indexOf(currentMonth) >= 0; if (currentMonth == 2) { // Feb. if (isLeapYear && tickInfo[x] > 29 || tickInfo[x] > 28) { if (tickInfo.month !== undefined) { tickInfo[x] -= isLeapYear ? 29 : 28; tickInfo.month += 1; } else { tickInfo[x] = undefined; } } } else if (isBigMonth && tickInfo[x] > 31 || tickInfo[x] > 30) { if (tickInfo.month !== undefined) { tickInfo[x] -= isLeapYear ? 31 : 30; tickInfo.month += 1; } else { tickInfo[x] = undefined; } } } else if (x == "day" && tickInfo[x] > 6) { if (tickInfo.month !== undefined) { tickInfo[x] %= 7; tickInfo.month += Math.ceil(tickInfo[x] / 7 / 4.1) + 1; } else { tickInfo[x] = undefined; } } else if (x == "month" && tickInfo[x] > 12) { if (tickInfo.year !== undefined) { tickInfo[x] -= 12; tickInfo.year += 1; } else { tickInfo[x] = undefined; } } } return tickInfo; } export function getNextTickTime(tickInfo: DateTime, date?: Date): number { date = date || new Date(); var seconds = tickInfo.seconds !== undefined ? tickInfo.seconds : date.getSeconds(), minutes = tickInfo.minutes !== undefined ? tickInfo.minutes : date.getMinutes(), hours = tickInfo.hours !== undefined ? tickInfo.hours : date.getHours(), month = tickInfo.month !== undefined ? tickInfo.month : date.getMonth() + 1, year = tickInfo.year !== undefined ? tickInfo.year : date.getFullYear(), _date: number; if (tickInfo.date !== undefined) { // use monthly date as the first choice _date = tickInfo.date; } else if (tickInfo.day !== undefined) { // if missing date, use weekday instead if (tickInfo.day >= date.getDay()) { _date = tickInfo.day - date.getDay() + date.getDate(); } else { _date = tickInfo.day - date.getDay() + 7 + date.getDate(); } } else { _date = date.getDate(); } var { seconds, minutes, hours, date: _date, month, year } = correctDates({ seconds, minutes, hours, date: _date, month, year }, date); return new Date(year, month - 1, _date, hours, minutes, seconds).getTime(); } function getCurrentTick(): DateTime { let date = new Date(); return { year: date.getFullYear(), day: date.getDay(), month: date.getMonth() + 1, date: date.getDate(), hours: date.getHours(), minutes: date.getMinutes(), seconds: date.getSeconds() } } /** * The possible returning values is: * -1: tick is expired; * 0: tick is just on time; * 1: tick is still awaiting. */ export function getTicKState(dateInfo: DateTimeLike, tickInfo: DateTime): number { let currentTick = getCurrentTick(), waitNextTick = false, state = 1; for (let x of Props) { if (!waitNextTick && isWildcard(dateInfo[x])) waitNextTick = true; if (tickInfo[x] === undefined) { continue; } else if (tickInfo[x] === currentTick[x]) { state = 0; } else if (tickInfo[x] > currentTick[x]) { state = 1; break; } else { // tickInfo[x] < currentTick[x] state = waitNextTick ? 1 : -1; break; } } return state; } export function getBestTimeout(tickInfo: DateTime, date?: Date): number { let timeout = getNextTickTime(tickInfo, date) - (date ? date.getTime() : Date.now()); return timeout > TimeoutLimit ? TimeoutLimit : timeout; } export function getBestInterval(tickInfo: DateTime): number { let timeouts = { seconds: 1000, minutes: 1000 * 60, hours: 1000 * 60 * 60, date: 1000 * 60 * 60 * 24, }; for (let x in timeouts) { if (tickInfo[x] !== undefined) return timeouts[x]; } return timeouts.date; } export function shouldRunOnce(dateInfo: DateTimeLike): boolean { let should = true; for (let x in dateInfo) { if (isWildcard(dateInfo[x])) { should = false break; } } return should; }
Hyurl/sfn-schedule-parser
src/index.ts
<reponame>Hyurl/sfn-schedule-parser<filename>src/index.ts import assign = require("lodash/assign"); import { DateTimeLike, DateTime } from "./types"; import { parseDateString, parseDateStatement } from "./parser"; import { shouldRunOnce, getNextTick, getTicKState, getBestInterval, getBestTimeout } from "./util"; export class ScheduleInfo implements DateTimeLike { year?: string | number; day?: string | number; month?: string | number; date?: string | number; hours?: string | number; minutes?: string | number; seconds?: string | number; /** Whether the schedule should run only once. */ readonly once: boolean; readonly pattern: string; private nextTick: DateTime; constructor(pattern: string) { let date = new Date; assign(this, parseDateString(pattern), parseDateStatement(pattern, date)); this.pattern = pattern; this.once = shouldRunOnce(this); this.nextTick = getNextTick(this, date); if (this.getState() === -1) throw new RangeError("Schedule pattern is already expired."); } /** * - `-1` expired, the schedule should stop now. * - `0` in position, the schedule should run now; * - `1` waiting, the schedule should wait for the next tick. */ getState() { let state = getTicKState(this, this.nextTick); if (state === 0) this.nextTick = getNextTick(this); return state; } getBestTimeout() { return getBestTimeout(this.nextTick); } getBestInterval() { return getBestInterval(this.nextTick); } } export function parse(pattern: string) { return new ScheduleInfo(pattern); } export default parse;
Hyurl/sfn-schedule-parser
src/parser.ts
import trimRight = require("lodash/trimEnd"); import { DateTimeLike } from "./types"; import { Weekdays2, Months, Beginnings, Endings, Weekdays } from "./consts"; import { ucfirst, isWildcard } from "./util"; function getNum(str: string): string | number { if (str === undefined) { return undefined; } else if (isWildcard(str)) { return str; } else { let num = parseInt(str); return isNaN(num) ? -1 : num; } } function setDateInfo(dateInfo: DateTimeLike, prop: string, val: string | number) { if (typeof val == "number") { dateInfo[prop] = (val >= Beginnings[prop] && val <= Endings[prop]) ? val : undefined; } else if (isWildcard(val)) { dateInfo[prop] = val; } } export function parseDateString(pattern: string): DateTimeLike { let parts = pattern.split(/\s+/), endings = ["st", "nd", "rd", "th"], // e.g. 1st, 2nd, 3rd 4th dateInfo: DateTimeLike = {}; for (let part of parts) { let nums: string[], isDate: boolean = false, isTime: boolean = false; if (part.indexOf(":") > 0) { // match H:i:s nums = part.split(":"); isTime = true; } else if (part.indexOf("-") > 0) { // match Y-m-d or m-d-Y nums = part.split("-"); isDate = true; } if (isDate || isTime) { let num1 = getNum(nums[0]); let num2 = getNum(nums[1]); let num3 = getNum(nums[2]); if (isDate) { if (typeof num3 === "number" && num3 > 31 || num3 === -1) { // m-d-Y setDateInfo(dateInfo, "year", num3); setDateInfo(dateInfo, "month", num1); setDateInfo(dateInfo, "date", num2); } else { // Y-m-d if (num1 !== undefined) setDateInfo(dateInfo, "year", num1); if (num2 !== undefined) setDateInfo(dateInfo, "month", num2); if (num3 !== undefined) setDateInfo(dateInfo, "date", num3); } } else { if (num1 !== undefined) setDateInfo(dateInfo, "hours", num1); if (num2 !== undefined) setDateInfo(dateInfo, "minutes", num2); if (num3 !== undefined) setDateInfo(dateInfo, "seconds", num3); } } else { let _part = trimRight(part, "."); // e.g. Mon. => Mon let i = Weekdays2.indexOf(_part); if (i >= 0) { dateInfo.day = i; continue; } i = Months.indexOf(_part); if (i >= 0) { dateInfo.month = i; continue; } let ending = part.substring(part.length - 2); let isNum = !isNaN(<any>part); if (endings.indexOf(ending) >= 0 || (isNum && part.length == 2)) { // match date let num = parseInt(part) || -1; if (dateInfo.date === undefined && num >= 1 && num <= 31) dateInfo.date = num; } else if (isNum) { // match year let num = parseInt(part) || -1; if (dateInfo.year === undefined && num >= 1970) dateInfo.year = num; } } } return dateInfo; } export function parseDateStatement(pattern: string, date?: Date): DateTimeLike { date = date || new Date; let re1 = /(every|on)\s+([a-z]+)/i, re2 = /(every|in|after)\s+(this|next|\d+)\s+([a-z]+)|(this|next)\s+([a-z]+)/i, re3 = /the\s+([a-z]+)\s+after\s+(.+)|today|tomorrow/i, matches1: RegExpMatchArray = null, matches2: RegExpMatchArray = null, matches3: RegExpMatchArray = null, dateInfo: DateTimeLike = {}; while (pattern.length > 0) { if (matches1 = pattern.match(re1)) { // on week day pattern = pattern.replace(matches1[0], ""); if (matches1[1] == "on") { let day = matches1[2], index = Weekdays.indexOf(day); if (index >= 0 && !("day" in dateInfo)) dateInfo.day = index; } else { let unit = matches1[2]; switch (unit) { case "second": // every second case "minute": // every minute case "hour": // every hour case "day": // every day let prop = unit == "day" ? "date" : unit + "s"; if (!(prop in dateInfo)) dateInfo[prop] = "*"; break; case "week": //every week // starts from the current week day if (!("day" in dateInfo)) dateInfo.day = date.getDay(); if (!("month" in dateInfo)) dateInfo.month = "*"; break; case "month": // every month if (!("month" in dateInfo)) dateInfo.month = "*"; break; default: // try to match weekdays, e.g. every Monday let index = Weekdays.indexOf(unit); if (index >= 0) { if (!("day" in dateInfo)) dateInfo.day = index; if (!("month" in dateInfo)) dateInfo.month = "*"; } break; } } } else if (matches2 = pattern.match(re2)) { pattern = pattern.replace(matches2[0], ""); let prep = matches2[1], num: string | number = prep ? matches2[2] : matches2[4], unit = prep ? matches2[3] : matches2[5]; if (prep) { // statement with preposition 'in' or 'every' if (num == "this") num = prep == "in" ? 0 : 1; else if (num == "next") num = prep == "in" ? 1 : 2; else num = parseInt(num) + (prep == "in" || prep == "every" ? 0 : 1); } else { if (num == "this") num = 0; else num = 1; } if (unit[unit.length - 1] == "s") unit = unit.substring(0, unit.length - 1); switch (unit) { case "second": case "minute": case "hour": case "day": let prop = unit == "day" ? "date" : unit + "s", method = "get" + ucfirst(prop); if (!(prop in dateInfo)) { if (prep == "every") dateInfo[prop] = num == 1 ? "*" : "*/" + num else dateInfo[prop] = date[method]() + num; } break; case "week": // when parsing week, set date instead if (!("date" in dateInfo)) { if (prep == "every") dateInfo.date = "*/" + (num * 7); else dateInfo.date = date.getDate() + (7 * num); } break; case "month": if (!("month" in dateInfo)) { if (prep == "every") dateInfo.month = num == 1 ? "*" : "*/" + num; else dateInfo.month = date.getMonth() + 1 + num; } break; default: let index = Weekdays.indexOf(unit); if (index >= 0) { if (num == 0 && !("day" in dateInfo)) dateInfo.day = date.getDay(); else if (num == 1 && !("date" in dateInfo)) // set date instead dateInfo.date = 7 - index + date.getDate(); } break; } } else if (matches3 = pattern.match(re3)) { pattern = pattern.replace(matches3[0], ""); if (matches3[0] == "today" && !("date" in dateInfo)) { dateInfo.date = date.getDate(); } else if (matches3[0] == "tomorrow" && !("date" in dateInfo)) { dateInfo.date = date.getDate() + 1; } else { let unit = matches3[1], str = matches3[2], getNum = (matches: RegExpMatchArray): number => { if (matches[1] == "this" || matches[0] == "today") return 1; else if (matches[1] == "next" || matches[0] == "tomorrow") return 2; else return parseInt(matches[1]); }; if (unit == "day") { let matches = str.match(/(\d+)\s+day[s]|today|tomorrow/); if (matches && !("date" in dateInfo)) dateInfo.date = date.getDate() + getNum(matches); } else if (unit == "week" || unit == "month") { let re = new RegExp("(this|next\\d+)\\s+" + unit + "[s]"), matches = str.match(re); if (matches) { if (unit == "week") { if (!("date" in dateInfo)) dateInfo.date = date.getDate() + (getNum(matches) * 7); } else { if (!("month" in dateInfo)) dateInfo.month = date.getMonth() + 1 + getNum(matches); } } } } } else { break; } } return dateInfo; }
Hyurl/sfn-schedule-parser
src/consts.ts
import { DateTime } from "./types"; export const Months = [ undefined, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec" ]; export const BigMonths = [1, 3, 5, 7, 8, 10, 12]; export const Weekdays = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; export const Weekdays2 = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]; export const Beginnings: DateTime = { year: 1970, day: 1, month: 1, date: 1, hours: 0, minutes: 0, seconds: 0 }; export const Endings: DateTime = { year: 9999, day: 7, month: 12, date: 31, hours: 23, minutes: 59, seconds: 59 }; export const Props = Object.keys(Beginnings); export const ReversedProps = Object.keys(Beginnings).reverse(); export const TimeoutLimit = Math.pow(2, 31) - 1;
Hyurl/sfn-schedule-parser
src/types.ts
<filename>src/types.ts export interface DateTimeLike { /** 2018+. */ year?: string | number; /** Day of week, `0` - `6`, `0` represents Sunday. */ day?: string | number; /** `1` - `12`. */ month?: string | number; /** Day of month, `1` - `31`. */ date?: string | number; /** `0` - `23`. */ hours?: string | number; /** `0` - `59`. */ minutes?: string | number; /** `0` - `59`. */ seconds?: string | number; } export interface DateTime extends DateTimeLike { year?: number; day?: number; month?: number; date?: number; hours?: number; minutes?: number; seconds?: number; };
akito0107/favalid
src/__tests__/utils.test.ts
import * as assert from "power-assert"; import { hasError, isBlank } from "../util"; describe("isBlank", () => { test("expected true when got null", () => { const actual = isBlank(null); assert.equal(actual, true); }); test("expected true when got undefined", () => { const actual = isBlank(undefined); assert.equal(actual, true); }); test("expected true when got []", () => { const actual = isBlank([]); assert.equal(actual, true); }); test("expected true when got ''", () => { const actual = isBlank(""); assert.equal(actual, true); }); test("expected true when got {}", () => { const actual = isBlank({}); assert.equal(actual, true); }); test("expected false when got 0", () => { const actual = isBlank(0); assert.equal(actual, false); }); test("expected false when got [1]", () => { const actual = isBlank([1]); assert.equal(actual, false); }); test("expected false when got 'hoge'", () => { const actual = isBlank("hoge"); assert.equal(actual, false); }); test("expected false when got { length: 1 }", () => { const actual = isBlank({ length: 1 }); assert.equal(actual, false); }); test("expected false when got { valueOf: null }", () => { const actual = isBlank({ valueOf: null }); assert.equal(actual, false); }); }); describe("hasError", () => { [ { in: { error: true, message: "some" }, out: true }, { in: { error: false, message: "" }, out: false }, { in: { prop1: { error: false, message: "" }, prop2: { error: true, message: "test" } }, out: true }, { in: { prop1: { error: false, message: "" }, prop2: { error: false, message: "" }, prop3: { prop4: { prop5: { error: true, message: "" } } } }, out: true }, { in: { prop1: { error: false, message: "" }, prop2: { error: false, message: "" }, prop3: { prop4: { prop5: { error: false, message: "" } } } }, out: false } ].forEach(c => { assert.equal(hasError(c.in), c.out); }); });
akito0107/favalid
src/util.ts
<gh_stars>10-100 import { SchemaValidationResult, ValidationResult } from "./core"; const isNil = (arg: any): boolean => arg === null || arg === undefined; const isEmpty = (arg: any): boolean => { switch (typeof arg) { case "string": return arg === ""; case "object": // refs: https://github.com/ramda/ramda/blob/f494250c0a/source/isEmpty.js#L20-L25 if (arg === null) { return false; } if (Array.isArray(arg)) { return arg.length === 0; } return arg.constructor === Object && Object.keys(arg).length === 0; default: return false; } }; export const strlen = (str: string) => [...str].length; export const isBlank = (s: any) => { return isNil(s) || isEmpty(s); }; export const isString = (str: string) => typeof str === "string"; export const hasError = ( res: SchemaValidationResult<object> | ValidationResult ): boolean => { const result: any = res; if (result.hasOwnProperty("error")) { return result.error; } const schemaResult: SchemaValidationResult<object> = res; return Object.keys(schemaResult).reduce((p, k) => { return p || hasError(schemaResult[k]); }, false); };
akito0107/favalid
src/main.ts
<reponame>akito0107/favalid export { tester, combine, combineWithReducer } from "./core"; export { asyncCombine, asyncCombineWithReducer, asyncTester, toAsync } from "./async"; export { default as required } from "./validators/required"; export { default as max } from "./validators/numbers.max"; export { default as min } from "./validators/numbers.min"; export { default as integer } from "./validators/numbers.integer"; export { default as lessThan } from "./validators/numbers.lessThan"; export { default as moreThan } from "./validators/numbers.moreThan"; export { default as positive } from "./validators/numbers.positive"; export { default as negative } from "./validators/numbers.negative"; export { default as regexp } from "./validators/strings.regexp"; export { default as maxLength } from "./validators/strings.maxLength"; export { default as minLength } from "./validators/strings.minLength"; export { default as minDate } from "./validators/date.min"; export { default as maxDate } from "./validators/date.max"; export { shape, safeShape } from "./schema"; export { default as conditional } from "./conditional";
akito0107/favalid
src/__tests__/conditional.test.ts
<filename>src/__tests__/conditional.test.ts import * as assert from "power-assert"; import { combine, tester } from "../core"; import { conditional, maxLength, minLength, required } from "../main"; import { isString } from "../util"; describe("conditional", () => { test("stop early", () => { const prerequiments = tester( () => false, () => "stop" ); const dummy = tester( () => { assert.fail("unreachable"); return false; }, () => "" ); assert.deepStrictEqual(conditional(prerequiments, dummy)(""), { error: true, message: "stop", preconditionCheckFailed: true }); }); test("pass requirements", () => { const prerequiments = tester( () => true, () => "" ); const dummy = tester( () => { return true; }, () => "validate fail" ); assert.deepStrictEqual(conditional(prerequiments, dummy)(""), { error: false, message: "" }); }); test("combine and conditional", () => { const precondition = combine( required(() => "required"), tester( str => isString(str), () => "must be string" ) ); const validator = combine( minLength(5, () => "min 5 length"), maxLength(10, () => "max 10 length") ); const conditionalCheckedValidator = conditional(precondition, validator); [ { in: null, except: { error: true, message: "required", preconditionCheckFailed: true } }, { in: 123, except: { error: true, message: "must be string", preconditionCheckFailed: true } }, { in: "1234", except: { error: true, message: "min 5 length" } }, { in: "12345678910", except: { error: true, message: "max 10 length" } }, { in: "123456789", except: { error: false, message: "" } } ].forEach(c => { assert.deepStrictEqual(conditionalCheckedValidator(c.in), c.except); }); }); });
akito0107/favalid
src/validators/date.min.ts
<reponame>akito0107/favalid import { Messager, tester, ValueValidator } from "../core"; export default (date: Date, messager: Messager): ValueValidator => { return tester((v: Date) => { return date < v; }, messager); };
akito0107/favalid
src/schema.ts
<gh_stars>10-100 import { default as conditional } from "./conditional"; import { Messager, SchemaValidationResult, SchemaValidator } from "./core"; import required from "./validators/required"; export const shape = <T extends object>(obj: T): SchemaValidator<T> => { return (o: object) => { return Object.keys(obj).reduce((prev, k) => { const validator = obj[k]; if (validator) { prev[k] = validator(o[k]); } return prev; }, {}) as SchemaValidationResult<T>; }; }; const defaultBlankErrorMessager = () => "blank"; export const safeShape = <T extends object>( obj: T, requiredMessager: Messager = defaultBlankErrorMessager ): SchemaValidator<T> => { return conditional(required(requiredMessager), shape(obj)) as SchemaValidator< T >; };
akito0107/favalid
src/validators/required.ts
<reponame>akito0107/favalid<gh_stars>10-100 import { Messager, tester, ValueValidator } from "../core"; import { isBlank, isString } from "../util"; export default (messager: Messager): ValueValidator => { return tester(v => { if (isString(v)) { v = v.trim(); } return !isBlank(v); }, messager); };
akito0107/favalid
src/conditional.ts
<filename>src/conditional.ts import { Validator } from "./core"; import { hasError } from "./util"; export default (requirements: Validator, main: Validator): Validator => { return <T>(...args: T[]) => { const precondition = requirements(...args); if (hasError(precondition)) { return { ...precondition, preconditionCheckFailed: true }; } return main(...args); }; };
akito0107/favalid
src/__tests__/async.test.ts
import { asyncCombine, asyncCombineWithReducer, asyncTester, toAsync } from "../async"; import { defaultReducer, tester } from "../core"; import { asyncHelper } from "../validators/__tests__/helper"; describe("async", () => { test("basic", async () => { await asyncHelper( asyncTester( () => { return Promise.resolve(true); }, () => "" ), null, { error: false, message: "" } ); }); test("should be invalid", async () => { await asyncHelper( asyncTester( () => { return Promise.resolve(false); }, () => "error" ), null, { error: true, message: "error" } ); }); test("fail Promise.resolve", async () => { await asyncHelper( asyncTester( () => { return Promise.reject(new Error("message")); }, () => "error" ), null, { error: true, message: "error" } ); }); test("with async function", async () => { await asyncHelper( asyncTester( async () => { return true; }, () => "" ), null, { error: false, message: "" } ); }); }); describe("asyncCombine (with Reducer)", () => { test("combine multiple asyncTesters", async () => { const tester1 = asyncTester( () => Promise.resolve(true), () => "test3" ); const tester2 = asyncTester( () => Promise.resolve(true), () => "test3" ); await asyncHelper( asyncCombineWithReducer(defaultReducer, tester1, tester2), null, { error: false, message: "" } ); }); test("reports first failed test", async () => { const tester1 = asyncTester( () => Promise.resolve(true), () => "test1" ); const tester2 = asyncTester( () => Promise.reject(new Error("error")), () => "test2" ); const tester3 = asyncTester( () => Promise.resolve(true), () => "test3" ); await asyncHelper( asyncCombineWithReducer(defaultReducer, tester1, tester2, tester3), null, { error: true, message: "test2" } ); }); }); describe("asyncCombine", () => { test("combine multiple asyncTesters", async () => { const tester1 = asyncTester( () => Promise.resolve(true), () => "test1" ); const tester2 = asyncTester( () => Promise.reject(new Error("error")), () => "test2" ); const tester3 = asyncTester( () => Promise.resolve(true), () => "test3" ); await asyncHelper(asyncCombine(tester1, tester2, tester3), null, { error: true, message: "test2" }); }); }); describe("convertToAsync", () => { test("convert to asyncTeter", async () => { const tester1 = asyncTester( () => Promise.resolve(true), () => "" ); const tester2 = tester( () => false, () => "test2" ); const tester3 = tester( () => true, () => "" ); await asyncHelper( asyncCombine(tester1, toAsync(tester2), toAsync(tester3)), null, { error: true, message: "test2" } ); }); });
akito0107/favalid
src/examples/email.ts
<filename>src/examples/email.ts import { combine, combineWithReducer, maxLength, minLength, regexp, required } from "../main"; import { isBlank } from "../util"; const REQUIRED_EMAIL_MESSAGE = () => "required."; const EMAIL_REGEXP = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i; const REGEXP_MESSAGE = () => "invalid email."; const EMAIL_MAX_LENGTH = 100; const MAX_LENGTH_MESSAGE = () => "exceeds 100 letters."; const EMAIL_MIN_LENGTH = 10; const MIN_LENGTH_MESSAGE = () => "at least 10 letters."; export const emailValidator = (email: string) => { return combine( required(REQUIRED_EMAIL_MESSAGE), minLength(EMAIL_MIN_LENGTH, MIN_LENGTH_MESSAGE), maxLength(EMAIL_MAX_LENGTH, MAX_LENGTH_MESSAGE), regexp(EMAIL_REGEXP, REGEXP_MESSAGE, {}) )(email); }; export const emailValidatorWithReducer = (email: string) => { const reducer = (prevError, currentError) => { const error = prevError.error || currentError.error; let message = prevError.message; if (currentError.error) { message = isBlank(message) ? currentError.message : message + " / " + currentError.message; } return { error, message }; }; return combineWithReducer( [ required(REQUIRED_EMAIL_MESSAGE), minLength(EMAIL_MIN_LENGTH, MIN_LENGTH_MESSAGE), maxLength(EMAIL_MAX_LENGTH, MAX_LENGTH_MESSAGE), regexp(EMAIL_REGEXP, REGEXP_MESSAGE, {}) ], reducer, { error: false, message: "" } )(email); }; export const emailValidatorWithMultipleErrorReducer = (email: string) => { const reducer = (prevError, currentError) => { if (currentError.error) { prevError.push(currentError); } return prevError; }; return combineWithReducer( [ required(REQUIRED_EMAIL_MESSAGE), minLength(EMAIL_MIN_LENGTH, MIN_LENGTH_MESSAGE), maxLength(EMAIL_MAX_LENGTH, MAX_LENGTH_MESSAGE), regexp(EMAIL_REGEXP, REGEXP_MESSAGE, {}) ], reducer, [] )(email); };
akito0107/favalid
src/__tests__/schema.test.ts
import * as assert from "power-assert"; import { combine, tester } from "../core"; import { emailValidator } from "../examples/email"; import { conditional, maxLength, minLength, required, safeShape } from "../main"; import { shape } from "../schema"; import { isString } from "../util"; describe("schema", () => { test("no error", () => { const validator = shape({ value: tester( () => false, () => "test" ) }); assert.deepStrictEqual(validator({ value: true }), { value: { error: true, message: "test" } }); }); test("multiple row", () => { const validator = shape({ bar: tester( () => true, () => "bar" ), foo: tester( () => false, () => "foo" ) }); assert.deepStrictEqual(validator({ foo: true, bar: true }), { bar: { error: false, message: "" }, foo: { error: true, message: "foo" } }); }); test("combined validator", () => { const validator = shape({ email: emailValidator, password: combine( minLength(10, () => "at least 10 letters."), maxLength(16, () => "maximum: 16 letters.") ) }); [ { in: { email: "<EMAIL>", password: "<PASSWORD>" }, out: { email: { error: false, message: "" }, password: { error: false, message: "" } } }, { in: { email: "<EMAIL>", password: "<PASSWORD>" }, out: { email: { error: true, message: "invalid email." }, password: { error: true, message: "at least 10 letters." } } }, { in: { email: "<EMAIL>", password: "<PASSWORD>", unknownprop: "unknown" }, out: { email: { error: true, message: "invalid email." }, password: { error: true, message: "at least 10 letters." } } } ].forEach(c => { assert.deepStrictEqual(validator(c.in), c.out); }); }); test("with conditional", () => { const nameValidator = combine( minLength(5, () => "at least 10 letters."), maxLength(16, () => "maximum: 16 letters.") ); const stringRequired = combine( required(() => "required"), tester( str => isString(str), () => "must be string" ) ); const validator = shape({ email: conditional(stringRequired, emailValidator), name: conditional( required(() => "required"), shape({ first: conditional(stringRequired, nameValidator), last: conditional(stringRequired, nameValidator) }) ) }); [ { in: { email: "", name: { first: "", last: "" } }, out: { email: { error: true, message: "required", preconditionCheckFailed: true }, name: { first: { error: true, message: "required", preconditionCheckFailed: true }, last: { error: true, message: "required", preconditionCheckFailed: true } } } }, { in: { email: null, name: { first: 123, last: undefined } }, out: { email: { error: true, message: "required", preconditionCheckFailed: true }, name: { first: { error: true, message: "must be string", preconditionCheckFailed: true }, last: { error: true, message: "required", preconditionCheckFailed: true } } } }, { in: { name: { first: "123456", last: "123456" } }, out: { email: { error: true, message: "required", preconditionCheckFailed: true }, name: { first: { error: false, message: "" }, last: { error: false, message: "" } } } }, { in: {}, out: { email: { error: true, message: "required", preconditionCheckFailed: true }, name: { error: true, message: "required", preconditionCheckFailed: true } } } ].forEach(c => { assert.deepStrictEqual(validator(c.in), c.out); }); }); test("ultra nested case with safeShape", () => { const nameValidator = combine( minLength(5, () => "at least 10 letters."), maxLength(16, () => "maximum: 16 letters.") ); const stringRequired = combine( required(() => "required"), tester( str => isString(str), () => "must be string" ) ); const validator = safeShape({ name: safeShape({ nameBrother: nameValidator, nameChild: safeShape({ nameGrandChild: safeShape({ first: conditional(stringRequired, nameValidator) }) }) }) }); [ { in: { name: { nameBrother: "123456", nameChild: { nameGrandChild: { first: "123456" } } } }, out: { name: { nameBrother: { error: false, message: "" }, nameChild: { nameGrandChild: { first: { error: false, message: "" } } } } } }, { in: { name: { nameBrother: "123456", nameChild: { nameGrandChild: {} // treat as a blank } } }, out: { name: { nameBrother: { error: false, message: "" }, nameChild: { nameGrandChild: { error: true, message: "blank", preconditionCheckFailed: true } } } } }, { in: { name: { nameBrother: "123456", nameChild: {} } }, out: { name: { nameBrother: { error: false, message: "" }, nameChild: { error: true, message: "blank", preconditionCheckFailed: true } } } }, { in: { name: {} }, out: { name: { error: true, message: "blank", preconditionCheckFailed: true } } } ].forEach(c => { assert.deepStrictEqual(validator(c.in), c.out); }); }); });
akito0107/favalid
src/core.ts
export type Test = (...v: any[]) => boolean; export type AsyncTest = (...v: any[]) => Promise<boolean>; export type SchemaValidator<T extends object> = ( v?: any ) => SchemaValidationResult<T>; export type ValueValidator = (...v: any[]) => ValidationResult; export type Validator = ValueValidator | SchemaValidator<object>; export type AsyncValidator = (...v: any[]) => Promise<ValidationResult>; export type Messager = (v?: any, a?: any[]) => string; export type Tester = (t: Test, m: Messager) => ValueValidator; export type AsyncTester = (t: AsyncTest, m: Messager) => AsyncValidator; export type ResultReducer = (p: any, e: ValidationResult) => any; export type SchemaValidationResult<T extends object> = { [P in keyof T]: T[P] extends object ? SchemaValidationResult<T[P]> : ValidationResult; }; export type ValidationResult = { error: boolean; message: any; preconditionCheckFailed?: boolean; }; export const tester: Tester = (test, messager) => (...args) => { if (!test(...args)) { return { error: true, message: messager(...args) }; } return { error: false, message: "" }; }; export const combineWithReducer: ( t: ValueValidator[], r: ResultReducer, i: any ) => (...as: any[]) => ValidationResult = ( validators, reducer, initialValue = { error: false, message: "" } ) => (...args) => { return validators.reduce((m, validator) => { return reducer(m, validator(...args)); }, initialValue); }; export const defaultReducer: ResultReducer = (m, e) => { if (m.error) { return m; } return e; }; export const combine: ( ...t: ValueValidator[] ) => (...args: any[]) => ValidationResult = (...tests: ValueValidator[]) => ( ...args: any[] ) => { return combineWithReducer(tests, defaultReducer, { error: false, message: "" })(...args); };
wwwwelton/nodejs-gobarber-gostack11
src/shared/container/providers/CacheProvider/models/ICacheProvider.ts
<gh_stars>10-100 import ICacheProviderDTO from '../dtos/ICacheProviderDTO'; export default interface ICacheProvider { save(data: ICacheProviderDTO): Promise<void>; recover<T>(key: string): Promise<T | null>; invalidate(key: string): Promise<void>; invalidatePrefix(prefix: string): Promise<void>; }
swimly/rollup-template
src/components/index.ts
<filename>src/components/index.ts export default 'ddd'
roblav96/register-futon-media
src/plugins/HotFlash.ts
<filename>src/plugins/HotFlash.ts import { PluginFunction } from 'vue' export const HotFlash = { install: function(Vue) { if (process.env.NODE_ENV == 'production') return module.hot.removeStatusHandler(HotFlash.statusHandler) module.hot.addStatusHandler(HotFlash.statusHandler) } as PluginFunction<never>, statusHandler: function(status) { if (status == 'check') { document.body.classList.add('hidden') } if (status == 'idle') { setTimeout(() => document.body.classList.remove('hidden'), 0) } } as Parameters<typeof module.hot.addStatusHandler>[0], } export default HotFlash
roblav96/register-futon-media
src/vm.ts
<gh_stars>0 import { Vue, Component } from 'vue-property-decorator' import router from './router' import App from './App.vue' @Component({ router, render: h => h(App) }) class Vm extends Vue { created() { console.log(`created`) router.onReady(route => { this.$mount('#app') }) } mounted() { console.log(`mounted`) } } const vm = new Vm() export default vm if (process.env.NODE_ENV == 'development') { Object.assign(window, { vm }) }
roblav96/register-futon-media
src/main.ts
// import 'dts-generate' import '@ibm/plex/css/ibm-plex.css' import '@mdi/font/css/materialdesignicons.css' import './styles/variables.scss' // import 'tailwindcss/base.css' import 'tailwindcss/utilities.css' import Vue from 'vue' Vue.config.productionTip = false Vue.config.performance = false Vue.config.devtools = false import Buefy from 'buefy' Buefy.install(Vue, { defaultDialogCancelText: 'Cancel', defaultDialogConfirmText: 'Confirm', defaultIconPack: 'mdi', defaultInputAutocomplete: 'off', defaultSnackbarDuration: 5000, defaultToastDuration: 5000, defaultTooltipType: 'is-dark', }) import HotFlash from './plugins/HotFlash' Vue.use(HotFlash) import VHelpers from './plugins/VHelpers' Vue.use(VHelpers) import './vm'
roblav96/register-futon-media
src/router.ts
<gh_stars>0 import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) export default new VueRouter({ mode: 'history', base: process.env.BASE_URL, linkActiveClass: 'is-active', routes: [ { path: '*', redirect: { name: 'home' } }, { path: '/', name: 'home', component: () => import('./views/Home.vue'), }, { path: '/signup', name: 'signup', component: () => import('./views/SignUp.vue'), }, { path: '/quickstart', name: 'quickstart', component: () => import('./views/QuickStart.vue'), }, { path: '/relay', name: 'relay', component: () => import('./views/Relay.vue'), }, ], }) declare module 'vue-router/types/router' { interface VueRouter { onReady(cb: (route: Partial<Route>) => void | Promise<void>): void } }
roblav96/register-futon-media
types/vue.d.ts
import Vue, { VueConstructor, DirectiveOptions } from 'vue' declare module 'vue/types/vue' { interface VueConstructor { prototype: Vue } } declare module 'vue/types/options' { interface DirectiveOptions { [key: string]: any } } declare module 'vue/types/vnode' { interface VNodeDirective { rawName: string def: DirectiveOptions } }
roblav96/register-futon-media
src/plugins/VHelpers.ts
import Vue, { PluginFunction } from 'vue' import * as _ from 'lodash' export const VHelpers = { install: function(Vue) { Object.defineProperty(Vue.prototype, '$vm', { get(this: Vue) { return this.$root }, configurable: false, enumerable: false, }) Vue.prototype.$_ = _ Vue.prototype.$log = console.log Vue.prototype.$development = process.env.NODE_ENV == 'development' Vue.prototype.$production = process.env.NODE_ENV == 'production' } as PluginFunction<never>, } export default VHelpers declare module 'vue/types/vue' { interface Vue { $vm: this $_: typeof _ $log: typeof console.log $development: boolean $production: boolean } }
tojurnru/poe-guild-application-scanner
src/api/github.ts
import axios from 'axios'; import parse = require('csv-parse/lib/sync'); import { axiosErrorHandler } from './errorHandler'; export type Blacklist = { account_name: string; discord_id: string; blacklisted_on: string; reason: string; active: string; }; export const fetchBlacklist = async (): Promise<Blacklist[]> => { try { const url = `https://raw.githubusercontent.com/The-Forbidden-Trove/ForbiddenTroveBlacklist/main/blacklist.csv`; const response = await axios.get(url); const blacklists = parse(response.data, { columns: true, ltrim: true, rtrim: true, }); const normalizedBlacklists = blacklists.map((blacklist: Blacklist) => { blacklist.account_name = blacklist.account_name.toLowerCase(); return blacklist; }); return normalizedBlacklists; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export default { fetchBlacklist };
tojurnru/poe-guild-application-scanner
src/api/pathofexile.ts
<filename>src/api/pathofexile.ts import axios from 'axios'; import cheerio from 'cheerio'; import { axiosErrorHandler } from './errorHandler'; export type Profile = { status: string; guild?: string; joined?: string; lastVisit?: string; achievement?: string; }; export type Characters = { name: string; league: string; classId: number; ascendancyClass: number; class: string; level: number; experience: number; }; // user agent is required to call pathofexile.com api const headers = { 'User-Agent': 'tojurnru:poe-guild-application-scanner-bot', }; export const fetchCharacters = async ( accountName: string, ): Promise<Characters[]> => { try { const url = `https://www.pathofexile.com/character-window/get-characters?accountName=${accountName}`; const response = await axios.get(url, { headers }); return response.data as Characters[]; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; const getStatus = ($: cheerio.Root): string => { const notFoundStr = $('.layoutBoxContent .strip-heading') .first() .text() .trim(); if (notFoundStr === 'Profile Not Found') { return 'Not Found'; } const bannedStr = $('.roleLabel.banned').first().text().trim(); if (bannedStr === 'Banned') { return 'Banned'; } const privateStr = $('.container-content p').first().text().trim(); const privateStrKeyword = 'This profile tab has been set to private, or you lack the permissions to view it.'; if (privateStr === privateStrKeyword) { return 'Private'; } return 'Public'; }; export const fetchProfile = async (accountName: string): Promise<Profile> => { try { const url = `https://www.pathofexile.com/account/view-profile/${accountName}`; const response = await axios.get(url, { headers }); const $ = cheerio.load(response.data); // get status const status = getStatus($); if (status !== 'Public') { return { status }; } // get joined and last visit const box = $('.profile-box.profile').first(); const rawText = box.text(); const guildKeyword = 'Guild:'; const guildIndex = rawText.indexOf(guildKeyword); const postKeyword = 'Forum Posts:'; const postIndex = rawText.indexOf(postKeyword); const joinKeyword = 'Joined:'; const joinIndex = rawText.indexOf(joinKeyword); const visitKeyword = 'Last Visited:'; const visitIndex = rawText.indexOf(visitKeyword); const guildStart = guildIndex + guildKeyword.length; const guildLength = postIndex - guildStart; const joinStart = joinIndex + joinKeyword.length; const joinLength = visitIndex - joinStart; const visitStart = visitIndex + visitKeyword.length; const guild = rawText.substr(guildStart, guildLength).trim(); const joined = rawText.substr(joinStart, joinLength).trim(); const lastVisit = rawText.substr(visitStart).trim(); // get achievements const box2 = $('.profile-box.achievements'); const rawText2 = box2.text(); const achieveKeyword = 'Achievements completed:'; const achieveIndex = rawText2.indexOf(achieveKeyword); const achieveStart = achieveIndex + achieveKeyword.length; const achievement = rawText2.substr(achieveStart).trim(); return { status, guild, joined, lastVisit, achievement, }; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export default { fetchCharacters };
tojurnru/poe-guild-application-scanner
src/controllers/blacklist.ts
<reponame>tojurnru/poe-guild-application-scanner import path from 'path'; import moment from 'moment'; import logger from './logger'; import { Blacklist, fetchBlacklist } from '../api/github'; const filename = path.basename(__filename); let blacklists: Blacklist[] = []; let createdAt: Date; export const getBlacklists = async (): Promise<Blacklist[]> => { // get local blacklist if we have record in the past 30 minutes const threshold = moment().subtract(30, 'minutes'); if (createdAt && threshold.isBefore(createdAt)) { return blacklists; } // get blacklist from github blacklists = await fetchBlacklist(); createdAt = new Date(); logger.debug(`${filename} | get blacklist from github`); return blacklists; };
tojurnru/poe-guild-application-scanner
src/api/discord.ts
<gh_stars>0 import axios from 'axios'; import { Message as DiscordMessage, Channel as DiscordChannel, } from 'discord.js'; import { axiosErrorHandler } from './errorHandler'; const { DISCORD_BOT_TOKEN = '' } = process.env; const headers = { Authorization: `Bot ${DISCORD_BOT_TOKEN}`, 'Content-Type': 'application/json', }; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export const postMessage = async ( channelId: string, message: string, ): Promise<DiscordMessage> => { try { const url = `https://discord.com/api/channels/${channelId}/messages`; const body = { content: message }; const config = { headers }; const response = await axios.post(url, body, config); await delay(1000); // prevent rate limit error return response.data as DiscordMessage; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export const postRawMessage = async (channelId: string, object: any): Promise<DiscordMessage> => { try { const url = `https://discord.com/api/channels/${channelId}/messages`; const config = { headers }; const response = await axios.post(url, object, config); await delay(1000); // prevent rate limit error return response.data as DiscordMessage; } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export const postNewThread = async ( channelId: string, messageId: string, channelName: string, message1: string, message2: string, ): Promise<void> => { try { // create new thread const url = `https://discord.com/api/channels/${channelId}/messages/${messageId}/threads`; const body = { name: channelName }; const config = { headers }; const response = await axios.post(url, body, config); await delay(1000); // prevent rate limit error // post message const threadChannel = response.data as DiscordChannel; await postMessage(threadChannel.id, message1); await delay(1000); await postMessage(threadChannel.id, message2); await delay(1000); } catch (error) { if (axios.isAxiosError(error)) axiosErrorHandler(error); throw error; } }; export default { postMessage };
tojurnru/poe-guild-application-scanner
src/parser/parseOutput.ts
import { Message as DiscordMessage } from 'discord.js'; import { Result } from './parseMessage'; export const parseOutput = async ( result: Result, message: DiscordMessage, ): Promise<string> => { const { discordId, accountName, characterName, poeProfile, charactersCount, characters95to100, blacklist, } = result; const discordTag = discordId ? `<@${discordId}>` : `<@${message.author.id}>`; let output = ''; output += `${discordTag}\n`; output += `Account Name: \`${accountName}\`\n`; output += `Character Name: \`${characterName}\`\n`; output += `POE Account Status: \`${poeProfile.status}\`\n`; if (poeProfile.status === 'Public') { output += ` Joined: \`${poeProfile.joined}\`\n`; // output += ` Last Visited: \`${poeProfile.lastVisit}\`\n`; output += ` Achievements: \`${poeProfile.achievement}\`\n`; output += ` Total Characters: \`${charactersCount} (${characters95to100} above Level 95)\`\n`; } output += ` Link: <https://www.pathofexile.com/account/view-profile/${result.accountName}>\n`; if (!blacklist) { output += `TFT Blacklist: No\n`; // output += ` Check Reputation At <https://discord.gg/F9E5v79P74>\n `; // output += ` Use Command: \`!v @${message.author.tag}\`\n`; } else { output += `TFT Blacklist: **YES**\n`; output += ` Account Name: \`${blacklist.account_name}\`\n`; output += ` Discord ID: \`${blacklist.discord_id}\`\n`; output += ` Reason: \`${blacklist.reason}\`\n`; output += ` Blacklisted On: \`${blacklist.blacklisted_on}\`\n`; } return output; };
tojurnru/poe-guild-application-scanner
src/parser/parseEmbed.ts
import { Message as DiscordMessage } from 'discord.js'; import { Result } from './parseMessage'; export const parseEmbed = async ( result: Result, message: DiscordMessage, ): Promise<any> => { const { discordId, accountName, characterName, poeProfile, charactersCount, characters80to94, characters95to100, blacklist, } = result; const discordTag = discordId ? `<@${discordId}>` : `<@${message.author.id}>`; const createdTimestamp = message.author.createdTimestamp; const createdTime = Math.floor(createdTimestamp / 1000); let fields = [ { "name": "Discord ID \u200B", "value": discordTag, "inline": true }, { "name": "Account Name \u200B", "value": `\`${accountName}\``, "inline": true }, { "name": "Character Name \u200B", "value": `\`${characterName}\``, "inline": true }, { "name": "Current Guild", "value": `\`${poeProfile.guild}\``, "inline": true }, { "name": "Joined", "value": poeProfile.joined, "inline": true }, { "name": "Achievements", "value": poeProfile.achievement, "inline": true }, { "name": "Total Characters", "value": charactersCount, "inline": true }, { "name": "Level 80-94", "value": characters80to94, "inline": true }, { "name": "Level 95-100", "value": characters95to100, "inline": true }, { "name": "Discord Created Date", "value": `<t:${createdTime}:D>`, "inline": true } ]; if (!blacklist) { fields = fields.concat({ "name": "TFT Blacklist", "value": "No", "inline": true }, { "name": "\u200B", "value": "\u200B", "inline": true }); } else { fields = fields.concat({ "name": "TFT Blacklist", "value": "**🚨 YES 🚨**", "inline": true }, { "name": "Blacklisted On", "value": blacklist.blacklisted_on, "inline": true }, { "name": "Reason", "value": blacklist.reason, "inline": true }); } return { // "channel_id": "123456", "content": "", "tts": false, "embeds": [ { "type": "rich", "title": "POE Profile", "description": "", "color": 0x0077DD, fields, "url": `https://www.pathofexile.com/account/view-profile/${accountName}` } ], /* "components": [ { "type": 1, "components": [ { "custom_id": "row_0_select_0", "placeholder": "verdict (not implemented yet)", "options": [ { "label": "Accept", "value": "accept", "emoji": { "id": null, "name": "✅" }, "default": false }, { "label": "Reject", "value": "reject", "emoji": { "id": null, "name": "❌" }, "default": false } ], "min_values": 1, "max_values": 1, "type": 3 } ] } ], */ }; };
tojurnru/poe-guild-application-scanner
src/api/errorHandler.ts
import { AxiosError, AxiosResponse } from 'axios'; import logger from '../controllers/logger'; export const axiosErrorHandler = (error: AxiosError) => { const response = error.response as AxiosResponse; const dataStr = JSON.stringify(response.data, null, 2); logger.error(`Axios Request: ${response.config.url}`); logger.error(`Axios Response ${response.status}, Data: ${dataStr}`); };
tojurnru/poe-guild-application-scanner
src/parser/parseMessage.ts
import path from 'path'; import { Message as DiscordMessage } from 'discord.js'; import { Blacklist } from '../api/github'; import { Profile as PoeProfile, fetchCharacters, fetchProfile, } from '../api/pathofexile'; import { getBlacklists } from '../controllers/blacklist'; import logger from '../controllers/logger'; import ApplicationError from '../error/applicationError'; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const filename = path.basename(__filename); export type Result = { discordId: string; accountName: string; characterName: string; poeProfile: PoeProfile; charactersCount: number; characters80to94: number; characters95to100: number; blacklist?: Blacklist; }; type PoeCharacter = { name: string; level: number; }; export const parseMessage = async ( message: DiscordMessage, ): Promise<Result> => { const { content, author } = message; let discordId = ''; let accountName = ''; let characterName = ''; // extract account name const lines = content.split('\n'); for (const line of lines) { const lineLowercase = line.trim().toLowerCase(); const words = line.trim().split(/ |:/); const value = words[words.length - 1] || ''; if (lineLowercase.match(/account.*name.*:/)) { accountName = value; } else if (lineLowercase.match(/character.*name.*:/)) { characterName = value; } else if (lineLowercase.match(/discord.*id.*:/)) { discordId = value; } } logger.debug(`Account Name: ${accountName}`); if (accountName === '') { const errMessage = 'Account Name not found. Make sure it is written in a single line (Example: `Account Name: your-account-name`).'; throw new ApplicationError(errMessage); } // get poe profile logger.debug(`${filename} | fetching poe profile`); const poeProfile = await fetchProfile(accountName); if (poeProfile.status !== 'Public') { throw new ApplicationError( `Account is ${poeProfile.status}. (<https://www.pathofexile.com/account/view-profile/${accountName}>)`, ); } // get poe characters logger.debug(`${filename} | fetching poe characters`); await delay(5000); // 5 seconds delay before calling pathofexile.com again let characters: PoeCharacter[] = []; try { characters = await fetchCharacters(accountName); } catch (err) { if (err.response && err.response.status === 403) { const errMessage = `Account Character Page is not Public. (<https://www.pathofexile.com/account/view-profile/${accountName}/characters>).`; throw new ApplicationError(errMessage); } else { throw err; } } const charNameLowercase = characterName.toLowerCase(); const charFound = characters.find( (char) => char.name.toLowerCase() === charNameLowercase, ); if (!charFound) { // characterName += ' (Not Found)'; let errMessage = 'Character Name not found. Make sure it is written in a single line '; errMessage += '(Example: `Character Name: your-character-name`), and it exist in your POE Account Character Page.'; throw new ApplicationError(errMessage); } const charactersCount = characters.length; const characters80to94 = characters.filter( (char) => char.level >= 80 && char.level <= 94, ).length; const characters95to100 = characters.filter( (char) => char.level >= 95, ).length; // check if account under blacklist const blacklists = await getBlacklists(); const accountNameLowercase = accountName.toLowerCase(); const found = blacklists.filter((blacklist: Blacklist) => { const { account_name, discord_id } = blacklist; return account_name === accountNameLowercase || discord_id === author.id; }); const blacklist = found.length > 0 ? found[0] : undefined; // return result return { discordId, accountName, characterName, poeProfile, charactersCount, characters80to94, characters95to100, blacklist, }; };
tojurnru/poe-guild-application-scanner
src/parser/parseApplicationError.ts
<reponame>tojurnru/poe-guild-application-scanner import { Message as DiscordMessage } from 'discord.js'; import { postMessage } from '../api/discord'; import logger from '../controllers/logger'; import ApplicationError from '../error/applicationError'; const { DISCORD_CHANNEL_OUTPUT = '' } = process.env; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export const parseApplicationError = async (err: ApplicationError, message: DiscordMessage): Promise<void> => { logger.error(`APPLICATION ERROR FOUND: ${err.message}`); // DM user let directMsg = `Your application post is deleted due to the following reason:\n`; directMsg += `**${err.message}**\n\n`; directMsg += `You are always welcomed to re-apply again once the above issue is resolved.\n\n`; directMsg += `Your Original Message:\n`; await message.author.send(directMsg); await delay(1000); const originalMessage = message.content.substr(0, 2000 - 8); await message.author.send('```\n' + originalMessage + '\n```'); await delay(1000); await message.delete(); await delay(1000); // Log const logMsg = `<@${message.author.id}>'s application deleted because: **${err.message}**`; await postMessage(DISCORD_CHANNEL_OUTPUT, logMsg); };
tojurnru/poe-guild-application-scanner
src/processor.ts
import discordClient from './controllers/discord'; const { DISCORD_BOT_TOKEN } = process.env; const run = async () => { // login into discord and start streaming await discordClient.login(DISCORD_BOT_TOKEN); }; run();
tojurnru/poe-guild-application-scanner
src/controllers/message.ts
import path from 'path'; import { Message as DiscordMessage } from 'discord.js'; import { parseMessage } from '../parser/parseMessage'; // import { parseOutput } from '../parser/parseOutput'; import { parseEmbed } from '../parser/parseEmbed'; import { parseThreadMessage1, parseThreadMessage2, } from '../parser/parseThreadMessage'; import { parseApplicationError } from '../parser/parseApplicationError'; // import { postMessage, postRawMessage, postNewThread } from '../api/discord'; import { postRawMessage, postNewThread } from '../api/discord'; import ApplicationError from '../error/applicationError'; import logger from './logger'; const { DISCORD_CHANNEL_INPUT = '', DISCORD_CHANNEL_OUTPUT = '', DISCORD_WHITELIST_IDS = '', } = process.env; const whitelists = DISCORD_WHITELIST_IDS.split(','); const filename = path.basename(__filename); const shouldParseMessage = (message: DiscordMessage): boolean => { // only process input channels if (message.channelId !== DISCORD_CHANNEL_INPUT) { return false; } if (whitelists.includes(message.author.id)) { return false; } return true; }; export const handleMessage = async (message: DiscordMessage): Promise<void> => { if (!shouldParseMessage(message)) { return; } logger.debug(`${filename} |\n${message.content}`); try { const result = await parseMessage(message); // post message // const output = await parseOutput(result, message); // const newMessage = await postMessage(DISCORD_CHANNEL_OUTPUT, output); const output = await parseEmbed(result, message); const newMessage = await postRawMessage(DISCORD_CHANNEL_OUTPUT, output); // prepare thread message const threadMessage1 = await parseThreadMessage1(result, message); const threadMessage2 = await parseThreadMessage2(result, message); // create thread and post thread message await postNewThread( DISCORD_CHANNEL_OUTPUT, newMessage.id, result.accountName, threadMessage1, threadMessage2, ); logger.debug(`${filename} | Message Processed #${message.id}.`); } catch (err) { if (err instanceof ApplicationError) { await parseApplicationError(err, message); } else { throw err; } } };
tojurnru/poe-guild-application-scanner
src/parser/parseThreadMessage.ts
import { Message as DiscordMessage } from 'discord.js'; import { Result } from './parseMessage'; export const parseThreadMessage1 = async ( result: Result, message: DiscordMessage, ): Promise<string> => { const discordId = result.discordId ? result.discordId : message.author.id; const discordTag = result.discordId ? '-' : message.author.tag; return `<@${discordId}> | ${discordId} | ${discordTag}`; }; export const parseThreadMessage2 = async ( result: Result, message: DiscordMessage, ): Promise<string> => { // const { guildId, channelId, id } = message; // output += `<https://discord.com/channels/${guildId}/${channelId}/${id}>\n`; // const prefix = 'Original Message:\n'; return message.content.substr(0, 2000); };
tojurnru/poe-guild-application-scanner
src/controllers/logger.ts
<reponame>tojurnru/poe-guild-application-scanner import winston from 'winston'; const { LOG_LEVEL = 'info' } = process.env; const { printf, combine, timestamp } = winston.format; const formatter = printf(({ level, message, timestamp }) => { return `${timestamp} | ${level} | ${message}`; }); export default winston.createLogger({ level: LOG_LEVEL, format: combine(timestamp(), formatter), transports: [new winston.transports.Console()], });
tojurnru/poe-guild-application-scanner
src/controllers/discord.ts
<gh_stars>0 import path from 'path'; import { Client, Intents } from 'discord.js'; import logger from './logger'; import { handleMessage } from './message'; const filename = path.basename(__filename); const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES], }); client .on('ready', () => { logger.info(`logged in as ${client.user?.tag}`); }) .on('debug', (info) => { logger.silly(`${filename} | debug: ${info}`); }) .on('messageCreate', handleMessage) .on('error', (err) => { logger.error(`${filename} | ${err}`); logger.error(err); }); export default client;
ShockTr/rustlabs
src/getItemList.ts
import fetch from "node-fetch"; import cheerio from "cheerio"; export async function getItemList() : Promise<GenericItem[]> { let res = await fetch("https://rustlabs.com/group=itemlist") let html = await res.text() const $ = cheerio.load(html) let items: GenericItem[] = [] $(".info-block").children("a").each((i,el) => { const name = $(el).text() const url = `https://rustlabs.com${$(el).attr("href")}` const logo = `https:${$(el).find("img").attr("src").replace("items40", "items180")}` const category = $(el).prevAll("h2").first().text() items.push({ name, url, logo, category }) }) return items } export interface GenericItem { name: string url: string logo: string category: string }
ShockTr/rustlabs
src/index.ts
export {getItemList} from "./getItemList";
ZANJIAHAO1008/Admin-Frame-vue3-template
src/common/event.ts
// event.js import { onMounted, onUnmounted } from "vue"; export function useEventListener(target: any, event: any, callback: any) { // 如果你想的话, // 也可以用字符串形式的 CSS 选择器来寻找目标 DOM 元素 onMounted(() => target.addEventListener(event, callback)); onUnmounted(() => target.removeEventListener(event, callback)); }
ZANJIAHAO1008/Admin-Frame-vue3-template
src/pinia/modules/tag.ts
<reponame>ZANJIAHAO1008/Admin-Frame-vue3-template<gh_stars>1-10 import { defineStore } from "pinia"; import { Tag } from "@/types/layout"; interface State { tagsList: Tag[]; MAX_TAG_LENGTH: number; collapse: boolean; BLACK_LIST: string[]; } export const useTagStore = defineStore({ id: "tag_974813758", // id必填,且需要唯 persist: { enabled: true, // 开启数据缓存 }, state: (): State => { return { tagsList: [], //tag标签存储 MAX_TAG_LENGTH: 10, //标签最大显示长度 collapse: false, //侧边栏展开关闭 BLACK_LIST: [ //无需保存的黑名单 "/login", "/global/abnormal/404", "/global/abnormal/403", "/global/abnormal/build", "/global/abnormal/networkError", ], }; }, actions: { setTags<T extends Tag>(tag: T) { //选中在tagsList添加菜单 this.tagsList.push(tag); }, delTags<T extends { index: number }>({ index }: T) { //如果标签到10个再选择就将最初的删除 this.tagsList.splice(index, 1); }, delRightMenu<T extends { WHITE_TAGS_LIST: string[] }>({ WHITE_TAGS_LIST, }: T) { //关闭tag的右菜单 const tagList: Tag[] = []; this.tagsList.forEach((tags, index) => { if (WHITE_TAGS_LIST?.includes(tags.path)) { tagList.push(tags); } }); this.tagsList = [...tagList]; }, // 侧边栏折叠 switchCollapse(state: boolean) { this.collapse = state; }, }, });
ZANJIAHAO1008/Admin-Frame-vue3-template
src/assets/js/dictionarie.ts
export const FONT_SIZE = [ //字体大小设置 { value: "large", label: "大的按钮", }, { value: "default", label: "标准按钮", }, { value: "small", label: "小的按钮", }, ];
ZANJIAHAO1008/Admin-Frame-vue3-template
src/utils/index.ts
import { ElLoading } from "element-plus"; import { unref } from "vue"; import config from "../../package.json"; export const debounce = (function () { //防重复提交 let timer = 0; return function (callback: Function, ms: number) { clearTimeout(timer); timer = setTimeout(callback, ms); } })(); export function Loading() { //loading方法 return ElLoading.service({ lock: false, text: "加载中···", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", }); } export function getValues<T extends object, K extends keyof T>( obj: T, key: K ): T[K] { //获取value值 return obj[key]; } export function toObtainAnalyticalData<T>(target: T): T { //多层proxy解析 return JSON.parse(JSON.stringify(unref(target))); }; export function getImage(url: string, type: string) { return new URL(`../assets/image/${url}.${type}`, import.meta.url).href; } export const printVersion = (name: string, version: string) => { console.log( `%c ${name} %c V${version} `, "padding: 5px 5px; border-radius: 3px 0 0 3px; color: #fff; background: #909399; font-weight: bold;", "padding: 5px 5px; border-radius: 0 3px 3px 0; color: #fff; background: #409EFF; font-weight: bold;" ); console.log(config.description); console.log("%c希望世界和平." + "\n" + "Peace & Love.", "color: #40a9ff;"); console.log(`%c项目地址:${config.url}`, "color: red;"); } printVersion(config.name, config.version);
ZANJIAHAO1008/Admin-Frame-vue3-template
vite.config.ts
import { defineConfig } from "vite"; import vue from "@vitejs/plugin-vue"; import * as path from "path"; import { viteMockServe } from "vite-plugin-mock"; import viteCompression from "vite-plugin-compression"; import AutoImport from "unplugin-auto-import/vite"; import Components from "unplugin-vue-components/vite"; import { ElementPlusResolver } from "unplugin-vue-components/resolvers"; import { createStyleImportPlugin, ElementPlusResolve, } from "vite-plugin-style-import"; import VueSetupExtend from "vite-plugin-vue-setup-extend"; import ElementPlus from "unplugin-element-plus/vite"; export default defineConfig({ base: "./", //打包路径 plugins: [ vue({ // refTransform: true //开启ref转换 使用$ref }), // ElementPlus({ // useSource: true, // }), VueSetupExtend(), //jiejue setup无法添加name问题 // gzip压缩 生产环境生成 .gz 文件 viteCompression({ verbose: true, disable: false, threshold: 10240, algorithm: "gzip", ext: ".gz", }), AutoImport({ imports: ["vue", "vue-router"], }), viteMockServe({ //Mock服务自动注册 mockPath: "./src/mock", localEnabled: true, prodEnabled: true }), // Components({ //自动注册组件 // dts:true, // resolvers: [ElementPlusResolver( // { // importStyle:'sass' // } // )], // }), // createStyleImportPlugin({ //自动导入框架样式 // resolves: [ // ElementPlusResolve(), // ], // // 自定义规则 // libs: [ // { // libraryName: 'element-plus', // esModule: true, // resolveStyle: (name) => { // return `element-plus/lib/theme-chalk/${name}.css` // } // } // ] // }) ], // 配置别名 resolve: { alias: { "@": path.resolve(__dirname, "src"), }, extensions: [".js", ".ts", ".json", ".vue"], //导入文件省略后缀 }, //启动服务配置 server: { open: true, https: false, strictPort: true, port: 3001, proxy: { // 选项写法 // "/api": { // target: "http://172.16.17.32:8002/", // changeOrigin: true, // rewrite: (path) => path.replace(/^\/api/, ""), // }, // // 正则表达式写法 // "^/fallback/.*": { // target: "http://jsonplaceholder.typicode.com", // changeOrigin: true, // rewrite: (path) => path.replace(/^\/fallback/, ""), // }, // // 使用 proxy 实例 // "/api1": { // target: "http://jsonplaceholder.typicode.com", // changeOrigin: true, // configure: (proxy, options) => { // // proxy 是 'http-proxy' 的实例 // }, // }, }, }, //css全局预处理器 css: { preprocessorOptions: { scss: { additionalData: '@use "@/assets/style/main.scss" as *;', }, }, postcss: { plugins: [ // 移除打包element时的@charset警告 { postcssPlugin: "internal:charset-removal", AtRule: { charset: (atRule) => { if (atRule.name === "charset") { atRule.remove(); } }, }, }, ], }, }, // 生产环境打包配置 //去除 console debugger // build: { // terserOptions: { // compress: { // drop_console: true, // drop_debugger: true, // }, // }, // }, });
ZANJIAHAO1008/Admin-Frame-vue3-template
src/common/mouse.ts
<filename>src/common/mouse.ts // mouse.js import { ref } from "vue"; import { useEventListener } from "./event"; export function useMouse() { const x = ref<string | number>(0); const y = ref<string | number>(0); interface Event { pageX: string | number; pageY: string | number; } useEventListener(window, "mousemove", (e: Event) => { x.value = e.pageX; y.value = e.pageY; }) return { x, y }; }
ZANJIAHAO1008/Admin-Frame-vue3-template
src/main.ts
import { createApp } from "vue"; import App from "./App.vue"; import router from "@/router"; import pinia from "@/pinia"; import "@/assets/css/font-awesome.min.css"; //font 样式 import "animate.css/animate.min.css"; import "default-passive-events"; import "vue-global-api"; //自动引入vue插件 import { loadAllPlugins } from "@/plugins"; const app = createApp(App); // 加载所有插件 loadAllPlugins(app); app.use(router); app.use(pinia); app.mount("#app");
ZANJIAHAO1008/Admin-Frame-vue3-template
src/common/watermark.ts
<reponame>ZANJIAHAO1008/Admin-Frame-vue3-template const id = "1.234523841642.1234124163"; const setWatermark = (str: string) => { if (document.getElementById(id) !== null) { document.body.removeChild(document.getElementById(id) as HTMLElement); } // 创建一个画布 const canvas = document.createElement("canvas"); // 设置画布的长宽 canvas.width = 220; canvas.height = 180; const ctx = canvas.getContext("2d") as CanvasRenderingContext2D; // 设置旋转角度 ctx.rotate((-20 * Math.PI) / 150); ctx.font = "15px Vedana"; // 设置填充绘画的颜色、渐变或者模式 ctx.fillStyle = "rgba(200, 200, 200, 0.70)"; // 设置文本内容的当前对齐方式 ctx.textAlign = "center"; // 设置在绘制文本时使用的当前文本基线 ctx.textBaseline = "middle"; // 在画布上绘制填色的文本(输出的文本,开始绘制文本的X坐标位置,开始绘制文本的Y坐标位置) ctx.fillText(str, canvas.width / 3, canvas.height / 2); const div = document.createElement("div"); div.id = id; div.style.pointerEvents = "none"; div.style.top = "40px"; div.style.left = "0px"; div.style.opacity = "0.6"; div.style.position = "fixed"; div.style.zIndex = "100000"; div.style.width = document.documentElement.clientWidth + "px"; div.style.height = document.documentElement.clientHeight + "px"; div.style.background = "url(" + canvas.toDataURL("image/png") + ") left top repeat"; document.body.appendChild(div); return id; } // 该方法只允许调用一次 // 添加水印的方法 export const setWaterMarker = (str: string) => { let id = setWatermark(str); if (document.getElementById(id) === null) { id = setWatermark(str); } }; // 移除水印的方法 export const removeWaterMarker = () => { if (document.getElementById(id) !== null) { const box = document.getElementById(id) as HTMLElement; box?.parentNode?.removeChild(box); } };
ZANJIAHAO1008/Admin-Frame-vue3-template
src/plugins/element.ts
import ElementPlus from "element-plus"; import "element-plus/dist/index.css"; import i18n from "@/locales/i18n"; import Cookies from "js-cookie"; import zhCn from "element-plus/lib/locale/lang/zh-cn"; import en from "element-plus/lib/locale/lang/en"; export default function load(app: any) { app.use(ElementPlus, { locale: Cookies?.get("lang") === "en" ? en : zhCn, size: Cookies.get("size") || "default", // 尺寸设置 }); }
ZANJIAHAO1008/Admin-Frame-vue3-template
src/types/layout.ts
import { RouteLocationNormalized } from "vue-router"; export interface HeaderState<T> { collapse: T; username: T; passVisible: boolean; baseVisible: boolean; versionVisible: boolean; driver: any; } export interface Tag extends RouteLocationNormalized { title?: string; }
ZANJIAHAO1008/Admin-Frame-vue3-template
src/pinia/modules/user.ts
import { defineStore } from "pinia"; import { BaseInfoState } from "@/types/setting"; interface State { user: Partial<BaseInfoState["baseInfoForm"]>; } export const useUserStore = defineStore({ id: "user_974813758", // id必填,且需要唯一 persist: { enabled: true, // 开启数据缓存 }, state: (): State => { return { user: {}, //用户信息 }; }, actions: {}, });
ZANJIAHAO1008/Admin-Frame-vue3-template
components.d.ts
// generated by unplugin-vue-components // We suggest you to commit this file into source control // Read more: https://github.com/vuejs/vue-next/pull/3399 declare module "vue" { export interface GlobalComponents { BaseInfo: typeof import("./src/components/Setting/baseInfo.vue")["default"]; CheckPass: typeof import("./src/components/Setting/checkPass.vue")["default"]; Header: typeof import("./src/components/Header/index.vue")["default"]; Pagination: typeof import("./src/components/Pagination/index.vue")["default"]; SideBar: typeof import("./src/components/SideBar/index.vue")["default"]; Tags: typeof import("./src/components/Tags/index.vue")["default"]; VersionLog: typeof import("./src/components/Setting/versionLog.vue")["default"]; } } export {};
billiramirez/express-server-with-typescript
src/controllers/decorators/controller.ts
import "reflect-metadata"; import { Request, Response, RequestHandler, NextFunction } from "express"; import { AppRouter } from "../../AppRouter"; import { Methods } from "./Methods"; import { MetadataKeys } from "./MetadataKeys"; function bodyValidators(keys: string[]): RequestHandler { return function(req: Request, res: Response, next: NextFunction) { if (!req.body) { res.status(422).send("Invalid Request"); return; } for (let key of keys) { if (!req.body[key]) { res.status(422).send(`Missing property ${key}`); return; } } next(); }; } export function controller(routePrefix: string) { return function(target: Function) { const router = AppRouter.getInstance(); for (let key in target.prototype) { const routeHandler = target.prototype[key]; const path = Reflect.getMetadata( MetadataKeys.path, target.prototype, key ); const method: Methods = Reflect.getMetadata( MetadataKeys.method, target.prototype, key ); const middewares = Reflect.getMetadata(MetadataKeys.middleware, target.prototype, key) || []; const requiredBodyProps = Reflect.getMetadata(MetadataKeys.validator, target.prototype, key) || []; const validator = bodyValidators(requiredBodyProps); if (path) { router[method]( `${routePrefix}${path}`, ...middewares, validator, routeHandler ); } } }; }
billiramirez/express-server-with-typescript
src/index.ts
<gh_stars>0 import express from "express"; import bodyParser from "body-parser"; import cookieSession from "cookie-session"; import { AppRouter } from "./AppRouter"; import "./controllers/LoginController"; import "./controllers/RootController"; const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieSession({ keys: ["asdfjkl"] })); app.use(AppRouter.getInstance()); app.listen(3000, () => { console.log("listening on 3000"); });
jerebtw/Sepa
src/index.ts
<reponame>jerebtw/Sepa<gh_stars>0 import { type DeclarationAttributes, type ElementCompact, js2xml, } from "xml-js"; import { isValidIBAN, isValidBIC } from "ibantools"; //#region Interfaces export interface Options { /** * If the xml should be pretty printed * @default false */ prettyPrint?: boolean; /** * Check if the IBAN is valid. (with IBANTools) * @default true */ checkIBAN?: boolean; /** * Check if the BIC is valid. (with IBANTools) * @default true */ checkBIC?: boolean; } export interface Payment { /** Max length is 35 */ id: string; name: string; iban: string; bic: string; mandateId?: string; mandateSignatureDate?: Date; amount: number; /** Default is "EUR" */ currency?: string; remittanceInformation: string; end2endReference?: string; } export interface CreditorPayments { /** Max length is 35 */ id: string; batchBooking?: boolean; /** When the payment should be executed */ requestedExecutionDate: Date; collectionDate?: Date; name: string; iban: string; bic: string; payments: Payment[]; } export interface SepaData { painVersion?: PAIN_VERSIONS; xmlVersion?: string; xmlEncoding?: string; xsiNamespace?: string; xsiXmls?: string; localInstrumentation?: LOCAL_INSTRUMENTATION; sequenceType?: SEQUENCE_TYPE; batchBooking?: boolean; /** Max length is 35 */ id: string; creationDate: Date; /** Max length is 70 */ initiatorName: string; positions: CreditorPayments[]; } //#endregion //#region enum | type enum PAIN_TYPES { "pain.001.001.02" = "pain.001.001.02", "pain.001.003.02" = "pain.001.003.02", "pain.001.001.03" = "CstmrCdtTrfInitn", "pain.001.003.03" = "CstmrCdtTrfInitn", "pain.008.001.01" = "pain.008.001.01", "pain.008.003.01" = "pain.008.003.01", "pain.008.001.02" = "CstmrDrctDbtInitn", "pain.008.003.02" = "CstmrDrctDbtInitn", } export type PAIN_VERSIONS = | "pain.001.001.02" | "pain.001.003.02" | "pain.001.001.03" | "pain.001.003.03" | "pain.008.001.01" | "pain.008.003.01" | "pain.008.001.02" | "pain.008.003.02"; export type LOCAL_INSTRUMENTATION = "CORE" | "COR1" | "B2B"; export type SEQUENCE_TYPE = "FRST" | "RCUR" | "OOFF" | "FNAL"; //#endregion //#region const const XSI_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; const XSI_XMLS = "urn:iso:std:iso:20022:tech:xsd:"; const PAIN_VERSION = "pain.001.001.03"; const XML_VERSION = "1.0"; const XML_ENCODING = "UTF-8"; //#endregion /** * Generate a SEPA XML file * * If the length of the values is longer than the max length, it will throw an error * or if checkIBAN or checkBIC is true, it will check if the IBAN or BIC is valid and throw an error if it is not */ export function createSepaXML( sepaData: SepaData, options: Options = { prettyPrint: false, checkBIC: true, checkIBAN: true }, ): string { const painFormat = sepaData.painVersion ?? PAIN_VERSION; const painVersion = parseInt( painFormat.substring(painFormat.length, painFormat.length - 2), 10, ) + (painFormat.indexOf("pain.008") === 0 ? 1 : 0); const declaration: { _attributes: DeclarationAttributes } = { _attributes: { version: sepaData.xmlVersion ?? XML_VERSION, encoding: sepaData.xmlEncoding ?? XML_ENCODING, }, }; checkLength(sepaData.id, "sepaData.id", 35); checkLength(sepaData.initiatorName, "sepaData.initiatorName", 70); const Document: ElementCompact = { _attributes: { xmlns: `${sepaData.xsiXmls ?? XSI_XMLS}${painFormat}`, "xmlns:xsi": sepaData.xsiNamespace ?? XSI_NAMESPACE, "xsi:schemaLocation": `${ sepaData.xsiXmls ?? XSI_XMLS }${painFormat} ${painFormat}.xsd`, }, }; Document[PAIN_TYPES[painFormat]] = { GrpHdr: { MsgId: sepaData.id, CreDtTm: sepaData.creationDate.toISOString().substring(0, 19), NbOfTxs: sepaData.positions.reduce( (sum, item) => sum + item.payments.length, 0, ), CtrlSum: sepaData.positions .reduce( (sum, item) => sum + item.payments.reduce((sum, payment) => sum + payment.amount, 0), 0, ) .toFixed(2), InitgPty: { Nm: sepaData.initiatorName, }, }, PmtInf: getPmtInf(sepaData, painFormat, painVersion, options), }; if (painVersion === 2) { Document[PAIN_TYPES[painFormat]].GrpHdr.BtchBookg = ( sepaData.batchBooking ?? false ).toString(); Document[PAIN_TYPES[painFormat]].GrpHdr.Grpg = "MIXD"; } return js2xml( { _declaration: declaration, Document }, { compact: true, spaces: options?.prettyPrint ? 2 : undefined }, ); } function getPmtInf( sepaData: SepaData, painFormat: PAIN_VERSIONS, painVersion: number, options: Options, ) { return sepaData.positions.map((item, index) => { checkLength(item.id, `sepaData.positions[${index}].id`, 35); checkLength(item.name, `sepaData.positions[${index}].name`, 70); if (options?.checkIBAN && !isValidIBAN(item.iban)) { throw new Error( `sepaData.positions[${index}].iban is not valid (${item.iban})`, ); } if (options?.checkBIC && !isValidBIC(item.bic)) { throw new Error( `sepaData.positions[${index}].bic is not valid (${item.bic})`, ); } const pmtMtd = painFormat.indexOf("pain.001") === 0 ? "TRF" : "DD"; const pmtInfData: ElementCompact = { PmtInfId: item.id, PmtMtd: pmtMtd, PmtTpInf: { SvcLvl: { Cd: "SEPA" } }, ChrgBr: "SLEV", }; if (painVersion === 3) { pmtInfData.BtchBookg = (item.batchBooking ?? false).toString(); pmtInfData.NbOfTxs = item.payments.length; pmtInfData.CtrlSum = item.payments .reduce((sum, payment) => sum + payment.amount, 0) .toFixed(2); } if (pmtMtd === "DD") { pmtInfData.PmtTpInf.LclInstrm = { Cd: sepaData.localInstrumentation ?? "", }; pmtInfData.SeqTp = sepaData.sequenceType ?? undefined; pmtInfData.ReqdColltnDt = item.collectionDate ?.toISOString() .substring(0, 10); pmtInfData.Cdtr = { Nm: item.name, }; pmtInfData.CdtrAcct = { Id: { IBAN: item.iban, }, }; pmtInfData.CdtrAgt = { FinInstnId: { BIC: item.bic } }; pmtInfData.CdtrSchmeId = { Id: { PrvtId: { Othr: { Id: item.id ?? "", SchmeNm: { Prtry: "SEPA", }, }, }, }, }; } else { pmtInfData.ReqdExctnDt = item.requestedExecutionDate .toISOString() .substring(0, 10); pmtInfData.Dbtr = { Nm: item.name, }; pmtInfData.DbtrAcct = { Id: { IBAN: item.iban, }, }; pmtInfData.DbtrAgt = { FinInstnId: { BIC: item.bic } }; } pmtInfData.CdtTrfTxInf = getPayments(item.payments, index, pmtMtd); return pmtInfData; }); } function getPayments(payments: Payment[], index: number, pmtMtd: "TRF" | "DD") { return payments.map((payment, paymentIndex) => { checkLength( payment.id, `sepaData.positions[${index}].payments[${paymentIndex}].id (${payment.id})`, 35, ); checkLength( payment.name, `sepaData.positions[${index}].payments[${paymentIndex}].name (${payment.name})`, 35, ); const paymentData: ElementCompact = { PmtId: { InstrId: payment.id, }, RmtInf: { Ustrd: payment.remittanceInformation }, }; if (payment.end2endReference) { paymentData.PmtId.EndToEndId = payment.end2endReference; } if (pmtMtd === "DD") { paymentData.Amt = { _attributes: { Ccy: payment.currency || "EUR" }, InstdAmt: payment.amount.toFixed(2), }; paymentData.DrctDbtTx = { MndtRltdInf: { MndtId: payment.mandateId ?? "", DtOfSgntr: payment.mandateSignatureDate?.toISOString().substring(0, 10) ?? "", }, }; paymentData.DbtrAcct = { Id: { IBAN: payment.iban, }, }; paymentData.DbtrAgt = { FinInstnId: { BIC: payment.bic }, }; paymentData.Dbtr = { Nm: payment.name }; } else { paymentData.Amt = { InstdAmt: { _attributes: { Ccy: payment.currency || "EUR" }, _text: payment.amount.toFixed(2), }, }; paymentData.CdtrAcct = { Id: { IBAN: payment.iban, }, }; paymentData.CdtrAgt = { FinInstnId: { BIC: payment.bic }, }; paymentData.Cdtr = { Nm: payment.name }; } return paymentData; }); } function checkLength(value: string, name: string, length: number) { if (value.length > length) { throw new Error(`Max length for ${name} is ${length} (${value})`); } }
klan1/app.demo
ts-output/db-models.ts
<reponame>klan1/app.demo import { Injectable } from '@angular/core'; @Injectable() export class DiasFestivosModel { IdDiaFestivo: number = null; FechaDiaFestivo: string = null; NombreDiaFestivo: string = null; DiaDeLaSemana: number = null; } export class AmbientesModel { id: number = null; name: string = null; } export class AnimalGrupoLineaPesoModel { peso_id: number = null; fk_linea_id: number = null; peso_genero: string = null; peso_semana: string = null; peso_unidad: string = null; peso_min: number = null; peso_max: number = null; peso_prom: number = null; postura: number = null; consumo: number = null; huevos: number = null; } export class AnimalGruposModel { animal_grupo_id: number = null; grupo_nombre: string = null; fk_animal_id: number = null; estado: number = null; } export class AnimalLineaModel { linea_id: number = null; fk_animal_grupo_id: number = null; fk_animal_id: number = null; linea_nombre: string = null; linea_descripcion: string = null; } export class AnimalesModel { animal_id: number = null; animal_nombre: string = null; animal_descripcion: string = null; estado: number = null; } export class CodCostaricaModel { Provincia: string = null; Canton: string = null; Distrito: string = null; Poblado: string = null; DistritoId: string = null; } export class CodEcuadorModel { cod_prov: string = null; cod_cant: string = null; cod_parro: string = null; nom_pro: string = null; nom_cant: string = null; nom_parro: string = null; } export class CodParaguayModel { cod: number = null; region: string = null; ciudad: string = null; cod_postal: string = null; } export class DepartamentoModel { departamento_id: number = null; fk_pais_id: string = null; departamento_nombre: string = null; } export class EmpresaGranjaGalponesModel { galpone_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; galpon_nombre: string = null; tipo_ambiente: string = null; sistema_produccion: string = null; estado: number = null; } export class EmpresaGranjasModel { granja_id: number = null; fk_empresa_id: number = null; granja_nombre: string = null; estado: number = null; } export class EmpresasModel { empresa_id: number = null; fk_municipio_id: number = null; fk_departamento_id: number = null; fk_pais_id: string = null; nit: string = null; nombre_empresa: string = null; razon_social: string = null; estado: number = null; } export class EstudioGalponIndividiosModel { individio_id: number = null; fk_estudio_galpon_id: number = null; fk_estudio_id: number = null; fk_animal_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; fk_linea_id: number = null; fk_galpone_id: number = null; } export class EstudioGalponResultadosModel { resultado_id: number = null; fk_estudio_galpon_id: number = null; fk_estudio_id: number = null; lote: string = null; fk_animal_id: number = null; fk_empresa_id: number = null; fk_granja_id: number = null; fk_linea_id: number = null; fk_galpone_id: number = null; fk_variable_id: number = null; resultado: string = null; maximo_esperado: number = null; ir: number = null; nivel_afeccion: number = null; porcentaje_afectacion: number = null; calificacion: string = null; index_g: number = null; isag: number = null; } export class EstudioGalponesModel { estudio_galpon_id: number = null; fk_estudio_id: number = null; fk_animal_id: number = null; fk_empresa_id: number = null; fk_granja_id: number = null; fk_linea_id: number = null; fk_galpone_id: number = null; individuos_semanas: number = null; individios_genero: string = null; estudio_galpon_lote: string = null; description: string = null; estado: number = null; postura: number = null; consumo: number = null; huevos: number = null; } export class EstudioIndividioVariableModel { fk_variable_id: number = null; fecha_estudio_individuo: string = null; variable_valor: number = null; fk_individio_id: number = null; fk_estudio_galpon_id: number = null; fk_estudio_id: number = null; fk_animal_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; fk_linea_id: number = null; fk_galpone_id: number = null; individuo_imagen: string = null; estado: number = null; } export class EstudioIpigValoresModel { resultado_ipig_id: number = null; fk_estudio_ipig_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; variable_id: number = null; tipo_variable: string = null; dias: number = null; valor: number = null; calificacion: number = null; } export class EstudiosModel { estudio_id: number = null; fk_animal_id: number = null; fk_empresa_id: number = null; fk_granja_id: number = null; fk_user_id: number = null; estudio_num_animales: number = null; estudios: string = null; fecha_estudio: string = null; } export class EstudiosGrupoVariablesModel { fk_grupo_variable_id: number = null; fk_estudio_id: number = null; } export class EstudiosIpigModel { estudio_ipig_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; fk_user_id: number = null; nombre: string = null; tipo_cria: number = null; tipo_cria_dias: number = null; tipo_levante: number = null; tipo_levante_dias: number = null; tipo_levante_alimento: string = null; tipo_ceba: number = null; tipo_ceba_dias: number = null; tipo_ceba_alimento: string = null; resultado: number = null; resultado_fecha: string = null; } export class EventsModel { id: number = null; event_name: string = null; start_date: string = null; end_date: string = null; fk_empresa_id: number = null; nombre_empresa: string = null; fk_granja_id: number = null; granja_nombre: string = null; fk_galpone_id: number = null; galpon_nombre: string = null; estudio_galpon_lote: string = null; animal_nombre: string = null; linea_nombre: string = null; individios_genero: string = null; estudio_num_animales: number = null; individuos_semanas: number = null; link: string = null; fk_user_id: number = null; email: string = null; nombres: string = null; apellidos: string = null; estudio_tipo: string = null; estudio_completado: string = null; } export class EventsModel { id: number = null; created_at: number = null; updated_at: number = null; event_name: string = null; start_date: string = null; end_date: string = null; link: string = null; } export class EventsUltimosModel { id: number = null; event_name: string = null; start_date: string = null; end_date: string = null; fk_empresa_id: number = null; nombre_empresa: string = null; fk_granja_id: number = null; granja_nombre: string = null; fk_galpone_id: number = null; galpon_nombre: string = null; estudio_galpon_lote: string = null; animal_nombre: string = null; linea_nombre: string = null; individios_genero: string = null; estudio_num_animales: number = null; individuos_semanas: number = null; link: string = null; fk_user_id: number = null; email: string = null; nombres: string = null; apellidos: string = null; estudio_tipo: string = null; estudio_completado: string = null; } export class GrupoVariablesModel { grupo_variable_id: number = null; grupo_nombre: string = null; constante: number = null; } export class MigrationsModel { id: number = null; migration: string = null; batch: number = null; } export class MunicipioModel { municipio_id: number = null; fk_departamento_id: number = null; fk_pais_id: string = null; municipio_nombre: string = null; } export class PaisModel { pais_id: string = null; pais_nombre: string = null; } export class PasswordResetsModel { email: string = null; token: string = null; created_at: number = null; } export class SistemasModel { id: number = null; name: string = null; } export class UsersModel { id: number = null; name: string = null; email: string = null; password: string = null; remember_token: string = null; created_at: number = null; updated_at: number = null; nombres: string = null; apellidos: string = null; cedula: string = null; rol: string = null; type1: number = null; type2: number = null; type3: number = null; type4: number = null; id_empresa: number = null; } export class UsersEmpresasGranjasModel { id: number = null; user_id: number = null; fk_granja_id: number = null; fk_empresa_id: number = null; created_at: number = null; updated_at: number = null; } export class VariablesModel { variable_id: number = null; fk_animal_id: number = null; variables_macro: string = null; variable_nombre: string = null; variable_descripcion: string = null; variable_min: number = null; variable_max: number = null; index_g: number = null; variables_apoyo_visual: string = null; ir_operador: string = null; calificacion_operador: string = null; ir_tolerancia: number = null; calificacion_tolerancia: number = null; variable_max_prog: number = null; calificacion_texto_pos: string = null; calificacion_texto_neg: string = null; operacion_resultado: string = null; con: number = null; } export class VariablesGrupoVariablesModel { fk_variable_id: number = null; fk_animal_id: number = null; fk_grupo_variable_id: number = null; } export class VariablesIpigModel { variable_id: number = null; tipo_variable: string = null; nombre: string = null; } export class ViewEstudiosIpigModel { estudio_ipig_id: number = null; fk_granja_id: number = null; granja_nombre: string = null; fk_empresa_id: number = null; nombre_empresa: string = null; fk_user_id: number = null; nombre: string = null; tipo_cria: number = null; tipo_cria_dias: number = null; tipo_levante: number = null; tipo_levante_dias: number = null; tipo_levante_alimento: string = null; tipo_ceba: number = null; tipo_ceba_dias: number = null; tipo_ceba_alimento: string = null; resultado: number = null; resultado_fecha: string = null; }
JamesAliaga/nest_proyect
src/app.service.ts
<filename>src/app.service.ts import { Injectable } from '@nestjs/common'; @Injectable() export class AppService { getHello(): any { return this.manifestJSON(); } async manifestJSON() { const axios = require("axios"); const response = await axios.get( "https://jsonplaceholder.typicode.com/posts" ); // console.log(response); return response.data; } }
fraxken/move-concurrently2
index.d.ts
declare function rename(from: string, to: string): Promise<void>; export = rename;
Nebulis/blog
src/components/images/asia/japan/tokyo/yasukuni-dori.tsx
<gh_stars>0 import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { yasukuniDoriNight: "Yasukuni-Dori At Night", yasukuniDoriNight2: "Yasukuni-Dori At Night", yasukuniDoriNight3: "Yasukuni-Dori At Night", yasukuniDoriNight4: "Yasukuni-Dori At Night", yasukuniDoriDay: "Yasukuni-Dori At Day", yasukuniDoriDay2: "Yasukuni-Dori At Day", yasukuniDoriDay3: "Yasukuni-Dori At Day", yasukuniDoriDay4: "Yasukuni-Dori At Day", yasukuniDoriDay5: "Yasukuni-Dori At Day", yasukuniDoriDay6: "Yasukuni-Dori At Day", yasukuniDoriDay7: "Yasukuni-Dori At Day", yasukuniDoriDay8: "Yasukuni-Dori At Day", yasukuniDoriDay9: "Yasukuni-Dori At Day", yasukuniDoriDay10: "Yasukuni-Dori At Day", yasukuniDoriDay11: "Yasukuni-Dori At Day", yasukuniDoriDay12: "Yasukuni-Dori At Day", yasukuniDoriDay13: "Yasukuni-Dori At Day", yasukuniDoriDay14: "Yasukuni-Dori At Day", yasukuniDoriDay15: "Yasukuni-Dori At Day", yasukuniDoriDay16: "Yasukuni-Dori At Day", cardFr1: "Yasukuni-Dori Pinterest card", cardFr2: "Yasukuni-Dori Pinterest card", cardEn1: "Yasukuni-Dori Pinterest card", cardEn2: "Yasukuni-Dori Pinterest card", } export const YasukuniDoriImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { yasukuniDoriNight: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-night.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriNight2: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-night2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriNight3: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-night3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriNight4: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-night4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay2: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay3: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay4: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay5: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay6: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay7: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay8: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay9: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay10: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay11: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay12: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day12.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay13: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day13.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay14: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day14.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay15: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day15.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } yasukuniDoriDay16: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/yasukuni-dori-day16.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/japan/tokyo/yasukuni-dori/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
Nebulis/blog
src/components/images/asia/japan/tokyo/ueno-park.tsx
<filename>src/components/images/asia/japan/tokyo/ueno-park.tsx import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { restaurant: "Ueno Park Restaurant", park: "Ueno Park", park2: "Ueno Park", park3: "Ueno Park", park4: "Ueno Park", park5: "Ueno Park", park6: "Ueno Park", park7: "Ueno Park", park8: "Ueno Park", park9: "Ueno Park", park10: "Ueno Park", park11: "Ueno Park", park12: "Ueno Park", park13: "Ueno Park", park14: "Ueno Park", park15: "Ueno Park", park16: "Ueno Park", park17: "Ueno Park", park18: "Ueno Park", cardFr1: "Pinterest Ueno Park Card", cardFr2: "Pinterest Ueno Park Card", cardEn1: "Pinterest Ueno Park Card", cardEn2: "Pinterest Ueno Park Card", } export const UenoParkImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { restaurant: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park-restaurant.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park2: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park3: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park4: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park5: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park6: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 70, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park7: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park8: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park9: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park10: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park11: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park12: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park12.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park13: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park13.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park14: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park14.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park15: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park15.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park16: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park16.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park17: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park17.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } park18: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/ueno-park18.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 70, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 70, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 70, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/japan/tokyo/ueno-park/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 70, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
Nebulis/blog
src/components/layout/menu.context.tsx
<filename>src/components/layout/menu.context.tsx import React, { useEffect, useState } from "react" import { useWindowSize } from "../hooks/useWindowSize" import { pageDesktopHeightWithoutBanner, pageMobileHeightWithoutBanner, pageMobileLandscapeHeightWithoutBanner, } from "../core/variables" export const MenuContext = React.createContext<{ open: boolean setOpen: (open: boolean) => void isMobileView: boolean pageHeight: string }>({ open: false, setOpen: () => void 0, isMobileView: false, pageHeight: pageDesktopHeightWithoutBanner, }) export const MenuProvider: React.FunctionComponent = ({ children }) => { const [open, setOpen] = useState(false) const { windowWidth, scrollbarWidth, mode } = useWindowSize() useEffect(() => { if (open) { document.body.style.overflowY = "hidden" document.body.style.marginRight = `${scrollbarWidth}px` // this to avoid element to move on thr right when hiding the menu } else { document.body.style.overflowY = "scroll" document.body.style.marginRight = "0px" } }, [open, scrollbarWidth]) const isMobileView = windowWidth <= 992 return ( <MenuContext.Provider value={{ open, setOpen, isMobileView, pageHeight: isMobileView ? mode === "portrait" ? pageMobileHeightWithoutBanner : pageMobileLandscapeHeightWithoutBanner : pageDesktopHeightWithoutBanner, }} > {children} </MenuContext.Provider> ) }
Nebulis/blog
src/components/images/asia/japan/himeji/himeji-castle-images.tsx
import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { gyuKaku: "Himeji Castle Gyu Kaku", visit: "Himeji Castle", garden: "Himeji Castle Garden", garden2: "Himeji Castle Garden", garden3: "Himeji Castle Garden", garden4: "Himeji Castle Garden", garden5: "Himeji Castle Garden", garden6: "Himeji Castle Garden", garden7: "Himeji Castle Garden", maze: "Himeji Castle Maze", maze2: "Himeji Castle Maze", maze3: "Himeji Castle Maze", maze4: "Himeji Castle Maze", maze5: "Himeji Castle Maze", maze6: "Himeji Castle Maze", maze7: "Himeji Castle Maze", maze8: "Himeji Castle Maze", maze9: "Himeji Castle Maze", maze10: "Himeji Castle Maze", maze11: "Himeji Castle Maze", maze12: "Himeji Castle Maze", inside: "Himeji Castle Inside", inside2: "Himeji Castle Inside", inside3: "Himeji Castle Inside", inside4: "Himeji Castle Inside", inside5: "Himeji Castle Inside", inside6: "Himeji Castle Inside", inside7: "Himeji Castle Inside", inside8: "Himeji Castle Inside", inside9: "Himeji Castle Inside", inside10: "Himeji Castle Inside", inside11: "Himeji Castle Inside", history: "Himeji Castle", bonus: "Himeji Castle", bonus2: "Himeji Castle", bonus3: "Himeji Castle", bonus4: "Himeji Castle", kokoEn: "Himeji Castle Koko-En Garden", cardFr1: "Himeji Castle Pinterest card", cardFr2: "Himeji Castle Pinterest card", cardEn1: "Himeji Castle Pinterest card", cardEn2: "Himeji Castle Pinterest card", } export const HimejiCastleImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { gyuKaku: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-gyu-kaku.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } visit: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-visit.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } history: file(relativePath: { eq: "asia/japan/home.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden2: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden3: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden4: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden5: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden6: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden7: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-garden7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze2: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze3: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze4: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze5: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze6: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze7: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze8: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze9: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze10: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze11: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } maze12: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-maze12.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside2: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside3: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside4: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside5: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside6: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside7: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside8: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside9: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside10: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } inside11: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-inside11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bonus: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-bonus.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bonus2: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-bonus2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bonus3: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-bonus3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bonus4: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-bonus4.jpg" }) { childImageSharp { fluid(maxWidth: 600, quality: 90, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } kokoEn: file(relativePath: { eq: "asia/japan/himeji/castle/himeji-castle-koko-en.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/japan/himeji/castle/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/japan/himeji/castle/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/japan/himeji/castle/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/japan/himeji/castle/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
Nebulis/blog
src/services/newsletter.ts
export const subscribe = ({ mail }: { mail: string }) => { return fetch("https://us-central1-blog-3dd22.cloudfunctions.net/newsletter", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ mail, }), }).then((res) => { if (!res.ok) { throw new Error("Request failed: " + res.statusText) } }) }
Nebulis/blog
src/pages/asia/malaysia/east-malaysia/weekend-in-kuching.tsx
import React, { useContext } from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/asia/malaysia/east-malaysia/weekend-in-kuching.json" import translationEn from "../../../../locales/en/asia/malaysia/east-malaysia/weekend-in-kuching.json" import { MalaysiaBlogLayout, MalaysiaHeadline } from "../../../../components/core/asia/malaysia/malaysia" import { Baggage, HowLong, HowMuch, Introduction, SectionContent, Visit, WhatTimeOfYear, Where, WhereToStay, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import { Quote } from "../../../../components/core/quote" import { Title } from "../../../../components/core/title" import HomeImgUrl from "../../../../images/asia/malaysia/carousel-malaysia2.jpg" import { ImageAsLandscape, ImageAsPortrait } from "../../../../components/images/layout" import { CarouselImageQuery } from "../../../../components/images/carousel" import { BookingCard, BookingWarning } from "../../../../components/core/booking" import { ArticleCardContainer, BookingGygCardContainer, MapContainer } from "../../../../components/layout/layout" import { BakoNationalParkCard, KubahNightFrogsTourCard, SemenggohNatureReserveCard, } from "../../../../components/core/asia/malaysia/malaysia.cards" import { getLink } from "../../../../components/core/links/links.utils" import { ApplicationContext } from "../../../../components/application" import hiltonHotel from "../../../../images/asia/malaysia/east-malaysia/weekend-in-kuching/hilton-hotel.jpg" import marianHotel from "../../../../images/asia/malaysia/east-malaysia/weekend-in-kuching/marian-hotel.jpg" import novaHotel from "../../../../images/asia/malaysia/east-malaysia/weekend-in-kuching/nova-hotel.jpg" import { WeekendInKuchingImages } from "../../../../components/images/asia/malaysia/east-malaysia/weekend-in-kuching" import WeekendInKuchingMap from "../../../../images/asia/malaysia/east-malaysia/weekend-in-kuching/weekend-in-kuching-map.png" const namespace = "asia/malaysia/east-malaysia/weekend-in-kuching" const id = "weekend-in-kuching" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { development } = useContext(ApplicationContext) const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.malaysia.card.${id}`) const orangutanLinkPublished = development || getLink("orangutan").published return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <MalaysiaBlogLayout page={id} location={location}> <Title title={title} linkId={id} /> <ImageAsLandscape> <CarouselImageQuery image="malaysia2" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction")}</Introduction> <Divider /> <WhatTimeOfYear title={t("what-time-of-year.title")}> <p>{t("what-time-of-year.part1")}</p> <p>{t("what-time-of-year.part2")}</p> <p>{t("what-time-of-year.part3")}</p> </WhatTimeOfYear> <HowLong title={t("how-long.title")}> <p>{t("how-long.part1")}</p> <p>{t("how-long.part2")}</p> <p>{t("how-long.part3")}</p> </HowLong> <HowMuch title={t("how-much.title")}> <p>{t("how-much.part1")}</p> <p>{t("how-much.part2")}</p> <ul> <li>{t("how-much.part3")}</li> <li>{t("how-much.part4")}</li> <li>{t("how-much.part5")}</li> <li>{t("how-much.part6")}</li> </ul> <p>{t("how-much.part7")}</p> </HowMuch> <WhereToStay title={t("where-to-stay.title")}> <p>{t("where-to-stay.part1")}</p> <p>{t("where-to-stay.part2")}</p> <BookingGygCardContainer> <BookingCard hotel="my/nova-kuching" title="Nova Kuching Hotel" image={novaHotel} note="7,7" price={16} people={2} kind="hotel" /> <BookingCard hotel="my/the-marian-boutique-lodging-house" title="The Marian Boutique Lodging House" image={marianHotel} note="8,6" price={25} people={2} kind="hotel" /> <BookingCard hotel="my/hilton-kuching" title="Hilton Kuching Hotel" image={hiltonHotel} note="8,4" price={50} people={2} kind="hotel" /> </BookingGygCardContainer> <BookingWarning>{t("where-to-stay.part3")}</BookingWarning> <p>{t("where-to-stay.part4")}</p> <p>{t("where-to-stay.part5")}</p> </WhereToStay> <Baggage title={t("what-to-bring.title")}> <ul> <li>{t("what-to-bring.part1")}</li> <li>{t("what-to-bring.part2")}</li> <li>{t("what-to-bring.part3")}</li> <li>{t("what-to-bring.part4")}</li> <li>{t("what-to-bring.part5")}</li> <li>{t("what-to-bring.part6")}</li> <li>{t("what-to-bring.part7")}</li> <li>{t("what-to-bring.part8")}</li> <li>{t("what-to-bring.part9")}</li> <li>{t("what-to-bring.part10")}</li> </ul> </Baggage> <Where title={t("itinerary.title")}> <p>{t("itinerary.part1")}</p> <p>{t("itinerary.part2")}</p> <p>{t("itinerary.part3")}</p> <p>{t("itinerary.part4")}</p> <p>{t("itinerary.part5")}</p> <p>{t("itinerary.part6")}</p> <p>{t("itinerary.part7")}</p> </Where> <Visit title={t("visit.title")}> <SectionContent> <p>{t("visit.part1")}</p> <ImageAsLandscape> <WeekendInKuchingImages image="welcome" /> </ImageAsLandscape> <p>{t("visit.part2")}</p> <p>{t("visit.part3")}</p> <p>{t("visit.part4")}</p> <p>{t("visit.part5")}</p> <p>{t("visit.part6")}</p> <p>{t("visit.part7")}</p> <p>{t("visit.part8")}</p> <MapContainer> <img src={WeekendInKuchingMap} alt="Weekend in Kuching Map" /> </MapContainer> </SectionContent> <Divider /> <section> <MalaysiaHeadline>{t("visit.visit1.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p className="i">{t("visit.visit1.part1")}</p> <p>{t("visit.visit1.part2")}</p> <p>{t("visit.visit1.part3")}</p> <p>{t("visit.visit1.part4")}</p> <p>{t("visit.visit1.part5")}</p> <p>{t("visit.visit1.part6")}</p> <p>{t("visit.visit1.part7")}</p> <p>{t("visit.visit1.part8")}</p> <p>{t("visit.visit1.part9")}</p> <ArticleCardContainer> <BakoNationalParkCard card={{ showTags: false, showPublished: false, showMore: true }} /> </ArticleCardContainer> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit.visit2.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p className="i">{t("visit.visit2.part1")}</p> <p>{t("visit.visit2.part2")}</p> <p>{t("visit.visit2.part3")}</p> <p>{t("visit.visit2.part4")}</p> <p>{t("visit.visit2.part5")}</p> <p>{t("visit.visit2.part6")}</p> <ArticleCardContainer> <KubahNightFrogsTourCard card={{ showTags: false, showPublished: false, showMore: true }} /> </ArticleCardContainer> </SectionContent> </section> <Divider /> <section> <MalaysiaHeadline>{t("visit.visit3.title")}</MalaysiaHeadline> <Divider /> <SectionContent> <p className="i">{t("visit.visit3.part1")}</p> <p>{t("visit.visit3.part2")}</p> <p>{t("visit.visit3.part3")}</p> <p>{t("visit.visit3.part4")}</p> <p>{t("visit.visit3.part5")}</p> <p>{t("visit.visit3.part6")}</p> <p>{t("visit.visit3.part7")}</p> <p>{t("visit.visit3.part8")}</p> <ArticleCardContainer> <SemenggohNatureReserveCard card={{ showTags: false, showPublished: false, showMore: true }} /> </ArticleCardContainer> </SectionContent> <Divider /> <SectionContent> <p>{t("visit.visit3.part9")}</p> <p>{t("visit.visit3.part10")}</p> {orangutanLinkPublished && <p>{t("visit.visit3.part11")}</p>} <ImageAsPortrait> <WeekendInKuchingImages image="orangutan" /> </ImageAsPortrait> </SectionContent> </section> </Visit> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [ <WeekendInKuchingImages image="cardFr1" key="cardFr1" />, <WeekendInKuchingImages image="cardFr2" key="cardFr1" />, ] : [ <WeekendInKuchingImages image="cardEn1" key="cardEn1" />, <WeekendInKuchingImages image="cardEn2" key="cardEn1" />, ], }} /> </MalaysiaBlogLayout> </> ) } export default IndexPage
Nebulis/blog
plopfile.ts
<reponame>Nebulis/blog import { NodePlopAPI } from "plop" const uppercase = (text: string) => text.charAt(0).toUpperCase() + text.slice(1) export default function (plop: NodePlopAPI) { // controller generator plop.setGenerator("page", { description: "create new page", prompts: [ { type: "input", name: "pagePath", message: "page path", }, ], actions: [ { type: "add", path: "src/pages/{{pagePath}}.tsx", templateFile: "templates/page.hbs", }, { type: "add", path: "src/locales/fr/{{pagePath}}.json", templateFile: "templates/translation.hbs", }, { type: "add", path: "src/locales/en/{{pagePath}}.json", templateFile: "templates/translation.hbs", }, { type: "add", path: "src/components/images/{{pagePath}}.tsx", templateFile: "templates/image.hbs", }, ], }) plop.setHelper("upPath", function (text: string) { return "../".repeat(text.split("/").length) }) plop.setHelper("upPathImage", function (text: string) { return "../".repeat(text.split("/").length + 1) }) plop.setHelper("getContinent", function (text: string) { return text.split("/")[0] }) plop.setHelper("getCountry", function (text: string) { return text.split("/")[1] }) plop.setHelper("getId", function (text: string) { const parts = text.split("/") return parts[parts.length - 1] }) plop.setHelper("getComponentImageName", function (text: string) { const parts = text.split("/") const unformattedName = parts[parts.length - 1] const nameParts = unformattedName.split("-") return nameParts.map(uppercase).join("") }) // plop.setHelper("getId", function (text: string) { // problem to load cachedLinks // const test = "asia/vietnam/southern-vietnam/discover" // for (const [id, link] of cachedLinks.entries()) { // if (link.url === test) { // return id // } // } // return "TODO" // }) plop.setHelper("uppercase", uppercase) }
Nebulis/blog
src/components/images/asia/philippines/palawan/el-nido-tour-a.tsx
import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { bigLagoon: "El Nido Tour A Big Lagoon", bigLagoon2: "El Nido Tour A Big Lagoon", bigLagoon3: "El Nido Tour A Big Lagoon", bigLagoon4: "El Nido Tour A Big Lagoon", bigLagoon5: "El Nido Tour A Big Lagoon", bigLagoon6: "El Nido Tour A Big Lagoon", secretLagoon: "El Nido Tour A Secret Lagoon", secretLagoon2: "El Nido Tour A Secret Lagoon", secretLagoon3: "El Nido Tour A Secret Lagoon", secretLagoon4: "El Nido Tour A Secret Lagoon", secretLagoon5: "El Nido Tour A Secret Lagoon", secretLagoon6: "El Nido Tour A Secret Lagoon", secretLagoon7: "El Nido Tour A Secret Lagoon", secretLagoon8: "El Nido Tour A Secret Lagoon", secretLagoon9: "El Nido Tour A Secret Lagoon", shimizuIsland: "El Nido Tour A Shimizu Island", shimizuIsland2: "El Nido Tour A Shimizu Island", shimizuIsland3: "El Nido Tour A Shimizu Island", shimizuIsland4: "El Nido Tour A Shimizu Island", payongBeach: "El Nido Tour A Payong Beach", payongBeach2: "El Nido Tour A Payong Beach", payongBeach3: "El Nido Tour A Payong Beach", payongBeach4: "El Nido Tour A Payong Beach", payongBeach5: "El Nido Tour A Payong Beach", sevenCommandoBeach: "El Nido Tour A 7 Commando Beach", sevenCommandoBeach2: "El Nido Tour A 7 Commando Beach", sevenCommandoBeach3: "El Nido Tour A 7 Commando Beach", sevenCommandoBeach4: "El Nido Tour A 7 Commando Beach", sevenCommandoBeach5: "El Nido Tour A 7 Commando Beach", sevenCommandoBeach6: "El Nido Tour A 7 Commando Beach", snorkeling: "El Nido Tour A Snorkeling", snorkeling2: "El Nido Tour A Snorkeling", snorkeling3: "El Nido Tour A Snorkeling", snorkeling4: "El Nido Tour A Snorkeling", snorkeling5: "El Nido Tour A Snorkeling", snorkeling6: "El Nido Tour A Snorkeling", snorkeling7: "El Nido Tour A Snorkeling", snorkeling8: "El Nido Tour A Snorkeling", snorkeling9: "El Nido Tour A Snorkeling", cardFr1: "El Nido Tour A Pinterest card", cardFr2: "El Nido Tour A Pinterest card", cardEn1: "El Nido Tour A Pinterest card", cardEn2: "El Nido Tour A Pinterest card", } export const TourAImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { bigLagoon: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bigLagoon2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bigLagoon3: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bigLagoon4: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bigLagoon5: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } bigLagoon6: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-big-lagoon6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon3: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon4: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon5: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon6: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon7: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon8: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } secretLagoon9: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-secret-lagoon9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } shimizuIsland: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-shimizu-island.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } shimizuIsland2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-shimizu-island2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } shimizuIsland3: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-shimizu-island3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } shimizuIsland4: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-shimizu-island4.jpg" }) { childImageSharp { fluid(maxWidth: 1800, quality: 80, srcSetBreakpoints: [600, 1200]) { ...GatsbyImageSharpFluid } } } payongBeach: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-payong-beach.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } payongBeach2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-payong-beach2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } payongBeach3: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-payong-beach3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } payongBeach4: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-payong-beach4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } payongBeach5: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-payong-beach5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach.jpg" } ) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach2: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach2.jpg" } ) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach3: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach3.jpg" } ) { childImageSharp { fluid(maxWidth: 1800, quality: 90, srcSetBreakpoints: [600, 1200]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach4: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach4.jpg" } ) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach5: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach5.jpg" } ) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } sevenCommandoBeach6: file( relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-seven-commando-beach6.jpg" } ) { childImageSharp { fluid(maxWidth: 1800, quality: 80, srcSetBreakpoints: [600, 1200]) { ...GatsbyImageSharpFluid } } } snorkeling: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling3: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling4: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling5: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling6: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling7: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling8: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } snorkeling9: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/tour-a-snorkeling9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/philippines/palawan/el-nido-tour-a/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 60, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
Nebulis/blog
src/components/core/asia/philippines/philippines.card.tsx
<gh_stars>0 import { Card } from "../../../card" import styled from "@emotion/styled" import { ExtraCardProps } from "../../../../types/shared" import { useCustomTranslation } from "../../../../i18n-hook" import commonFr from "../../../../locales/fr/common.json" import commonEn from "../../../../locales/en/common.json" import { philippinesPrimaryColor } from "./philippines.colors" import React, { FunctionComponent } from "react" import { SharedCardPhilippinesImages } from "../../../images/asia/philippines/shared-card-philippines-images" import { CarouselImageQuery } from "../../../images/carousel" export const PhilippinesCard = styled(Card)` .tags a { color: ${philippinesPrimaryColor}; } .tags a:hover { border-bottom: 1px solid ${philippinesPrimaryColor}; } .show-more { color: ${philippinesPrimaryColor}; } ` export const ElNidoParadiseCard: FunctionComponent<ExtraCardProps> = ({ fluidObject, card = {} }) => { const { i18n } = useCustomTranslation() const common = i18n.languageCode === "fr" ? commonFr : commonEn return ( <PhilippinesCard title={common.country.philippines.card["el-nido-paradise"]} to="el-nido-paradise" {...card}> <SharedCardPhilippinesImages image="elNido" fluidObject={fluidObject} /> </PhilippinesCard> ) } export const ElNidoWhichTourCard: FunctionComponent<ExtraCardProps> = ({ fluidObject, card = {} }) => { const { i18n } = useCustomTranslation() const common = i18n.languageCode === "fr" ? commonFr : commonEn return ( <PhilippinesCard title={common.country.philippines.card["which-tour"]} to="el-nido-which-tour" {...card}> <CarouselImageQuery image="philippines2" fluidObject={fluidObject} /> </PhilippinesCard> ) } export const ElNidoTourACard: FunctionComponent<ExtraCardProps> = ({ fluidObject, card = {} }) => { const { i18n } = useCustomTranslation() const common = i18n.languageCode === "fr" ? commonFr : commonEn return ( <PhilippinesCard title={common.country.philippines.card["el-nido-tour-a"]} to="el-nido-tour-a" {...card}> <SharedCardPhilippinesImages image="tourA" fluidObject={fluidObject} /> </PhilippinesCard> ) } export const ElNidoTourBCard: FunctionComponent<ExtraCardProps> = ({ fluidObject, card = {} }) => { const { i18n } = useCustomTranslation() const common = i18n.languageCode === "fr" ? commonFr : commonEn return ( <PhilippinesCard title={common.country.philippines.card["el-nido-tour-b"]} to="el-nido-tour-b" {...card}> <SharedCardPhilippinesImages image="tourB" fluidObject={fluidObject} /> </PhilippinesCard> ) }
Nebulis/blog
src/pages/asia/singapore/christmas-in-singapore.tsx
<reponame>Nebulis/blog<filename>src/pages/asia/singapore/christmas-in-singapore.tsx import React from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../components/layout/seo" import { useCustomTranslation } from "../../../i18n-hook" import { Comments } from "../../../components/core/comments" import translationFr from "../../../locales/fr/asia/singapore/christmas-in-singapore.json" import translationEn from "../../../locales/en/asia/singapore/christmas-in-singapore.json" import { Introduction, PillTitle, SectionContent, Visit } from "../../../components/core/section" import { Conclusion } from "../../../components/core/conclusion" import { Divider } from "../../../components/core/divider" import { Title } from "../../../components/core/title" import HomeImgUrl from "../../../images/asia/singapore/christmas-in-singapore/christmas-in-singapore-main.jpg" import { GroupOfImages, ImageAsLandscape, ImageAsLandscapeOnTheLeft, ImageAsLandscapeOnTheRight, ImageAsPortrait, TwoImagesLeftBigger, TwoImagesRightBigger, TwoImagesSameSizeOrToGroup, } from "../../../components/images/layout" import { SharedCardSingaporeImages } from "../../../components/images/asia/singapore/shared-card-singapore-images" import { ChristmasInSingaporeImages } from "../../../components/images/asia/singapore/christmas-in-singapore" import { ChristmasBlogLayout, ChristmasHeadline } from "../../../components/core/christmas" const namespace = "asia/singapore/christmas-in-singapore" const id = "christmas-in-singapore" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.singapore.card.${id}`) return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <ChristmasBlogLayout page={id} location={location}> <Title title={title} linkId={id} /> <ImageAsLandscape> <SharedCardSingaporeImages image="christmasInSingapore" /> </ImageAsLandscape> <Divider /> <Introduction>{t("introduction.part1")}</Introduction> <SectionContent> <p>{t("introduction.part2")}</p> </SectionContent> <Divider /> <PillTitle title={t("part1.title")}> <p>{t("part1.part1")}</p> <p>{t("part1.part2")}</p> <ImageAsLandscape> <ChristmasInSingaporeImages image="tradition" /> </ImageAsLandscape> <p>{t("part1.part3")}</p> <p>{t("part1.part4")}</p> <p>{t("part1.part5")}</p> <p>{t("part1.part6")}</p> </PillTitle> <PillTitle title={t("part2.title")}> <p>{t("part2.part1")}</p> <p>{t("part2.part2")}</p> <p>{t("part2.part3")}</p> </PillTitle> <PillTitle title={t("part3.title")}> <p>{t("part3.part1")}</p> <p>{t("part3.part2")}</p> <p>{t("part3.part3")}</p> <GroupOfImages> <ImageAsLandscape> <ChristmasInSingaporeImages image="singapore" /> </ImageAsLandscape> <ImageAsPortrait> <ChristmasInSingaporeImages image="singapore2" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="singapore3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("part3.part4")}</p> <p>{t("part3.part5")}</p> <p>{t("part3.part6")}</p> </PillTitle> <Visit> {/* just to have the correct space*/} <SectionContent /> <Divider /> <section> <ChristmasHeadline>{t("visit.title")}</ChristmasHeadline> <Divider /> <PillTitle title={t("visit.title1")}> <p>{t("visit.part1")}</p> <p>{t("visit.part2")}</p> <p>{t("visit.part3")}</p> </PillTitle> </section> <Divider /> <section> <ChristmasHeadline>{t("visit1.title")}</ChristmasHeadline> <Divider /> <SectionContent> <p>{t("visit1.part1")}</p> <p>{t("visit1.part2")}</p> </SectionContent> <PillTitle title={t("visit1.part3.title")}> <p>{t("visit1.part3.part1")}</p> </PillTitle> <PillTitle title={t("visit1.part4.title")}> <p>{t("visit1.part4.part1")}</p> <p>{t("visit1.part4.part2")}</p> <p>{t("visit1.part4.part3")}</p> <ImageAsLandscape> <ChristmasInSingaporeImages image="mbs" /> </ImageAsLandscape> </PillTitle> <PillTitle title={t("visit1.part5.title")}> <p>{t("visit1.part5.part1")}</p> <p>{t("visit1.part5.part2")}</p> <p>{t("visit1.part5.part3")}</p> <p>{t("visit1.part5.part4")}</p> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden" /> </ImageAsLandscape> <p>{t("visit1.part5.part5")}</p> <p>{t("visit1.part5.part6")}</p> <GroupOfImages> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden2" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <ChristmasInSingaporeImages image="garden3" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <ChristmasInSingaporeImages image="garden4" /> </ImageAsLandscapeOnTheRight> <ImageAsPortrait> <ChristmasInSingaporeImages image="garden5" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden6" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden7" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <ChristmasInSingaporeImages image="garden8" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <ChristmasInSingaporeImages image="garden9" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden10" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="garden11" /> <ChristmasInSingaporeImages image="garden12" /> </TwoImagesSameSizeOrToGroup> <ImageAsPortrait> <ChristmasInSingaporeImages image="garden13" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden14" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit1.part5.part7")}</p> <p>{t("visit1.part5.part8")}</p> <GroupOfImages> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden15" /> </ImageAsLandscape> <TwoImagesRightBigger> <ChristmasInSingaporeImages image="garden16" /> <ChristmasInSingaporeImages image="garden17" /> </TwoImagesRightBigger> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden28" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden19" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="garden20" /> <ChristmasInSingaporeImages image="garden21" /> </TwoImagesSameSizeOrToGroup> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="garden22" /> <ChristmasInSingaporeImages image="garden23" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden24" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="garden25" /> <ChristmasInSingaporeImages image="garden26" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden27" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden18" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="garden29" /> <ChristmasInSingaporeImages image="garden30" /> </TwoImagesSameSizeOrToGroup> <ImageAsPortrait> <ChristmasInSingaporeImages image="garden31" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden32" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden33" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="garden34" /> </ImageAsLandscape> <TwoImagesRightBigger> <ChristmasInSingaporeImages image="garden35" /> <ChristmasInSingaporeImages image="garden36" /> </TwoImagesRightBigger> </GroupOfImages> <p>{t("visit1.part5.part9")}</p> </PillTitle> </section> <Divider /> <section> <ChristmasHeadline>{t("visit2.title")}</ChristmasHeadline> <Divider /> <PillTitle title={t("visit2.title1")}> <p>{t("visit2.part1")}</p> <GroupOfImages> <ImageAsPortrait> <ChristmasInSingaporeImages image="jewel" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="jewel2" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="jewel3" /> <ChristmasInSingaporeImages image="jewel4" /> </TwoImagesSameSizeOrToGroup> </GroupOfImages> <p>{t("visit2.part2")}</p> <p>{t("visit2.part3")}</p> <p>{t("visit2.part4")}</p> <ImageAsPortrait> <ChristmasInSingaporeImages image="jewel5" /> </ImageAsPortrait> <p>{t("visit2.part5")}</p> <GroupOfImages> <TwoImagesRightBigger> <ChristmasInSingaporeImages image="jewel6" /> <ChristmasInSingaporeImages image="jewel7" /> </TwoImagesRightBigger> <TwoImagesLeftBigger> <ChristmasInSingaporeImages image="jewel9" /> <ChristmasInSingaporeImages image="jewel8" /> </TwoImagesLeftBigger> <ImageAsPortrait> <ChristmasInSingaporeImages image="jewel10" /> </ImageAsPortrait> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="jewel11" /> <ChristmasInSingaporeImages image="jewel12" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscapeOnTheLeft> <ChristmasInSingaporeImages image="jewel13" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <ChristmasInSingaporeImages image="jewel14" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit2.part6")}</p> <GroupOfImages> <ImageAsLandscape> <ChristmasInSingaporeImages image="jewel15" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="jewel16" /> <ChristmasInSingaporeImages image="jewel17" /> </TwoImagesSameSizeOrToGroup> </GroupOfImages> </PillTitle> </section> <Divider /> <section> <ChristmasHeadline>{t("visit3.title")}</ChristmasHeadline> <Divider /> <SectionContent> <p>{t("visit3.part1")}</p> <p>{t("visit3.part2")}</p> <p>{t("visit3.part3")}</p> <GroupOfImages> <ImageAsLandscape> <ChristmasInSingaporeImages image="meal" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="meal2" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="meal3" /> <ChristmasInSingaporeImages image="meal4" /> </TwoImagesSameSizeOrToGroup> </GroupOfImages> <p>{t("visit3.part4")}</p> <ImageAsLandscape> <ChristmasInSingaporeImages image="meal5" /> </ImageAsLandscape> </SectionContent> </section> <Divider /> <section> <ChristmasHeadline>{t("visit4.title")}</ChristmasHeadline> <Divider /> <PillTitle title={t("visit4.part1.title")}> <p>{t("visit4.part1.part1")}</p> <p>{t("visit4.part1.part2")}</p> </PillTitle> <PillTitle title={t("visit4.part2.title")}> <p>{t("visit4.part2.part1")}</p> </PillTitle> <PillTitle title={t("visit4.part3.title")}> <p>{t("visit4.part3.part1")}</p> <p>{t("visit4.part3.part2")}</p> <p>{t("visit4.part3.part3")}</p> <GroupOfImages> <ImageAsPortrait> <ChristmasInSingaporeImages image="snow" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="snow2" /> </ImageAsLandscape> </GroupOfImages> </PillTitle> <PillTitle title={t("visit4.part4.title")}> <p>{t("visit4.part4.part1")}</p> <p>{t("visit4.part4.part2")}</p> <p>{t("visit4.part4.part3")}</p> </PillTitle> </section> <Divider /> <section> <ChristmasHeadline>{t("visit5.title")}</ChristmasHeadline> <Divider /> <SectionContent> <p>{t("visit5.part1")}</p> <p>{t("visit5.part2")}</p> <p>{t("visit5.part3")}</p> <p>{t("visit5.part4")}</p> <GroupOfImages> <ImageAsPortrait> <ChristmasInSingaporeImages image="orientExpress" /> </ImageAsPortrait> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress2" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress3" /> </ImageAsLandscape> <TwoImagesSameSizeOrToGroup> <ChristmasInSingaporeImages image="orientExpress4" /> <ChristmasInSingaporeImages image="orientExpress5" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress6" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress7" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress8" /> </ImageAsLandscape> <ImageAsLandscape> <ChristmasInSingaporeImages image="orientExpress9" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <SectionContent> <p>{t("visit6.part1")}</p> <p>{t("visit6.part2")}</p> <p>{t("visit6.part3")}</p> </SectionContent> </section> </Visit> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}\n${t("facebook.part3")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [] : [], }} /> </ChristmasBlogLayout> </> ) } export default IndexPage
Nebulis/blog
src/components/core/asia/philippines/console-draw-sth.ts
<gh_stars>0 /* eslint-disable prettier/prettier */ export const drawSth = () => { console.log("TODOOOOOO") }
Nebulis/blog
src/components/images/asia/japan/nagoya/toganji-images.tsx
import { useStaticQuery, graphql } from "gatsby" import Img from "gatsby-image" import React, { useEffect } from "react" import { ExtraImageProps } from "../../../../../types/shared" const alt = { visit: "Toganji Visit", visit2: "Toganji Visit", visit3: "Toganji Visit", garden: "Toganji Garden", garden2: "Toganji Garden", garden3: "Toganji Garden", garden4: "Toganji Garden", garden5: "Toganji Garden", garden6: "Toganji Garden", garden7: "Toganji Garden", garden8: "Toganji Garden", garden9: "Toganji Garden", garden10: "Toganji Garden", garden11: "Toganji Garden", garden12: "Toganji Garden", garden13: "Toganji Garden", garden14: "Toganji Garden", garden15: "Toganji Garden", garden16: "Toganji Garden", buddha: "Toganji Buddha", buddha2: "Toganji Buddha", buddha3: "Toganji Buddha", buddha4: "Toganji Buddha", buddha5: "Toganji Buddha", buddha6: "Toganji Buddha", cardFr1: "Toganji Pinterest card", cardFr2: "Toganji Pinterest card", cardEn1: "Toganji Pinterest card", cardEn2: "Toganji Pinterest card", } export const ToganjiImages: React.FunctionComponent<ExtraImageProps & { image: keyof typeof alt }> = ({ className = "", image, fluidObject = {}, imgStyle = {}, onLoad, }) => { const data = useStaticQuery(graphql` query { visit: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-visit.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } visit2: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-visit2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } visit3: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-visit3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden2: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden3: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden4: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden5: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden6: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden7: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden7.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden8: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden8.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden9: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden9.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden10: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden10.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden11: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden11.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden12: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden12.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden13: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden13.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden14: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden14.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden15: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden15.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } garden16: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-garden16.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha2: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha2.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha3: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha3.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha4: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha4.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 80, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha5: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha5.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 90, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } buddha6: file(relativePath: { eq: "asia/japan/nagoya/toganji/toganji-buddha6.jpg" }) { childImageSharp { fluid(maxWidth: 1200, quality: 60, srcSetBreakpoints: [600]) { ...GatsbyImageSharpFluid } } } cardFr1: file(relativePath: { eq: "asia/japan/nagoya/toganji/card-fr1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 80, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardFr2: file(relativePath: { eq: "asia/japan/nagoya/toganji/card-fr2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 80, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn1: file(relativePath: { eq: "asia/japan/nagoya/toganji/card-en1.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 80, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } cardEn2: file(relativePath: { eq: "asia/japan/nagoya/toganji/card-en2.jpg" }) { childImageSharp { fluid(maxWidth: 1000, quality: 80, srcSetBreakpoints: [1000]) { ...GatsbyImageSharpFluid } } } } `) useEffect(() => { if (onLoad) onLoad(data[image].childImageSharp.fluid.src) }, [data, image, onLoad]) return ( <Img fluid={{ ...data[image].childImageSharp.fluid, ...fluidObject }} alt={alt[image]} className={className} imgStyle={imgStyle} /> ) }
Nebulis/blog
src/components/core/asia/vietnam/vietnam.colors.ts
<reponame>Nebulis/blog<filename>src/components/core/asia/vietnam/vietnam.colors.ts export const vietnamPrimaryColor = "#ffd966" export const vietnamPrimaryColorWithOpacity = (opacity: number) => `rgba(255,217,102,${opacity})` export const vietnamPrimaryColorDarker = "#B88A00" // using contrast checker - lighthouse happy with #946F00
Nebulis/blog
src/components/core/asia/singapore/singapore.cards.tsx
import { ExtraCardProps } from "../../../../types/shared" import { useCustomTranslation } from "../../../../i18n-hook" import commonFr from "../../../../locales/fr/common.json" import commonEn from "../../../../locales/en/common.json" import React, { FunctionComponent } from "react" import { Card } from "../../../card" import styled from "@emotion/styled" import { singaporePrimaryColorDarker } from "./singapore.variables" import { SharedCardSingaporeImages } from "../../../images/asia/singapore/shared-card-singapore-images" export const SingaporeCard = styled(Card)` .tags a { color: ${singaporePrimaryColorDarker}; } .tags a:hover { border-bottom: 1px solid ${singaporePrimaryColorDarker}; } .show-more { color: ${singaporePrimaryColorDarker}; } ` export const ChritmasInSingaporeCard: FunctionComponent<ExtraCardProps> = ({ fluidObject, card = {} }) => { const { i18n } = useCustomTranslation() const common = i18n.languageCode === "fr" ? commonFr : commonEn return ( <SingaporeCard title={common.country.singapore.card["christmas-in-singapore"]} to="christmas-in-singapore" {...card} > <SharedCardSingaporeImages image="christmasInSingapore" fluidObject={fluidObject} /> </SingaporeCard> ) }
Nebulis/blog
src/__tests__/utils.test.ts
<reponame>Nebulis/blog import { getPathForEnglish, getPathForFrench } from "../utils" describe("getPathForFrench", () => { it("should work when url start with /en", () => { expect(getPathForFrench({ pathname: "/en/bla" })).toBe("/bla") }) it("should work when url start is /en", () => { expect(getPathForFrench({ pathname: "/en" })).toBe("") }) it("should work when url start is /", () => { expect(getPathForFrench({ pathname: "/" })).toBe("/") }) it("should work when url does not start by /en", () => { expect(getPathForFrench({ pathname: "/bar" })).toBe("/bar") }) it("should keep search", () => { expect(getPathForFrench({ pathname: "/bar", search: "?country=australia" })).toBe("/bar?country=australia") }) }) describe("getPathForEnglish(", () => { it("should work when url start with /en", () => { expect(getPathForEnglish({ pathname: "/en/bla" })).toBe("/en/bla") }) it("should work when url start is /en", () => { expect(getPathForEnglish({ pathname: "/en" })).toBe("/en") }) it("should work when url start is /", () => { expect(getPathForEnglish({ pathname: "/" })).toBe("/en/") }) it("should work when url does not start by /en", () => { expect(getPathForEnglish({ pathname: "/bar" })).toBe("/en/bar") }) it("should keep search", () => { expect(getPathForEnglish({ pathname: "/bar", search: "?country=australia" })).toBe("/en/bar?country=australia") }) })
Nebulis/blog
src/pages/asia/philippines/palawan/el-nido-tour-a.tsx
import React from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/asia/philippines/palawan/el-nido-tour-a.json" import translationEn from "../../../../locales/en/asia/philippines/palawan/el-nido-tour-a.json" import { PhilippinesBlogLayout, PhilippinesHeadline, PhilippinesTitle, } from "../../../../components/core/asia/philippines/philippines" import { Baggage, Booking, HowLong, HowMuch, Introduction, Opinion, SectionContent, Visit, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import HomeImgUrl from "../../../../images/asia/philippines/palawan/el-nido-tour-a/tour-a-main.jpg" import { GroupOfImages, ImageAsLandscape, ImageAsLandscapeOnTheLeft, ImageAsLandscapeOnTheRight, ImageAsPortrait, Panorama, TwoImagesSameSize, TwoImagesSameSizeOrToGroup, } from "../../../../components/images/layout" import { SharedCardPhilippinesImages } from "../../../../components/images/asia/philippines/shared-card-philippines-images" import ElNidoMap from "../../../../images/asia/philippines/palawan/el-nido-tour-a/tour-a-map.png" import SkipperCharters1 from "../../../../images/asia/philippines/palawan/el-nido-tour-a/skipper-charters-tour-a-1.jpg" import SkipperCharters2 from "../../../../images/asia/philippines/palawan/el-nido-tour-a/skipper-charters-tour-a-2.jpg" import { BookingGygCardContainer, MapContainer } from "../../../../components/layout/layout" import { TourAImages } from "../../../../components/images/asia/philippines/palawan/el-nido-tour-a" import { philippinesPrimaryColor, philippinesPrimaryColorDarker, } from "../../../../components/core/asia/philippines/philippines.colors" import { css } from "@emotion/react" import { Quote } from "../../../../components/core/quote" import { TravelCardBookingStyle } from "../../../../components/core/booking" const namespace = "asia/philippines/palawan/tour-a" const id = "el-nido-tour-a" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.philippines.card.${id}`) return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <PhilippinesBlogLayout page={id} location={location}> <PhilippinesTitle title={title} linkId={id} /> <ImageAsLandscape> <SharedCardPhilippinesImages image="tourA" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction")}</Introduction> <Divider /> <SectionContent> <MapContainer> <img src={ElNidoMap} alt="El Nido Map Tour A" /> </MapContainer> </SectionContent> <Booking title={t("where-to-book.title")}> <p>{t("where-to-book.part1")}</p> <p>{t("where-to-book.part2")}</p> <p>{t("where-to-book.part3")}</p> </Booking> <HowMuch> <p>{t("how-much.part1")}</p> <ul> <li> <span css={css` font-weight: bold; text-transform: uppercase; color: ${philippinesPrimaryColorDarker}; `} > {t("how-much.part2")} </span> <ul> <li>{t("how-much.part3")}</li> <li>{t("how-much.part4")}</li> </ul> </li> </ul> <BookingGygCardContainer> <TravelCardBookingStyle to="https://www.elnidoparadise.com/booking/private-tours/private-tour-a/" title={ i18n.languageCode === "fr" ? "El Nido Paradise - Tour A - Privé" : "El Nido Paradise - Private Tour A" } image="https://www.elnidoparadise.com/wp-content/uploads/booking-el-nido-tour-a.jpeg" price={135} duration={{ value: 1, unit: "day" }} groupType="private" /> <TravelCardBookingStyle to="https://www.elnidoparadise.com/booking/main-island-hopping-tours/tour-a/" title={ i18n.languageCode === "fr" ? "El Nido Paradise - Tour A - Public" : "El Nido Paradise - Public Tour A" } image="https://www.elnidoparadise.com/wp-content/uploads/small-lagoon.jpg" price={20} duration={{ value: 1, unit: "day" }} groupType="public" /> </BookingGygCardContainer> <ul> <li> <span css={css` font-weight: bold; text-transform: uppercase; color: ${philippinesPrimaryColorDarker}; `} > {t("how-much.part5")} </span> <ul> <li>{t("how-much.part6")}</li> <li>{t("how-much.part7")}</li> </ul> </li> </ul> <BookingGygCardContainer> <TravelCardBookingStyle to="http://www.skippercharters.ph/el-nido-charters.html" title={ i18n.languageCode === "fr" ? "El Nido Charters - Tour A - Privé" : "El Nido Charters - Private Tour A" } image={SkipperCharters1} price={400} duration={{ value: 1, unit: "day" }} groupType="private" /> <TravelCardBookingStyle to="http://www.skippercharters.ph/el-nido-charters.html" title={ i18n.languageCode === "fr" ? "El Nido Charters - Tour A - Public" : "El Nido Charters - Public Tour A" } image={SkipperCharters2} price={60} duration={{ value: 1, unit: "day" }} groupType="public" /> </BookingGygCardContainer> <p>{t("how-much.part8")}</p> <ul> <li>{t("how-much.part9")}</li> <li>{t("how-much.part10")}</li> <li>{t("how-much.part11")}</li> </ul> <p>{t("how-much.part12")}</p> <p>{t("how-much.part13")}</p> </HowMuch> <HowLong title={t("how-long.title")}> <p>{t("how-long.part1")}</p> <p>{t("how-long.part2")}</p> <p>{t("how-long.part3")}</p> <p>{t("how-long.part4")}</p> </HowLong> <Visit title={t("visit.title")}> {/* just to have the correct space*/} <SectionContent /> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit1.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="bigLagoon" /> </ImageAsLandscape> <p className="tc b" css={css` color: ${philippinesPrimaryColor}; `} > {t("visit.visit1.part1")} </p> <p>{t("visit.visit1.part2")}</p> <p>{t("visit.visit1.part3")}</p> <p>{t("visit.visit1.part4")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourAImages image="bigLagoon2" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourAImages image="bigLagoon3" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.visit1.part5")}</p> <p>{t("visit.visit1.part6")}</p> <ImageAsLandscape> <TourAImages image="bigLagoon4" /> </ImageAsLandscape> <p>{t("visit.visit1.part7")}</p> <p>{t("visit.visit1.part8")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="bigLagoon6" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="bigLagoon5" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit2.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="secretLagoon" /> </ImageAsLandscape> <p>{t("visit.visit2.part1")}</p> <p>{t("visit.visit2.part2")}</p> <p>{t("visit.visit2.part3")}</p> <p>{t("visit.visit2.part4")}</p> <TwoImagesSameSizeOrToGroup> <TourAImages image="secretLagoon2" /> <TourAImages image="secretLagoon3" /> </TwoImagesSameSizeOrToGroup> <p>{t("visit.visit2.part5")}</p> <p>{t("visit.visit2.part6")}</p> <p>{t("visit.visit2.part7")}</p> <GroupOfImages> <TwoImagesSameSize css={css` .panel-image { max-height: 80vh; } `} > <TourAImages image="secretLagoon4" /> <TourAImages image="secretLagoon5" /> </TwoImagesSameSize> <ImageAsPortrait> <TourAImages image="secretLagoon6" /> </ImageAsPortrait> </GroupOfImages> <p>{t("visit.visit2.part8")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="secretLagoon7" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="secretLagoon8" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="secretLagoon9" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit3.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="shimizuIsland" /> </ImageAsLandscape> <p>{t("visit.visit3.part1")}</p> <p>{t("visit.visit3.part2")}</p> <p>{t("visit.visit3.part3")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourAImages image="shimizuIsland2" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourAImages image="shimizuIsland3" /> </ImageAsLandscapeOnTheRight> <Panorama> <TourAImages image="shimizuIsland4" /> </Panorama> </GroupOfImages> <p>{t("visit.visit3.part4")}</p> <p>{t("visit.visit3.part5")}</p> </SectionContent> <Divider /> </section> <section> <PhilippinesHeadline>{t("visit.visit4.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="payongBeach" /> </ImageAsLandscape> <p>{t("visit.visit4.part1")}</p> <p>{t("visit.visit4.part2")}</p> <p>{t("visit.visit4.part3")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="payongBeach2" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="payongBeach3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.visit4.part4")}</p> <p>{t("visit.visit4.part5")}</p> <p>{t("visit.visit4.part6")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourAImages image="payongBeach4" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourAImages image="payongBeach5" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit5.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="sevenCommandoBeach" /> </ImageAsLandscape> <p>{t("visit.visit5.part1")}</p> <p>{t("visit.visit5.part2")}</p> <ImageAsLandscape> <TourAImages image="sevenCommandoBeach2" /> </ImageAsLandscape> <p>{t("visit.visit5.part3")}</p> <p>{t("visit.visit5.part4")}</p> <GroupOfImages> <Panorama> <TourAImages image="sevenCommandoBeach3" /> </Panorama> <ImageAsLandscapeOnTheLeft> <TourAImages image="sevenCommandoBeach4" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourAImages image="sevenCommandoBeach5" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.visit5.part5")}</p> <Panorama> <TourAImages image="sevenCommandoBeach6" /> </Panorama> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit6.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourAImages image="snorkeling" /> </ImageAsLandscape> <p>{t("visit.visit6.part1")}</p> <p>{t("visit.visit6.part2")}</p> <p>{t("visit.visit6.part3")}</p> <p className="tc ttu b">{t("visit.visit6.part4")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="snorkeling2" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling3" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling4" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling5" /> </ImageAsLandscape> </GroupOfImages> <p className="tc ttu b">{t("visit.visit6.part5")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="snorkeling6" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling7" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling8" /> </ImageAsLandscape> <ImageAsLandscape> <TourAImages image="snorkeling9" /> </ImageAsLandscape> </GroupOfImages> <p className="tc i">{t("visit.visit6.part6")}</p> </SectionContent> </section> </Visit> <Opinion title={t("opinion.title")}> <p>{t("opinion.part1")}</p> <p>{t("opinion.part2")}</p> <p>{t("opinion.part3")}</p> <p>{t("opinion.part4")}</p> <p>{t("opinion.part5")}</p> </Opinion> <Baggage title={t("must-pack.title")}> <ul> <li>{t("must-pack.part1")}</li> <li>{t("must-pack.part2")}</li> <li>{t("must-pack.part3")}</li> <li>{t("must-pack.part4")}</li> <li>{t("must-pack.part5")}</li> <li>{t("must-pack.part6")}</li> <li>{t("must-pack.part7")}</li> <li>{t("must-pack.part8")}</li> <li>{t("must-pack.part9")}</li> </ul> </Baggage> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [<TourAImages image="cardFr1" key="cardFr1" />, <TourAImages image="cardFr2" key="cardFr1" />] : [<TourAImages image="cardEn1" key="cardEn1" />, <TourAImages image="cardEn2" key="cardEn1" />], }} /> </PhilippinesBlogLayout> </> ) } export default IndexPage
Nebulis/blog
src/components/application.tsx
<reponame>Nebulis/blog<gh_stars>0 import { graphql, PageProps, useStaticQuery } from "gatsby" import React, { useState } from "react" import { configureI18n } from "../i18n" import { isEnglishPage } from "../utils" import { useCustomTranslation } from "../i18n-hook" configureI18n() export const Application: React.FunctionComponent<PageProps> = ({ children, location }) => { const { i18n } = useCustomTranslation() const { site } = useStaticQuery( graphql` query { site { siteMetadata { config { context comments ssrBuild } } } } ` ) const initialDevelopmentValue = site.siteMetadata.config.context !== "production" const [development, setDevelopment] = useState(initialDevelopmentValue) if (!initialDevelopmentValue) { // if the URL starts with /en, then we really want to display the page in english if (isEnglishPage(location) && i18n.languageCode !== "en") { i18n.changeLanguage("en") } else if (!isEnglishPage(location) && i18n.languageCode !== "fr") { i18n.changeLanguage("fr") } } return ( <ApplicationContext.Provider value={{ initialDevelopmentValue, development, displayComments: site.siteMetadata.config.comments === "enabled", ssrBuild: site.siteMetadata.config.ssrBuild === "enabled", toggle: () => setDevelopment(!development), covid: true, instagramInAppBrowser: typeof window !== "undefined" ? navigator.userAgent.toLowerCase().indexOf("instagram") !== -1 : false, }} > {children} </ApplicationContext.Provider> ) } export const ApplicationContext = React.createContext<{ development: boolean displayComments: boolean ssrBuild: boolean /** * Property to keep track of the initial value of development when the page started * This property is useful because development property can be changed over the time by calling the toggle function * Some features need to be always enable or disable and must not change over the time */ initialDevelopmentValue?: boolean toggle?: () => void covid: boolean /** * There is a problem with instagram in-app browser. the browser menu and footer bar change the height of viewport, * which in turn change the maximum height of images, and triggers a very annoying layout shift * we use this boolean to detect whether we are inside instagram in-app browser. If that's the case, we will set the maximum-height * with the current viewport height, so that it doesn't update when the browser bars appear or disappear. Fixed elements * - images (mainly portrait) * - header (computed using 100vh) * - carousel (computed using header) */ instagramInAppBrowser: boolean }>({ development: false, displayComments: false, ssrBuild: false, initialDevelopmentValue: false, covid: true, instagramInAppBrowser: false, })
Nebulis/blog
src/pages/asia/philippines/palawan/el-nido-tour-b.tsx
import React from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/asia/philippines/palawan/el-nido-tour-b.json" import translationEn from "../../../../locales/en/asia/philippines/palawan/el-nido-tour-b.json" import { PhilippinesBlogLayout, PhilippinesHeadline, PhilippinesTitle, } from "../../../../components/core/asia/philippines/philippines" import { Baggage, Booking, HowLong, HowMuch, Introduction, Opinion, SectionContent, Visit, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import { Quote } from "../../../../components/core/quote" import HomeImgUrl from "../../../../images/asia/philippines/palawan/el-nido-tour-b/tour-b-main.jpg" import { GroupOfImages, ImageAsLandscape, ImageAsLandscapeOnTheLeft, ImageAsLandscapeOnTheRight, ImageAsPortrait, TwoImagesSameSizeOrToGroup, } from "../../../../components/images/layout" import { SharedCardPhilippinesImages } from "../../../../components/images/asia/philippines/shared-card-philippines-images" import { BookingGygCardContainer, MapContainer } from "../../../../components/layout/layout" import ElNidoMap from "../../../../images/asia/philippines/palawan/el-nido-tour-b/tour-b-map.png" import SkipperCharters1 from "../../../../images/asia/philippines/palawan/el-nido-tour-b/skipper-charters-tour-b-1.jpg" import SkipperCharters2 from "../../../../images/asia/philippines/palawan/el-nido-tour-b/skipper-charters-tour-b-2.jpg" import { TourBImages } from "../../../../components/images/asia/philippines/palawan/el-nido-tour-b" import { philippinesPrimaryColor, philippinesPrimaryColorDarker, } from "../../../../components/core/asia/philippines/philippines.colors" import { css } from "@emotion/react" import { CarouselImageQuery } from "../../../../components/images/carousel" import { TravelCardBookingStyle } from "../../../../components/core/booking" const namespace = "asia/philippines/palawan/tour-b" const id = "el-nido-tour-b" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.philippines.card.${id}`) return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <PhilippinesBlogLayout page={id} location={location}> <PhilippinesTitle title={title} linkId={id} /> <ImageAsLandscape> <SharedCardPhilippinesImages image="tourB" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction")}</Introduction> <Divider /> <SectionContent> <MapContainer> <img src={ElNidoMap} alt="El Nido Map Tour A" /> </MapContainer> </SectionContent> <Booking title={t("where-to-book.title")}> <p>{t("where-to-book.part1")}</p> <p>{t("where-to-book.part2")}</p> <p>{t("where-to-book.part3")}</p> </Booking> <HowMuch title={t("how-much.title")}> <p>{t("how-much.part1")}</p> <ul> <li> <span css={css` font-weight: bold; text-transform: uppercase; color: ${philippinesPrimaryColorDarker}; `} > {t("how-much.part2")} </span> <ul> <li>{t("how-much.part3")}</li> <li>{t("how-much.part4")}</li> </ul> </li> </ul> <BookingGygCardContainer> <TravelCardBookingStyle to="https://www.elnidoparadise.com/booking/private-tours/private-tour-b/" title={ i18n.languageCode === "fr" ? "El Nido Paradise - Tour B - Privé" : "El Nido Paradise - Private Tour B" } image="https://www.elnidoparadise.com/wp-content/uploads/booking-el-nido-tour-b.jpg" price={145} duration={{ value: 1, unit: "day" }} groupType="private" /> <TravelCardBookingStyle to="https://www.elnidoparadise.com/booking/main-island-hopping-tours/tour-b/" title={ i18n.languageCode === "fr" ? "El Nido Paradise - Tour B - Public" : "El Nido Paradise - Public Tour B" } image="https://www.elnidoparadise.com/wp-content/uploads/cudugnon-cave.jpg" price={22} duration={{ value: 1, unit: "day" }} groupType="public" /> </BookingGygCardContainer> <ul> <li> <span css={css` font-weight: bold; text-transform: uppercase; color: ${philippinesPrimaryColorDarker}; `} > {t("how-much.part5")} </span> <ul> <li>{t("how-much.part6")}</li> <li>{t("how-much.part7")}</li> </ul> </li> </ul> <BookingGygCardContainer> <TravelCardBookingStyle to="http://www.skippercharters.ph/el-nido-charters.html" title={ i18n.languageCode === "fr" ? "El Nido Charters - Tour B - Privé" : "El Nido Charters - Private Tour B" } image={SkipperCharters1} price={400} duration={{ value: 1, unit: "day" }} groupType="private" /> <TravelCardBookingStyle to="http://www.skippercharters.ph/el-nido-charters.html" title={ i18n.languageCode === "fr" ? "El Nido Charters - Tour B - Public" : "El Nido Charters - Public Tour B" } image={SkipperCharters2} price={60} duration={{ value: 1, unit: "day" }} groupType="public" /> </BookingGygCardContainer> <p>{t("how-much.part8")}</p> <ul> <li>{t("how-much.part9")}</li> <li>{t("how-much.part10")}</li> </ul> <p>{t("how-much.part11")}</p> <p>{t("how-much.part12")}</p> </HowMuch> <HowLong title={t("how-long.title")}> <p>{t("how-long.part1")}</p> <p>{t("how-long.part2")}</p> <p>{t("how-long.part3")}</p> <p>{t("how-long.part4")}</p> </HowLong> <Visit title={t("visit.title")}> {/* just to have the correct space*/} <SectionContent /> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit1.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourBImages image="entalulaBeach" /> </ImageAsLandscape> <p>{t("visit.visit1.part1")}</p> <p>{t("visit.visit1.part2")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourBImages image="entalulaBeach2" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="entalulaBeach3" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.visit1.part3")}</p> <p>{t("visit.visit1.part4")}</p> <p>{t("visit.visit1.part5")}</p> <TwoImagesSameSizeOrToGroup> <TourBImages image="entalulaBeach4" /> <TourBImages image="entalulaBeach5" /> </TwoImagesSameSizeOrToGroup> <p>{t("visit.visit1.part6")}</p> <p>{t("visit.visit1.part7")}</p> <GroupOfImages> <ImageAsLandscape> <TourBImages image="entalulaBeach6" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <TourBImages image="entalulaBeach7" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="entalulaBeach8" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit2.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourBImages image="snakeIsland" /> </ImageAsLandscape> <p className="tc b mb2" css={css` color: ${philippinesPrimaryColor}; `} > {t("visit.visit2.part1")} </p> <p>{t("visit.visit2.part2")}</p> <p>{t("visit.visit2.part3")}</p> <p>{t("visit.visit2.part4")}</p> <p>{t("visit.visit2.part5")}</p> <TwoImagesSameSizeOrToGroup> <TourBImages image="snakeIsland2" /> <TourBImages image="snakeIsland3" /> </TwoImagesSameSizeOrToGroup> <p>{t("visit.visit2.part6")}</p> <p>{t("visit.visit2.part7")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourBImages image="snakeIsland4" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="snakeIsland5" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> <p>{t("visit.visit2.part8")}</p> <p>{t("visit.visit2.part9")}</p> <p>{t("visit.visit2.part10")}</p> <p>{t("visit.visit2.part11")}</p> <GroupOfImages> <ImageAsLandscape> <TourBImages image="snakeIsland6" /> </ImageAsLandscape> <ImageAsLandscape> <TourBImages image="snakeIsland7" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <TourBImages image="snakeIsland8" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="snakeIsland9" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit3.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <CarouselImageQuery image="philippines1" /> </ImageAsLandscape> <p>{t("visit.visit3.part1")}</p> <p className="tc b mb2" css={css` color: ${philippinesPrimaryColor}; `} > {t("visit.visit3.part2")} </p> <p>{t("visit.visit3.part3")}</p> <GroupOfImages> <ImageAsLandscape> <TourBImages image="pinagbuyutanIsland2" /> </ImageAsLandscape> <ImageAsLandscape> <TourBImages image="pinagbuyutanIsland3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.visit3.part4")}</p> <TwoImagesSameSizeOrToGroup> <TourBImages image="pinagbuyutanIsland4" /> <TourBImages image="pinagbuyutanIsland5" /> </TwoImagesSameSizeOrToGroup> <p>{t("visit.visit3.part5")}</p> <GroupOfImages> <ImageAsLandscape> <TourBImages image="pinagbuyutanIsland6" /> </ImageAsLandscape> <ImageAsLandscape> <TourBImages image="pinagbuyutanIsland7" /> </ImageAsLandscape> <ImageAsLandscapeOnTheLeft> <TourBImages image="pinagbuyutanIsland8" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="pinagbuyutanIsland9" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit4.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourBImages image="yumyumIsland" /> </ImageAsLandscape> <p>{t("visit.visit4.part1")}</p> <p>{t("visit.visit4.part2")}</p> <GroupOfImages> <ImageAsPortrait> <TourBImages image="yumyumIsland2" /> </ImageAsPortrait> <ImageAsLandscape> <TourBImages image="yumyumIsland3" /> </ImageAsLandscape> </GroupOfImages> <p>{t("visit.visit4.part3")}</p> <p>{t("visit.visit4.part4")}</p> <ImageAsLandscape> <TourBImages image="yumyumIsland4" /> </ImageAsLandscape> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit5.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourBImages image="cudugnonCave" /> </ImageAsLandscape> <p>{t("visit.visit5.part1")}</p> <p>{t("visit.visit5.part2")}</p> <p>{t("visit.visit5.part3")}</p> <GroupOfImages> <TwoImagesSameSizeOrToGroup> <TourBImages image="cudugnonCave2" /> <TourBImages image="cudugnonCave3" /> </TwoImagesSameSizeOrToGroup> <ImageAsLandscape> <TourBImages image="cudugnonCave4" /> </ImageAsLandscape> <ImageAsPortrait> <TourBImages image="cudugnonCave5" /> </ImageAsPortrait> <ImageAsLandscape> <TourBImages image="cudugnonCave6" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> </section> <Divider /> <section> <PhilippinesHeadline>{t("visit.visit6.title")}</PhilippinesHeadline> <Divider /> <SectionContent> <ImageAsLandscape> <TourBImages image="snorkeling" /> </ImageAsLandscape> <p>{t("visit.visit6.part1")}</p> <p>{t("visit.visit6.part2")}</p> <p>{t("visit.visit6.part3")}</p> <GroupOfImages> <ImageAsLandscapeOnTheLeft> <TourBImages image="snorkeling2" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight> <TourBImages image="snorkeling3" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscape> <TourBImages image="snorkeling4" /> </ImageAsLandscape> <ImageAsLandscape> <TourBImages image="snorkeling5" /> </ImageAsLandscape> <ImageAsLandscape> <TourBImages image="snorkeling6" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> </section> </Visit> <Opinion title={t("opinion.title")}> <p>{t("opinion.part1")}</p> <p>{t("opinion.part2")}</p> <p>{t("opinion.part3")}</p> <p>{t("opinion.part4")}</p> </Opinion> <Baggage title={t("must-pack.title")}> <ul> <li>{t("must-pack.part1")}</li> <li>{t("must-pack.part2")}</li> <li>{t("must-pack.part3")}</li> <li>{t("must-pack.part4")}</li> <li>{t("must-pack.part5")}</li> <li>{t("must-pack.part6")}</li> <li>{t("must-pack.part7")}</li> <li>{t("must-pack.part8")}</li> <li>{t("must-pack.part9")}</li> </ul> </Baggage> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [<TourBImages image="cardFr1" key="cardFr1" />, <TourBImages image="cardFr2" key="cardFr1" />] : [<TourBImages image="cardEn1" key="cardEn1" />, <TourBImages image="cardEn2" key="cardEn1" />], }} /> </PhilippinesBlogLayout> </> ) } export default IndexPage
Nebulis/blog
firebase/functions/src/contact.ts
import { adminEmail, createCors, mailgunConfiguration } from "./shared"; import express from "express"; import mailgun from "mailgun-js"; export const app = express(); app.use(createCors()); app.post("/", (req, res) => { console.log(JSON.stringify(req.body)); const { name, message, mail, title, isPro } = req.body; const mg = mailgun(mailgunConfiguration); const data = { from: adminEmail, to: "<EMAIL>", "h:Reply-To": `${name} <${mail}>`, subject: `[${isPro ? "Professionel" : "Particulier"}] ${title}`, html: `<h4>From ${name} &lt;${mail}&gt;</h4><p>${message}</p>`, }; mg.messages().send(data, function (error, body) { if (error) { console.error(JSON.stringify(error)); res.status(400).send(error); } else { console.log("Mail sent with success:", JSON.stringify(body)); res.status(200).send(); } }); });
Nebulis/blog
src/pages/asia/philippines/palawan/el-nido-which-tour.tsx
<reponame>Nebulis/blog<gh_stars>0 import React, { useContext } from "react" import { PageProps } from "gatsby" import i18n from "i18next" import SEO from "../../../../components/layout/seo" import { useCustomTranslation } from "../../../../i18n-hook" import { Comments } from "../../../../components/core/comments" import translationFr from "../../../../locales/fr/asia/philippines/palawan/el-nido-which-tour.json" import translationEn from "../../../../locales/en/asia/philippines/palawan/el-nido-which-tour.json" import { PhilippinesBlogLayout, PhilippinesHeadline, PhilippinesTitle, } from "../../../../components/core/asia/philippines/philippines" import { Baggage, Boat, Booking, Choice, HowMuch, Introduction, Opinion, SectionContent, SectionTitle, Visit, } from "../../../../components/core/section" import { Conclusion } from "../../../../components/core/conclusion" import { Divider } from "../../../../components/core/divider" import HomeImgUrl from "../../../../images/asia/philippines/carousel-philippines-2.jpg" import ElNidoMap from "../../../../images/asia/philippines/palawan/el-nido-which-tour/el-nido-which-tour-map.png" import { Anchor, GroupOfImages, ImageAsLandscape, ImageAsLandscapeOnTheLeft, ImageAsLandscapeOnTheRight, ImageAsPortrait, } from "../../../../components/images/layout" import { SharedCardPhilippinesImages } from "../../../../components/images/asia/philippines/shared-card-philippines-images" import { ArticleCardContainer } from "../../../../components/layout/layout" import { ElNidoParadiseCard } from "../../../../components/core/asia/philippines/philippines.card" import styled from "@emotion/styled" import { getLink } from "../../../../components/core/links/links.utils" import { ApplicationContext } from "../../../../components/application" import { ElNidoWhichTourImages } from "../../../../components/images/asia/philippines/palawan/el-nido-which-tour" import { ApplicationLink, ExternalLinkNotUnderlined } from "../../../../components/core/links/link" import { css } from "@emotion/react" // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore https://github.com/Swizec/useDimensions/issues/16 import useDimensions from "react-use-dimensions" import { Quote } from "../../../../components/core/quote" import { TourAImages } from "../../../../components/images/asia/philippines/palawan/el-nido-tour-a" import { CarouselImageQuery } from "../../../../components/images/carousel" import { FakeList } from "../../../../components/core/title" const namespace = "asia/philippines/palawan/which-tour" const id = "el-nido-which-tour" i18n.addResourceBundle("fr", namespace, translationFr) i18n.addResourceBundle("en", namespace, translationEn) const CustomTitle = styled(SectionTitle)` justify-content: center; font-style: italic; font-size: 1.1rem; margin-bottom: 1rem; ` const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => { const { development } = useContext(ApplicationContext) const { t, i18n } = useCustomTranslation([namespace, "common"]) const title = t(`common:country.philippines.card.which-tour`) const tourALinkPublished = development || getLink("el-nido-tour-a").published const tourBLinkPublished = development || getLink("el-nido-tour-b").published const tourCLinkPublished = development || getLink("el-nido-tour-c").published const tourDLinkPublished = development || getLink("el-nido-tour-d").published const [ref, { width }] = useDimensions() const ratio = width / 800 return ( <> <SEO title={title} fullTitle={t("full-title")} socialNetworkDescription={t("social-network-description")} googleDescription={t("google-description")} image={HomeImgUrl} location={location} /> <PhilippinesBlogLayout page={id} location={location}> <PhilippinesTitle title={title} linkId={id} /> <ImageAsLandscape> <CarouselImageQuery image="philippines2" /> </ImageAsLandscape> <Quote>{t("quote")}</Quote> <Divider /> <Introduction>{t("introduction.part1")}</Introduction> <Divider /> <SectionContent> <p>{t("introduction.part2")}</p> {t("introduction.part3") && <p>{t("introduction.part3")}</p>} <p>{t("introduction.part4")}</p> <p>{t("introduction.part5")}</p> <p>{t("introduction.part6")}</p> <ArticleCardContainer> <ElNidoParadiseCard card={{ showTags: false, showPublished: false, showMore: true }} /> </ArticleCardContainer> <p>{t("introduction.part7")}</p> </SectionContent> <Booking title={t("where-to-book.title")}> <p>{t("where-to-book.part1")}</p> <ul> <li>{t("where-to-book.part2")}</li> <li>{t("where-to-book.part3")}</li> <li>{t("where-to-book.part4")}</li> <li>{t("where-to-book.part5")}</li> <li>{t("where-to-book.part6")}</li> </ul> <p>{t("where-to-book.part7")}</p> <p>{t("where-to-book.part8")}</p> <p>{t("where-to-book.part9")}</p> <p>{t("where-to-book.part10")}</p> <p>{t("where-to-book.part11")}</p> <p>{t("where-to-book.part12")}</p> <p>{t("where-to-book.part13")}</p> </Booking> <Choice title={t("tour-category.title")}> <p>{t("tour-category.part1")}</p> <FakeList>{t("tour-category.part2")}</FakeList> <p>{t("tour-category.part3")}</p> <FakeList>{t("tour-category.part4")}</FakeList> <p>{t("tour-category.part5")}</p> <p>{t("tour-category.part6")}</p> <p>{t("tour-category.part7")}</p> <p>{t("tour-category.part8")}</p> <FakeList>{t("tour-category.part9")}</FakeList> <p>{t("tour-category.part10")}</p> <FakeList>{t("tour-category.part11")}</FakeList> <p>{t("tour-category.part12")}</p> </Choice> <HowMuch> <ul> <li>{t("how-much.part1")}</li> <li>{t("how-much.part2")}</li> <li>{t("how-much.part3")}</li> <li>{t("how-much.part5")}</li> <li>{t("how-much.part6")}</li> </ul> <p>{t("how-much.part7")}</p> <ul> <li>{t("how-much.part8")}</li> <li>{t("how-much.part9")}</li> <li>{t("how-much.part10")}</li> <li>{t("how-much.part11")}</li> <li>{t("how-much.part12")}</li> </ul> <p>{t("how-much.part13")}</p> <p>{t("how-much.part14")}</p> </HowMuch> <Baggage title={t("what-to-bring.title")}> <p>{t("what-to-bring.part1")}</p> <p>{t("what-to-bring.part2")}</p> <p>{t("what-to-bring.part3")}</p> <p>{t("what-to-bring.part4")} </p> </Baggage> <Boat title={t("which-boat.title")}> <p>{t("which-boat.part1")}</p> <GroupOfImages> <ImageAsLandscape> <ElNidoWhichTourImages image="speedboat" /> </ImageAsLandscape> <ImageAsLandscape> <ElNidoWhichTourImages image="boat" /> </ImageAsLandscape> </GroupOfImages> </Boat> <Visit title={t("visit-title")}> <section className="pt3"> <div className="relative tc" css={css` margin-bottom: 1.45rem; `} > <span className="relative dib"> <img ref={ref} src={ElNidoMap} alt="El Nido Tour Map" className="db" css={css` width: 100%; max-width: 700px; object-fit: contain; `} /> <a href="#tour-a" css={css` position: absolute; width: ${270 * ratio}px; height: ${93 * ratio}px; top: ${354 * ratio}px; left: ${234 * ratio}px; z-index: 10; border-radius: ${93 * ratio}px / ${45 * ratio}px; transform: rotate(-25deg); `} /> <a href="#tour-b" css={css` position: absolute; width: ${270 * ratio}px; height: ${130 * ratio}px; top: ${465 * ratio}px; left: ${284 * ratio}px; z-index: 10; border-radius: ${130 * ratio}px / ${65 * ratio}px; transform: rotate(-5deg); `} /> <a href="#tour-c" css={css` position: absolute; width: ${238 * ratio}px; height: ${100 * ratio}px; top: ${215 * ratio}px; left: ${124 * ratio}px; z-index: 10; border-radius: ${100 * ratio}px / ${50 * ratio}px; transform: rotate(-2deg); `} /> <a href="#tour-d" css={css` position: absolute; width: ${170 * ratio}px; height: ${110 * ratio}px; top: ${160 * ratio}px; left: ${340 * ratio}px; z-index: 10; border-radius: ${110 * ratio}px / ${70 * ratio}px; transform: rotate(50deg); `} /> <ApplicationLink to="palawan" css={css` position: absolute; width: ${90 * ratio}px; height: ${60 * ratio}px; top: ${285 * ratio}px; left: ${494 * ratio}px; z-index: 10; border-radius: ${90 * ratio}px / ${60 * ratio}px; `} /> </span> </div> <Divider /> <Anchor id="tour-a" /> <PhilippinesHeadline>{t("tour-a.title")}</PhilippinesHeadline> <Divider /> <CustomTitle>{t("tour-a.big-lagoon.title")}</CustomTitle> <SectionContent> <p>{t("tour-a.big-lagoon.part1")}</p> <p>{t("tour-a.big-lagoon.part2")}</p> <p>{t("tour-a.big-lagoon.part3")}</p> <ImageAsLandscape> <SharedCardPhilippinesImages image="tourA" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-a.secret-lagoon.title")}</CustomTitle> <SectionContent> <p>{t("tour-a.secret-lagoon.part1")}</p> <p>{t("tour-a.secret-lagoon.part2")}</p> <p>{t("tour-a.secret-lagoon.part3")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="secretLagoon" /> </ImageAsLandscape> <ImageAsPortrait> <ElNidoWhichTourImages image="secretLagoon2" /> </ImageAsPortrait> </GroupOfImages> </SectionContent> <Divider /> <CustomTitle>{t("tour-a.shimizu-island.title")}</CustomTitle> <SectionContent> <p>{t("tour-a.shimizu-island.part1")}</p> <p>{t("tour-a.shimizu-island.part2")}</p> <p>{t("tour-a.shimizu-island.part3")}</p> <ImageAsLandscape> <TourAImages image="shimizuIsland" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-a.commando-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-a.commando-beach.part1")}</p> <p>{t("tour-a.commando-beach.part2")}</p> <p>{t("tour-a.commando-beach.part3")}</p> <GroupOfImages> <ImageAsLandscape> <TourAImages image="sevenCommandoBeach" /> </ImageAsLandscape> <ImageAsLandscape> <ElNidoWhichTourImages image="commandoBeach2" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> <Divider /> <CustomTitle>{t("tour-a.snorkeling.title")}</CustomTitle> <SectionContent> <p>{t("snorkeling")}</p> </SectionContent> {tourALinkPublished && ( <SectionContent> <p>{t("tour-a.snorkeling.part1")}</p> </SectionContent> )} </section> <Divider /> <section> <Anchor id="tour-b" /> <PhilippinesHeadline>{t("tour-b.title")}</PhilippinesHeadline> <Divider /> <CustomTitle>{t("tour-b.entalula-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-b.entalula-beach.part1")}</p> <p>{t("tour-b.entalula-beach.part2")}</p> <ImageAsLandscape> <ElNidoWhichTourImages image="entalulaBeach" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-b.snake-island.title")}</CustomTitle> <SectionContent> <p>{t("tour-b.snake-island.part1")}</p> <p>{t("tour-b.snake-island.part2")}</p> <GroupOfImages> <ImageAsLandscape> <ElNidoWhichTourImages image="snakeIsland1" /> </ImageAsLandscape> <ImageAsLandscape> <ElNidoWhichTourImages image="snakeIsland2" /> </ImageAsLandscape> </GroupOfImages> </SectionContent> <Divider /> <CustomTitle>{t("tour-b.pinagbuyutan-island.title")}</CustomTitle> <SectionContent> <p>{t("tour-b.pinagbuyutan-island.part1")}</p> <p>{t("tour-b.pinagbuyutan-island.part2")}</p> <p>{t("tour-b.pinagbuyutan-island.part3")}</p> <p>{t("tour-b.pinagbuyutan-island.part4")}</p> <ImageAsLandscape> <ElNidoWhichTourImages image="pinagbuyutanIsland" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-b.yum-yum-island.title")}</CustomTitle> <SectionContent> <p>{t("tour-b.yum-yum-island.part1")}</p> <ImageAsLandscape> <ElNidoWhichTourImages image="yumyumIsland" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-b.cudugnon-cave.title")}</CustomTitle> <SectionContent> <p>{t("tour-b.cudugnon-cave.part1")}</p> <p>{t("tour-b.cudugnon-cave.part2")}</p> <ImageAsLandscape> <ElNidoWhichTourImages image="cudugnonCave" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-b.snorkeling.title")}</CustomTitle> <SectionContent>{t("snorkeling")}</SectionContent> {tourBLinkPublished && <SectionContent>{t("tour-b.snorkeling.part1")}</SectionContent>} </section> <Divider /> <section> <Anchor id="tour-c" /> <PhilippinesHeadline>{t("tour-c.title")}</PhilippinesHeadline> <Divider /> <CustomTitle>{t("tour-c.helicopter-island.title")}</CustomTitle> <SectionContent> <p>{t("tour-c.helicopter-island.part1")}</p> <p>{t("tour-c.helicopter-island.part2")}</p> <p>{t("tour-c.helicopter-island.part3")}</p> <ImageAsLandscape credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/helicopter-island"> Tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="helicopterIsland" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-c.matinloc-shrine.title")}</CustomTitle> <SectionContent> <p>{t("tour-c.matinloc-shrine.part1")}</p> <p>{t("tour-c.matinloc-shrine.part2")}</p> <p>{t("tour-c.matinloc-shrine.part3")}</p> <p>{t("tour-c.matinloc-shrine.part4")}</p> <ImageAsLandscape credit={ <ExternalLinkNotUnderlined href="https://www.routard.com/photos/philippines/1502975-matinloc_shrine.htm"> Routard </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="matinlocShrine" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-c.secret-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-c.secret-beach.part1")}</p> <p>{t("tour-c.secret-beach.part2")}</p> <p>{t("tour-c.secret-beach.part3")}</p> <ImageAsPortrait credit={ <ExternalLinkNotUnderlined href="https://www.pinterest.fr/pin/333125703680649065/"> cachucha24 </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="secretBeach" /> </ImageAsPortrait> </SectionContent> <Divider /> <CustomTitle>{t("tour-c.star-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-c.star-beach.part1")}</p> <p>{t("tour-c.star-beach.part2")}</p> <p>{t("tour-c.star-beach.part3")}</p> <ImageAsPortrait credit={ <ExternalLinkNotUnderlined href="https://www.travel-palawan.com/?attachment_id=70373"> travel-palawan </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="starBeach" /> </ImageAsPortrait> </SectionContent> <Divider /> <CustomTitle>{t("tour-c.hidden-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-c.hidden-beach.part1")}</p> <p>{t("tour-c.hidden-beach.part2")}</p> <ImageAsPortrait credit={ <ExternalLinkNotUnderlined href="https://www.travel-palawan.com/product/el-nido-tour-c/"> travel-palawan </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="hiddenBeach" /> </ImageAsPortrait> </SectionContent> <Divider /> <CustomTitle>{t("tour-c.snorkeling.title")}</CustomTitle> <SectionContent>{t("snorkeling")}</SectionContent> {tourCLinkPublished && <SectionContent>{t("tour-c.snorkeling.part1")}</SectionContent>} </section> <Divider /> <section> <Anchor id="tour-d" /> <PhilippinesHeadline>{t("tour-d.title")}</PhilippinesHeadline> <Divider /> <CustomTitle>{t("tour-d.ipil-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-d.ipil-beach.part1")}</p> <p>{t("tour-d.ipil-beach.part2")}</p> <p>{t("tour-d.ipil-beach.part3")}</p> <ImageAsPortrait credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/ipil-beach"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="ipilBeach" /> </ImageAsPortrait> </SectionContent> <Divider /> <CustomTitle>{t("tour-d.cadlao-lagoon.title")}</CustomTitle> <SectionContent> <p>{t("tour-d.cadlao-lagoon.part1")}</p> <p>{t("tour-d.cadlao-lagoon.part2")}</p> <p>{t("tour-d.cadlao-lagoon.part3")}</p> <ImageAsLandscape credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/cadlao-island"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="cadlaoIsland" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-d.paradise-beach.title")}</CustomTitle> <SectionContent> <p>{t("tour-d.paradise-beach.part1")}</p> <p>{t("tour-d.paradise-beach.part2")}</p> <p>{t("tour-d.paradise-beach.part3")}</p> <GroupOfImages> <ImageAsLandscapeOnTheRight credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/nat-nat-beach"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="natNatBeach" /> </ImageAsLandscapeOnTheRight> <ImageAsLandscapeOnTheLeft credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/paradise-beach"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="paradiseBeach" /> </ImageAsLandscapeOnTheLeft> <ImageAsLandscapeOnTheRight credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/pasandigan-cove"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="pasandiganCove" /> </ImageAsLandscapeOnTheRight> </GroupOfImages> </SectionContent> <Divider /> <CustomTitle>{t("tour-d.small-lagoon.title")}</CustomTitle> <SectionContent> <p>{t("tour-d.small-lagoon.part1")}</p> <p>{t("tour-d.small-lagoon.part2")}</p> <p>{t("tour-d.small-lagoon.part3")}</p> <ImageAsLandscape credit={ <ExternalLinkNotUnderlined href="https://www.tikigo.com/palawan/palawan/small-lagoon"> tikigo </ExternalLinkNotUnderlined> } > <ElNidoWhichTourImages image="smallLagoon" /> </ImageAsLandscape> </SectionContent> <Divider /> <CustomTitle>{t("tour-d.snorkeling.title")}</CustomTitle> <SectionContent>{t("snorkeling")}</SectionContent> {tourDLinkPublished && <SectionContent>{t("tour-d.snorkeling.part1")}</SectionContent>} </section> </Visit> <Divider /> <Opinion title={t("opinion.title")}> <p>{t("opinion.part1")}</p> <p>{t("opinion.part2")}</p> <p>{t("opinion.part3")}</p> <FakeList> <span className="b">1.</span> {t("opinion.part4")} </FakeList> <p>{t("opinion.part5")}</p> <FakeList> <span className="b">2.</span> {t("opinion.part6")} </FakeList> <p>{t("opinion.part7")}</p> <p>{t("opinion.part8")}</p> <FakeList> <span className="b">3.</span> {t("opinion.part9")} </FakeList> <p>{t("opinion.part10")}</p> <p>{t("opinion.part11")}</p> <FakeList> <span className="b">4.</span> {t("opinion.part12")} </FakeList> <p>{t("opinion.part13")}</p> <p>{t("opinion.part14")}</p> <p>{t("opinion.part15")}</p> </Opinion> <Divider /> <Conclusion> <p>{t("conclusion")}</p> <ul> <li>{t("question1")}</li> <li>{t("question2")}</li> </ul> <p>{t("love")}</p> </Conclusion> <Divider /> <Comments collectionName={namespace} location={location} facebookQuote={`${t("facebook.part1")}\n${t("facebook.part2")}\\n${t("facebook.part3")}`} pinterest={{ description: t("pinterest"), nodes: i18n.languageCode === "fr" ? [ <ElNidoWhichTourImages image="cardFr1" key="cardFr1" />, <ElNidoWhichTourImages image="cardFr2" key="cardFr1" />, ] : [ <ElNidoWhichTourImages image="cardEn1" key="cardEn1" />, <ElNidoWhichTourImages image="cardEn2" key="cardEn1" />, ], }} /> </PhilippinesBlogLayout> </> ) } export default IndexPage