Skip to content

Commit

Permalink
fix(docs): add button for view demos with Stackblitz
Browse files Browse the repository at this point in the history
  • Loading branch information
alyleui committed Sep 5, 2018
1 parent 9631322 commit 188f3a4
Show file tree
Hide file tree
Showing 2 changed files with 180 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/app/demo-view/view/view.component.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<div [elevation]="3" shadowColor="background:secondary" bg="background:tertiary">
<div class="code">
<!-- <a ly-icon-button routerLink="stackblitz" target="_blank"><ly-icon>launch</ly-icon></a> -->
<a ly-icon-button (click)="openPostStackblitz()" target="_blank"><ly-icon>launch</ly-icon></a>
<button ly-icon-button (click)="toggleCode()"><ly-icon src="assets/svg/code"></ly-icon></button>
</div>
<ly-tabs *ngIf="hasCode">
Expand Down
191 changes: 179 additions & 12 deletions src/app/demo-view/view/view.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@ import {
VERSION,
isDevMode
} from '@angular/core';
import { Observable, of, merge } from 'rxjs';
import { Observable, of, merge, forkJoin } from 'rxjs';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { catchError, retry, tap } from 'rxjs/operators';
import { catchError, retry } from 'rxjs/operators';
import { Platform, AUI_VERSION, LyTheme2 } from '@alyle/ui';

