All files / app/form/ext ext.component.ts

36.13% Statements 43/119
14.28% Branches 16/112
31.57% Functions 12/38
37.62% Lines 38/101

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 31467x                                                     67x 67x     67x       67x 67x 67x 67x 67x 67x                                   67x 2x 2x 2x         2x   2x                     2x     2x     2x                   2x 2x 2x 2x       2x 2x                 40x                 5x       5x       5x                                                                                 5x       5x       5x       5x                                                                                                                                                                                         1x 1x                         1x                       1x           1x            
import { CdkDropListGroup } from '@angular/cdk/drag-drop';
import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  forwardRef,
  Input,
  OnDestroy,
  Output,
  ViewChild
} from '@angular/core';
import {
  FormArray,
  FormControl,
  ReactiveFormsModule,
  UntypedFormBuilder,
  UntypedFormControl,
  UntypedFormGroup,
  Validators
} from '@angular/forms';
import { RouterLink } from '@angular/router';
import { FormlyFieldConfig, FormlyForm, FormlyFormOptions } from '@ngx-formly/core';
import { cloneDeep, defer, uniq } from 'lodash-es';
import { DateTime } from 'luxon';
import { catchError, of, Subject, takeUntil } from 'rxjs';
import { v4 as uuid } from 'uuid';
import { LoadingComponent } from '../../component/loading/loading.component';
import { RefComponent } from '../../component/ref/ref.component';
import { Ext } from '../../model/ext';
import { Ref } from '../../model/ref';
import { getMailbox } from '../../mods/mailbox';
import { AdminService } from '../../service/admin.service';
import { RefService } from '../../service/api/ref.service';
import { Store } from '../../store/store';
import { TAG_REGEX } from '../../util/format';
import { convertFilter, convertSort, defaultDesc, negatable, toggle, UrlFilter } from '../../util/query';
import { hasPrefix } from '../../util/tag';
import { EditorComponent } from '../editor/editor.component';
import { linksForm } from '../links/links.component';
import { themesForm, ThemesFormComponent } from '../themes/themes.component';
 
@Component({
  selector: 'app-ext-form',
  templateUrl: './ext.component.html',
  styleUrls: ['./ext.component.scss'],
  host: { 'class': 'nested-form' },
  imports: [
    forwardRef(() => RefComponent),
    forwardRef(() => EditorComponent),
    ReactiveFormsModule,
    FormlyForm,
    CdkDropListGroup,
    RouterLink,
    ThemesFormComponent,
    LoadingComponent,
  ],
})
export class ExtFormComponent implements OnDestroy {
  private destroy$ = new Subject<void>();
  allSorts = this.admin.refSorts.map(convertSort);
  allFilters = this.admin.filters.map(convertFilter);
 
  @Input()
  group!: UntypedFormGroup;
  @Input()
  showClear = false;
  @Output()
  clear = new EventEmitter<void>();
 
  @ViewChild('fillPopover')
  fillPopover?: ElementRef;
  @ViewChild('fillSidebar')
  fillSidebar?: ElementRef;
  @ViewChild('mainFormlyForm')
  mainFormlyForm?: FormlyForm;
  @ViewChild('advancedFormlyForm')
  advancedFormlyForm?: FormlyForm;
 
  id = 'ext-' + uuid();
  form?: FormlyFieldConfig[];
  advancedForm?: FormlyFieldConfig[];
  loadingDefaults = false;
  defaults?: Ref;
 
  options: FormlyFormOptions = {
    formState: {
      admin: this.admin,
      config: { }
    }
  };
 
  private tag?: string;
 
  constructor(
    public admin: AdminService,
    public store: Store,
    private refs: RefService,
    private cd: ChangeDetectorRef,
  ) { }
 
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
 
  get user() {
    if (!this.admin.getTemplate('user')) return false;
    return hasPrefix(this.group.get('tag')!.value, 'user');
  }
 
  get config() {
    return this.group.get('config') as UntypedFormGroup;
  }
 
  get inbox() {
    if (!this.admin.getPlugin('plugin/inbox')) return null;
    return getMailbox(this.group.get('tag')!.value, this.store.account.origin);
  }
 
  get modmail() {
    return this.config.get('modmail') as FormControl<boolean>;
  }
 
  get defaultSort() {
    return this.config.get('defaultSort') as FormArray<FormControl<string>>;
  }
 
  get defaultFilter() {
    return this.config.get('defaultFilter') as FormArray<FormControl<string>>;
  }
 
  get sortCol() {
    if (!this.defaultSort.value?.[0]) return undefined;
    if (!this.defaultSort.value[0].includes(',')) return this.defaultSort.value[0];
    return this.defaultSort.value[0].split(',')[0];
  }
 
  get sortDir() {
    if (!this.defaultSort.value?.[0]) return undefined;
    if (!this.defaultSort.value[0].includes(',')) return defaultDesc(this.defaultSort.value[0]) ? 'DESC' : 'ASC';
    return this.defaultSort.value[0].split(',')[1].toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
  }
 
  get filter(): UrlFilter | undefined {
    return this.defaultFilter.value[0] as UrlFilter;
  }
 
