<commit_before>import { Component, OnInit, Compiler, Injector, ViewContainerRef, ViewChild, Inject, ComponentRef, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpBackend, HttpRequest, HttpEvent } from '@angular/common/http';
import { HttpTestingController, TestRequest } from '@angular/common/http/testing';
import { CodeExampleComponent } from './code-example/code-example.component';
import { Observable } from 'rxjs/Observable';
import { updateProperty } from 'typescript';
import { AppData } from '../../app.model';

@Component({
    selector: 'ui-jar-example-item',
    template: `
        <div class="example-top-bar">
            <h2>{{_example.title}}</h2>
            <button class="view-source-btn" (click)="toggleViewSource()" title="View source">
                <svg width="23" height="11" xmlns="http://www.w3.org/2000/svg">
                    <g>
                        <path d="M 7.6115221,10.08469 1.9751419,5.5563165 7.6115221,0.8834201 2.0233161,5.5563165 z" 
                            style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
                        <path d="m 15.397052,10.08469 5.63638,-4.5283735 -5.63638,-4.6728964 5.588205,4.6728964 z" 
                            style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
                    </g>
                </svg>
            </button>
        </div>
        <ui-jar-code-example [sourceCode]="exampleSourceCode"></ui-jar-code-example>
        <div class="example-container">
            <div #example></div>
        </div>
    `
})
export class ExampleItemComponent implements OnInit {
    @ViewChild('example', { read: ViewContainerRef }) content: ViewContainerRef;
    @ViewChild(CodeExampleComponent) codeExampleComponent: CodeExampleComponent;
    private modules: any = [];
    _example: ExampleProperties;
    exampleSourceCode: string = '';

    @Input()
    set example(value: any) {
        this._example = value;
    }

    constructor(private compiler: Compiler,
                private parentInjector: Injector,
                private activatedRoute: ActivatedRoute,
                @Inject('AppData') private appData: AppData) { }

    ngOnInit(): void {
        this.modules = this.appData.modules;
        this.createView();
    }

    private getCurrentComponentName(): string {
        const lastUrlSegmentIndex = this.activatedRoute.snapshot.pathFromRoot[0].firstChild.url.length - 1;
        return this.activatedRoute.snapshot.pathFromRoot[0].firstChild.url[lastUrlSegmentIndex].path;
    }

    private getComponentModuleImports(componentKey: string) {
        const dependencies = this.appData.components[decodeURI(componentKey)].moduleDependencies;
        let imports = [];

        dependencies.forEach((moduleName) => {
            this.modules.forEach((moduleDetails) => {
                if (moduleName === moduleDetails.name) {
                    imports.push(moduleDetails.moduleRef);
                }
            });
        });

        return imports;
    }

    private getBootstrapComponentRef(componentKey: string) {
        const bootstrapComponent = this._example.bootstrapComponent;

        const componentDetails = this.appData.componentRefs.find((componentDetails) => {
            return bootstrapComponent === componentDetails.name;
        });

        if(componentDetails) {
            return componentDetails.componentRef;
        }
    }

    private createView() {
        this.codeExampleComponent.hide();
        this.createComponent();
    }

    toggleViewSource() {
        if (this.codeExampleComponent.isComponentVisible()) {
            this.codeExampleComponent.hide();
        } else {
            this.codeExampleComponent.show();
        }
    }

    private createComponent() {
        this.cleanUp();

        const componentName = this.getCurrentComponentName();
        const componentFactory = this.getBootstrapComponentFactory(componentName);
        const componentRef = this.content.createComponent(componentFactory);

        this.listenOnHttpRequests(componentRef.injector, this._example.httpRequests);
        this.setComponentProperties(componentRef, this._example.componentProperties);
        this.setExampleSourceCode(componentRef, this._example.sourceCode);
    }