const MODULE_REGEXP = /export\sclass\s([\w]+)/;
const EXPORTS_REGEXP = /exports\:\s?\[[\w]+\]\,?([\s]+)?/;
const IMPORTS_POINT_REGEXP = /imports\:?(?:[\s]+)?\[(?:[\s]+)?/;
const DECLARATIONS_REGEXP = /declarations: \[\:?(?:[\s]+)?([\w]+)(?:[\s]+)?\]/;
const SELECTOR_REGEXP = /selector: \'([\w-]+)\'/;
const SELECTOR_APP = 'my-app';

const styles = {
codeContainer: {
Expand Down Expand Up @@ -68,7 +74,7 @@ export class ViewComponent implements OnInit {
const url = this.url(index);
const getUrl = this.http.get(url, { responseType: 'text' })
.pipe(
retry(10),
retry(3),
catchError((err: HttpErrorResponse) => of(`Error: ${err.statusText}`))
);
if (Platform.isBrowser) {
Expand All @@ -86,6 +92,167 @@ export class ViewComponent implements OnInit {
return `${host}/${fileName}.${file.type}.${file.ext}`;
}

openPostStackblitz() {
const data = forkJoin(
this.http.get(this.url(0), { responseType: 'text' }),
this.http.get(this.url(1), { responseType: 'text' }),
this.http.get(this.url(2), { responseType: 'text' }),
);
data.subscribe(([res1, res2, res3]) => {
const otherModules = `/** Angular */
import { BrowserModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
/** Alyle UI */
import { LyThemeModule, LyCommonModule, LyThemeConfig, LY_THEME_CONFIG, LyHammerGestureConfig } from '@alyle/ui';
import { MinimaTheme } from '@alyle/ui/themes/minima';
`;
const AppModule = otherModules + res3.replace(MODULE_REGEXP, (str, token) => {
return str
.replace(token, 'AppModule');
}).replace(EXPORTS_REGEXP, '')
.replace(IMPORTS_POINT_REGEXP, (str) => {
return str + `BrowserModule,
BrowserAnimationsModule,
LyThemeModule.setTheme('minima-dark'),
`;
}).replace(DECLARATIONS_REGEXP, (str, token) => {
return `bootstrap: [${token}],
providers: [
{
provide: HAMMER_GESTURE_CONFIG,
useClass: LyHammerGestureConfig
},
{
provide: LY_THEME_CONFIG,
useClass: MinimaTheme
}
],` + str;
});

const appComponentTs = res2.replace(SELECTOR_REGEXP, (str, token) => str.replace(token, SELECTOR_APP));
this.makeForm([res1, appComponentTs, AppModule]);
});
}

makeForm([res1, res2, res3]) {
const form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('target', '_blank');
form.setAttribute('action', 'https://run.stackblitz.com/api/angular/v1/');
const name = this.path.split('/').reverse()[0];
const title = name.replace(/-/g, ' ') + ' | Alyle UI';
const payload: {
files: {[path: string]: string};
title: string;
description: string;
template: 'angular-cli' | 'create-react-app' | 'typescript' | 'javascript';
tags?: string[];
dependencies?: {[name: string]: string};
settings?: {
compile?: {
trigger?: 'auto' | 'keystroke' | 'save';
action?: 'hmr' | 'refresh';
clearConsole?: boolean;
};
};
} = {
files: {
[`app/${name}.component.html`]: res1,
[`app/${name}.component.ts`]: res2,
[`app/app.module.ts`]: res3,
'main.ts': (
`import './polyfills';\n` +
`import { BrowserModule } from '@angular/platform-browser';\n` +
`import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n` +
`import { AppModule } from './app/app.module';\n` +
`\n` +
`platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {\n` +
` // Ensure Angular destroys itself on hot reloads.\n` +
` if (window['ngRef']) {\n` +
` window['ngRef'].destroy();\n` +
` }\n` +
` window['ngRef'] = ref;\n` +
`\n` +
` // Otherwise, log the boot error\n` +
`}).catch(err => console.error(err));`
),
'polyfills.ts': (
`import 'core-js/es6/reflect';\nimport 'core-js/es7/reflect';\nimport 'zone.js/dist/zone';\nimport 'hammerjs';\nimport 'web-animations-js';\n`
),
'index.html': (
`<link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet">\n` +
`<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">\n` +
`<${SELECTOR_APP}></${SELECTOR_APP}>`
)
},
title,
description: title,
template: 'angular-cli',
dependencies: {
'@alyle/ui': AUI_VERSION,
'@angular/core': VERSION.full,
'@angular/common': VERSION.full,
'@angular/forms': VERSION.full,
'@angular/http': VERSION.full,
'@angular/animations': VERSION.full,
'@angular/platform-browser': VERSION.full,
'@angular/compiler': VERSION.full,
'@angular/platform-browser-dynamic': VERSION.full,
'chroma-js': 'latest',
'web-animations-js': 'latest',
'core-js': 'latest',
'zone.js': 'latest',
'rxjs': 'latest',
'hammerjs': (window as any).Hammer.VERSION
},
settings: {
compile: {
action: 'refresh',
clearConsole: false
}
}
};

for (const key in payload) {
if (payload.hasOwnProperty(key)) {
let input;
const element = payload[key];
if (typeof element === 'string') {
input = this.createHiddenField(`[${key}]`, element);
form.appendChild(input);
} else if (key === 'files') {
Object.keys(element).forEach(_ => {
input = this.createHiddenField(`[${key}][${_}]`, element[_]);
form.appendChild(input);
});
} else {
input = this.createHiddenField(`[${key}]`, JSON.stringify(element));
form.appendChild(input);
}
}
}

console.log(payload);

document.body.appendChild(form);
const btn = document.createElement('input');
btn.setAttribute('type', 'submit');
form.appendChild(btn);
// form.submit();
btn.click();
// document.body.removeChild(form);
}

createHiddenField(name: string, value: string) {
const field = document.createElement('input');
field.setAttribute('type', 'hidden');
field.setAttribute('value', value);
field.setAttribute('name', name);
return field;
}

openStackblitz() {
const payload = {
files: {
Expand All @@ -110,16 +277,16 @@ export class ViewComponent implements OnInit {
// newWindow: true
// });
// this.http.post('https://run.stackblitz.com/api/angular/v1/', payload).pipe(take(1)).subscribe();
const newWindow = window.open(`/api`, `_blank`);
this.getFile(2).pipe(
tap(next => {
if (this.getModules(next).length) {
console.log(this.getModules(next));
// const newWindow = window.open(`/api`, `_blank`);
// this.getFile(2).pipe(
// tap(next => {
// if (this.getModules(next).length) {
// console.log(this.getModules(next));

newWindow.document.write(this._payload(this.getModules(next)));
}
})
).subscribe();
// newWindow.document.write(this._payload(this.getModules(next)));
// }
// })
// ).subscribe();
}

getModules(str: string) {
Expand Down

0 comments on commit 188f3a4

Please sign in to comment.