All files / app/formly code.type.ts

10.34% Statements 3/29
30% Branches 6/20
20% Functions 1/5
9.09% Lines 2/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 7511x                                                                           11x                                                                        
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FieldType, FieldTypeConfig, FormlyAttributes, FormlyFieldProps } from '@ngx-formly/core';
import { autorun, IReactionDisposer } from 'mobx';
import { MonacoEditorModule } from 'ngx-monaco-editor';
import { ResizeHandleDirective } from '../directive/resize-handle.directive';
import { ConfigService } from '../service/config.service';
import { Store } from '../store/store';
 
interface CodeProps extends FormlyFieldProps {
  /**
   * Monaco language id, such as javascript, python, css, html or json.
   */
  language?: string;
}
 
@Component({
  selector: 'formly-field-code',
  host: { 'class': 'field code-editor' },
  template: `
    @defer {
      <ngx-monaco-editor [formControl]="formControl"
                         [options]="editorOptions"
                         [formlyAttributes]="field"
                         [style.width]="'min(900px, 50vw)'"
                         [style.height]="'min(300px, 90vh)'"
                         appResizeHandle
                         [hitArea]="config.mobile ? 48 : 20"></ngx-monaco-editor>
    }
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    ReactiveFormsModule,
    FormlyAttributes,
    MonacoEditorModule,
    ResizeHandleDirective,
  ],
})
export class FormlyFieldCode extends FieldType<FieldTypeConfig<CodeProps>> implements OnDestroy {
 
  private disposers: IReactionDisposer[] = [];
  private dark = false;
 
  constructor(
    public config: ConfigService,
    private store: Store,
    private cd: ChangeDetectorRef,
  ) {
    super();
    this.disposers.push(autorun(() => {
      this.dark = store.darkTheme;
      this.cd.markForCheck();
    }));
  }
 
  get editorOptions() {
    const language = this.props.language || 'javascript';
    const theme = this.dark ? 'vs-dark' : 'vs';
    if (this._options?.language !== language || this._options?.theme !== theme) {
      this._options = {
        language,
        theme,
        automaticLayout: true,
      };
    }
    return this._options;
  }
  private _options?: any;
 
  ngOnDestroy() {
    for (const dispose of this.disposers) dispose();
    this.disposers.length = 0;
  }
}