    private setExampleSourceCode(componentRef: ComponentRef<any>, sourceCode: string) {
        let modifiedSourceCodeSplit = sourceCode.split(/\)[\n\s\t\r]+class|\)[\n\s\t\r]+export\sclass/);

        if(modifiedSourceCodeSplit.length > 1) {
            const componentKeys = Object.keys(componentRef.instance).concat(Object.keys(Object.getPrototypeOf(componentRef.instance)));
            const uniqueComponentProperties = Array.from(new Set(componentKeys));
            const propertyNamesInExample = uniqueComponentProperties.filter((propertyName) => {
                return new RegExp('="(?:[\\w\\s]+)?'+ propertyName +'(?:\.|\\[)?(?:.+)?"|\{\{(?:\.|\\[["\'])?'+ propertyName +'(?:\.|["\']\\])?(?:.+)?\}\}', 'i').test(modifiedSourceCodeSplit[0]);
            });

            try {
                const jsonValues = [];
                const jsonReplacer = (key, value) => {
                    if(value !== null && typeof value === 'object') {
                        if(jsonValues.includes(value)) {
                            return;
                        }

                        jsonValues.push(value);
                    }

                    return value;
                };

                let classProperties = propertyNamesInExample.reduce((result, currentKey) => {
                    if(typeof componentRef.instance[currentKey] === 'function'){
                        result += `  ${currentKey} = ${componentRef.instance[currentKey]};\n`;    
                    } else {
                        result += `  ${currentKey} = ${JSON.stringify(componentRef.instance[currentKey], jsonReplacer)};\n`;
                    }
                    return result;
                }, '');

                classProperties = `{\n${classProperties}}`;

                modifiedSourceCodeSplit[1] = modifiedSourceCodeSplit[1].slice(0, modifiedSourceCodeSplit[1].indexOf('{')) + classProperties;
            } catch(error) {
                console.error(error);
            }
        }

        this.exampleSourceCode = modifiedSourceCodeSplit.join(')\nclass');
    }<commit_msg>Small fix on display value to #24<commit_after>import { Component, OnInit, Compiler, Injector, ViewContainerRef, ViewChild, Inject, ComponentRef, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpBackend, HttpRequest, HttpEvent } from '@angular/common/http';
import { HttpTestingController, TestRequest } from '@angular/common/http/testing';
import { CodeExampleComponent } from './code-example/code-example.component';
import { Observable } from 'rxjs/Observable';
import { updateProperty } from 'typescript';
import { AppData } from '../../app.model';

@Component({
    selector: 'ui-jar-example-item',
    template: `
        <div class="example-top-bar">
            <h2>{{_example.title}}</h2>
            <button class="view-source-btn" (click)="toggleViewSource()" title="View source">
                <svg width="23" height="11" xmlns="http://www.w3.org/2000/svg">
                    <g>
                        <path d="M 7.6115221,10.08469 1.9751419,5.5563165 7.6115221,0.8834201 2.0233161,5.5563165 z" 
                            style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
                        <path d="m 15.397052,10.08469 5.63638,-4.5283735 -5.63638,-4.6728964 5.588205,4.6728964 z" 
                            style="fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:2;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none" />
                    </g>
                </svg>
            </button>
        </div>
        <ui-jar-code-example [sourceCode]="exampleSourceCode"></ui-jar-code-example>
        <div class="example-container">
            <div #example></div>
        </div>
    `
})
export class ExampleItemComponent implements OnInit {
    @ViewChild('example', { read: ViewContainerRef }) content: ViewContainerRef;
    @ViewChild(CodeExampleComponent) codeExampleComponent: CodeExampleComponent;
    private modules: any = [];
    _example: ExampleProperties;
    exampleSourceCode: string = '';

    @Input()
    set example(value: any) {
        this._example = value;
    }

    constructor(private compiler: Compiler,
                private parentInjector: Injector,
                private activatedRoute: ActivatedRoute,
                @Inject('AppData') private appData: AppData) { }

    ngOnInit(): void {
        this.modules = this.appData.modules;
        this.createView();
    }