  setSortCol(value: string) {
    this.defaultSort.setValue([value + ',' + this.sortDir]);
  }
 
  setSortDir(value: string) {
    this.defaultSort.setValue([this.sortCol + ',' + value]);
  }
 
  setFilter(value: string | null) {
    if (value) {
      this.defaultFilter.setValue([value]);
    } else {
      this.defaultFilter.setValue([]);
    }
  }
 
  toggleFilter() {
    if (!this.filter) return;
    this.defaultFilter.setValue([toggle(this.filter)]);
  }
 
  get sidebar() {
    return this.config.get('sidebar') as UntypedFormControl;
  }
 
  get popover() {
    return this.config.get('popover') as UntypedFormControl;
  }
 
  get themes() {
    return this.config.get('themes') as UntypedFormGroup;
  }
 
  get userTheme() {
    return this.config.get('userTheme') as UntypedFormGroup;
  }
 
  get themeValues() {
    return uniq([...Object.keys(this.themes?.value || {}), ...this.admin.themes.flatMap(p => Object.keys(p.config?.themes || {}))]);
  }
 
  get userThemeValues() {
    return uniq([...Object.keys(this.themes?.value || {}), ...this.admin.themes.flatMap(p => Object.keys(p.config?.themes || {}))]);
  }
 
  get pinned() {
    return this.config.get('pinned') as UntypedFormControl;
  }
 
  negatable(filter: string) {
    return negatable(filter);
  }
 
  setValue(ext: Ext) {
    this.tag = ext.tag;
    if (ext.config?.defaults) {
      this.loadingDefaults = true;
      this.refs.getCurrent('tag:/' + ext.tag)
        .subscribe(ref => {
          this.defaults = ref;
          this.loadingDefaults = false;
        });
    }
    if (!this.form) {
      this.form = cloneDeep(this.admin.getTemplateForm(ext.tag));
    }
    if (!this.advancedForm) {
      this.advancedForm = cloneDeep(this.admin.getTemplateAdvancedForm(ext.tag));
    }
    this.setModel(ext);
  }
 
  private setModel(ext: Ext) {
    if (!this.mainFormlyForm || !this.advancedFormlyForm) {
      this.cd.markForCheck();
      defer(() => this.setModel(ext));
      return;
    }
    this.group!.patchValue(ext);
    this.options.formState.config = ext.config;
    this.mainFormlyForm!.model = ext.config;
    // TODO: Why aren't changed being detected?
    // @ts-ignore
    this.mainFormlyForm.builder.build(this.mainFormlyForm.field);
    if (this.advancedFormlyForm) {
      this.advancedFormlyForm!.model = ext.config;
      // TODO: Why aren't changed being detected?
      // @ts-ignore
      this.advancedFormlyForm.builder.build(this.advancedFormlyForm.field);
    }
    this.config.valueChanges.pipe(
      takeUntil(this.destroy$),
    ).subscribe(value => {
      if (value.defaults) {
        if (!this.defaults) this.createDefaults();
      } else {
        delete this.defaults;
        this.loadingDefaults = false;
      }
    });
    this.cd.markForCheck();
  }
 
  createDefaults() {
    this.loadingDefaults = true;
    this.refs.getCurrent('tag:/' + this.tag).pipe(
      catchError(err => {
        this.defaults = {
          origin: this.store.account.origin,
          url: 'tag:/' + this.tag,
          tags: ['internal', this.store.account.localTag],
          created: DateTime.now(),
          published: DateTime.now(),
          modified: DateTime.now(),
        };
        this.refs.create(this.defaults).subscribe(cursor => this.defaults!.modifiedString = cursor);
        return of(this.defaults);
      })
    ).subscribe(ref => {
      if (!this.loadingDefaults) return;
      this.defaults = ref;
      this.loadingDefaults = false;
    });
  }
}
 
export function extForm(fb: UntypedFormBuilder, ext: Ext | undefined, admin: AdminService, locked: boolean) {
  let configControls = {};
  Iif (admin.getTemplate('') && !hasPrefix(ext?.tag, 'config')) {
    configControls = {
      ...configControls,
      defaultSort: [[]],
      defaultFilter: [[]],
      sidebar: [''],
      popover: [''],
      modmail: [false],
      pinned: linksForm(fb, ext?.config?.pinned || []),
      themes: themesForm(fb, ext?.config?.themes || []),
      theme: [''],
    };
  }
  Iif (admin.home && hasPrefix(ext?.tag, 'config/home')) {
    configControls = {
      ...configControls,
      defaultSort: [[]],
      defaultFilter: [[]],
      sidebar: [''],
      modmail: [false],
      pinned: linksForm(fb, ext?.config?.pinned || []),
      themes: themesForm(fb, ext?.config?.themes || []),
      theme: [''],
    };
  }
  Iif (admin.getTemplate('user') && hasPrefix(ext?.tag, 'user')) {
    configControls = {
      ...configControls,
      userTheme: [''],
    };
  }
  return fb.group({
    tag: [{value: '', disabled: locked}, [Validators.required, Validators.pattern(TAG_REGEX)]],
    name: [''],
    config: fb.group(configControls),
  });
}