    private getCurrentComponentName(): string {
        const lastUrlSegmentIndex = this.activatedRoute.snapshot.pathFromRoot[0].firstChild.url.length - 1;
        return this.activatedRoute.snapshot.pathFromRoot[0].firstChild.url[lastUrlSegmentIndex].path;
    }

    private getComponentModuleImports(componentKey: string) {
        const dependencies = this.appData.components[decodeURI(componentKey)].moduleDependencies;
        let imports = [];

        dependencies.forEach((moduleName) => {
            this.modules.forEach((moduleDetails) => {
                if (moduleName === moduleDetails.name) {
                    imports.push(moduleDetails.moduleRef);
                }
            });
        });

        return imports;
    }

    private getBootstrapComponentRef(componentKey: string) {
        const bootstrapComponent = this._example.bootstrapComponent;

        const componentDetails = this.appData.componentRefs.find((componentDetails) => {
            return bootstrapComponent === componentDetails.name;
        });

        if(componentDetails) {
            return componentDetails.componentRef;
        }
    }

    private createView() {
        this.codeExampleComponent.hide();
        this.createComponent();
    }

    toggleViewSource() {
        if (this.codeExampleComponent.isComponentVisible()) {
            this.codeExampleComponent.hide();
        } else {
            this.codeExampleComponent.show();
        }
    }

    private createComponent() {
        this.cleanUp();

        const componentName = this.getCurrentComponentName();
        const componentFactory = this.getBootstrapComponentFactory(componentName);
        const componentRef = this.content.createComponent(componentFactory);

        this.listenOnHttpRequests(componentRef.injector, this._example.httpRequests);
        this.setComponentProperties(componentRef, this._example.componentProperties);
        this.setExampleSourceCode(componentRef, this._example.sourceCode);
    }

    private setExampleSourceCode(componentRef: ComponentRef<any>, sourceCode: string) {
        let modifiedSourceCodeSplit = sourceCode.split(/\)[\n\s\t\r]+class|\)[\n\s\t\r]+export\sclass/);

        if(modifiedSourceCodeSplit.length > 1) {
            const componentKeys = Object.keys(componentRef.instance).concat(Object.keys(Object.getPrototypeOf(componentRef.instance)));
            const uniqueComponentProperties = Array.from(new Set(componentKeys));
            const propertyNamesInExample = uniqueComponentProperties.filter((propertyName) => {
                return new RegExp('="(?:[\\w\\s]+)?'+ propertyName +'(?:\.|\\[)?(?:.+)?"|\{\{(?:\.|\\[["\'])?'+ propertyName +'(?:\.|["\']\\])?(?:.+)?\}\}', 'i').test(modifiedSourceCodeSplit[0]);
            });

            try {
                const jsonValues = [];
                const jsonReplacer = (key, value) => {
                    if(value !== null && typeof value === 'object') {
                        if(jsonValues.includes(value)) {
                            return;
                        }

                        jsonValues.push(value);
                    }

                    return value;
                };

                let classProperties = propertyNamesInExample.reduce((result, currentKey) => {
                    if(typeof componentRef.instance[currentKey] === 'function'){
                        result += `  ${currentKey}${componentRef.instance[currentKey]};\n`.replace('function', '');
                    } else {
                        result += `  ${currentKey} = ${JSON.stringify(componentRef.instance[currentKey], jsonReplacer)};\n`;
                    }
                    return result;
                }, '');

                classProperties = `{\n${classProperties}}`;

                modifiedSourceCodeSplit[1] = modifiedSourceCodeSplit[1].slice(0, modifiedSourceCodeSplit[1].indexOf('{')) + classProperties;
            } catch(error) {
                console.error(error);
            }
        }

        this.exampleSourceCode = modifiedSourceCodeSplit.join(')\nclass');
    }
{'fraction_non_alphanumeric': 0.13468064248548375, 'fraction_numerical': 0.0262423648291984, 'mean_word_length': 2.403130613292276, 'pattern_counts': {'":': 0, '<': 41, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6342185', 'n_tokens_mistral': 3806, 'n_tokens_neox': 3471, 'n_words': 543}