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

32.41% Statements 47/145
16.66% Branches 11/66
21.21% Functions 7/33
30.7% Lines 39/127

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  1x                         1x 1x 1x 1x 1x     1x         1x 1x 1x 1x                                 3x 1x 1x         1x 1x 1x 1x 1x 1x     1x   1x           1x     1x 1x 1x 1x 1x 1x   1x 1x                   1x 1x 1x 1x 1x                                                                               1x 1x       1x                                                                                                                                                                                                                                                                          
import { HttpErrorResponse } from '@angular/common/http';
import { Component, HostBinding, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {
  ReactiveFormsModule,
  UntypedFormBuilder,
  UntypedFormControl,
  UntypedFormGroup,
  Validators
} from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { defer, isObject } from 'lodash-es';
import { autorun, IReactionDisposer, runInAction } from 'mobx';
import { MobxAngularModule } from 'mobx-angular';
import { catchError, of, Subscription, switchMap, throwError } from 'rxjs';
import { LoadingComponent } from '../../component/loading/loading.component';
import { SelectTemplateComponent } from '../../component/select-template/select-template.component';
import { SettingsComponent } from '../../component/settings/settings.component';
import { LimitWidthDirective } from '../../directive/limit-width.directive';
import { extForm, ExtFormComponent } from '../../form/ext/ext.component';
import { HasChanges } from '../../guard/pending-changes.guard';
import { Ext } from '../../model/ext';
import { isDeletorTag, tagDeleteNotice } from '../../mods/delete';
import { AdminService } from '../../service/admin.service';
import { ExtService } from '../../service/api/ext.service';
import { ModService } from '../../service/mod.service';
import { Store } from '../../store/store';
import { scrollToFirstInvalid } from '../../util/form';
import { TAG_SUFFIX_REGEX } from '../../util/format';
import { printError } from '../../util/http';
import { access, hasPrefix, localTag, prefix } from '../../util/tag';
 
@Component({
  selector: 'app-ext-page',
  templateUrl: './ext.component.html',
  styleUrls: ['./ext.component.scss'],
  imports: [
    MobxAngularModule,
    RouterLink,
    SettingsComponent,
    ReactiveFormsModule,
    SelectTemplateComponent,
    LoadingComponent,
    LimitWidthDirective,
    ExtFormComponent,
  ],
})
export class ExtPage implements OnInit, OnDestroy, HasChanges {
  private disposers: IReactionDisposer[] = [];
  @HostBinding('class') css = 'full-page-form';
 
  @ViewChild('form')
  form?: ExtFormComponent;
 
  template = '';
  created = false;
  submitted = false;
  invalid = false;
  overwritten = false;
  overwrite = false;
  extForm: UntypedFormGroup;
  editForm!: UntypedFormGroup;
  serverError: string[] = [];
 
  templates = this.admin.tmplSubmit;
 
  creating?: Subscription;
  editing?: Subscription;
  deleting?: Subscription;
 
  private overwrittenModified? = '';
 
  constructor(
    private mod: ModService,
    private admin: AdminService,
    public router: Router,
    public store: Store,
    private exts: ExtService,
    private fb: UntypedFormBuilder,
  ) {
    mod.setTitle($localize`Edit Tag`);
    this.extForm = fb.group({
      tag: ['', [Validators.pattern(TAG_SUFFIX_REGEX)]],
    });
  }
 
  saveChanges() {
    return !this.editForm?.dirty;
  }
 
  ngOnInit(): void {
    this.disposers.push(autorun(() => {
      if (!this.store.view.tag) {
        this.template = '';
        this.tag.setValue('');
        runInAction(() => this.store.view.exts = []);
      } else E{
        const tag = this.store.view.localTag + this.store.account.origin;
        this.exts.get(tag).pipe(
          catchError(() => of(undefined)),
        ).subscribe(ext => this.setExt(tag, ext));
      }
    }));
  }
 
  setExt(tag: string, ext?: Ext) {
    tag = localTag(tag);
    runInAction(() => this.store.view.exts = ext ? [ext] : []);
    if (ext) {
      this.editForm = extForm(this.fb, ext, this.admin, true);
      this.editForm.patchValue(ext);
      defer(() => this.form!.setValue(ext));
    } else {
      for (const t of this.templates) {
        if (hasPrefix(tag, t.tag)) {
          this.template = t.tag;
          this.tag.setValue(access(tag) + tag.substring(t.tag.length + access(tag).length + 1))
          return;
        }
      }
      if (tag) {
        const template = this.admin.getTemplate(tag);
        if (template?.config?.submit) {
          this.templates.unshift(template);
          this.template = tag;
          this.tag.setValue('')
          return;
        }
      }
      this.template = '';
      this.tag.setValue(tag);
    }
  }
 
  ngOnDestroy() {
    for (const dispose of this.disposers) dispose();
    this.disposers.length = 0;
  }
 
  get tag() {
    return this.extForm.get('tag') as UntypedFormControl;
  }
 
  prefix(tag: string) {
    if (!this.template) return tag;
    if (!tag) return this.template;
    if (access(this.template) && access(tag)) tag = tag.substring(access(tag).length);
    return prefix(this.template, tag);
  }
 
  validate(input: HTMLInputElement) {
    if (this.tag.touched) {
      if (this.tag.errors?.['pattern']) {
        input.setCustomValidity($localize`
          Tags must be lower case letters, numbers, periods and forward slashes.
          Must not start with a forward slash or period.
          Must not or contain two forward slashes or periods in a row.
          Protected tags start with a plus sign.
          Private tags start with an underscore.
          (i.e. "science", "my/tag", or "_my/private/tag")`);
        input.reportValidity();
      }
    }
  }
 
  create() {
    this.serverError = [];
    this.submitted = true;
    this.extForm.markAllAsTouched();
    if (!this.extForm.valid) {
      scrollToFirstInvalid();
      return;
    }
    const prefixed = this.prefix(this.tag.value);
    const tag = prefixed + this.store.account.origin;
    this.creating = this.exts.create({
      tag: prefixed,
      origin: this.store.account.origin,
    }).pipe(
      catchError((res: HttpErrorResponse) => {
        if (res.status === 409) {
          // Ignore Already exists error
          return of(null);
        }
        return throwError(() => res);
      }),
      switchMap(() => this.exts.get(tag)),
      catchError((res: HttpErrorResponse) => {
        delete this.creating;
        this.serverError = printError(res);
        return throwError(() => res);
      }),
    ).subscribe(ext => {
      delete this.creating;
      this.serverError = [];
      this.setExt(tag, ext);
      this.router.navigate(['/ext', ext.tag]);
    });
  }
 
  save() {
    this.serverError = [];
    this.submitted = true;
    this.editForm.markAllAsTouched();
    if (!this.editForm.valid) {
      scrollToFirstInvalid();
      return;
    }
    let ext = {
      ...this.editForm.value,
      tag: this.store.view.ext!.tag, // Need to fetch because control is disabled
      modifiedString: this.overwrite ? this.overwrittenModified : this.store.view.ext!.modifiedString,
    };
    const config = this.store.view.ext!.config;
    ext = {
      ...this.store.view.ext,
      ...ext,
      config: {
        ...isObject(config) ? config : {},
        ...ext.config,
      },
    };
    this.editing = this.exts.update(ext).pipe(
      catchError((res: HttpErrorResponse) => {
        delete this.editing;
        if (res.status === 400) {
          this.invalid = true;
          console.log(res.message);
          // TODO: read res.message to find which fields to delete
        }
        if (res.status === 409) {
          this.overwritten = true;
          this.exts.get(ext.tag + ext.origin).subscribe(x => this.overwrittenModified = x.modifiedString);
        }
        this.serverError = printError(res);
        return throwError(() => res);
      }),
    ).subscribe(() => {
      delete this.editing;
      this.editForm.markAsPristine();
      if (ext.tag === 'config/home' && this.admin.home) {
        this.router.navigate(['/home']);
      } else {
        this.router.navigate(['/tag', ext.tag]);
      }
    });
  }
 
  delete() {
    const ext = this.store.view.ext!;
    // TODO: Better dialogs
    if (confirm($localize`Are you sure you want to delete this tag extension?`)) {
      const deleteNotice = !isDeletorTag(ext.tag) && this.admin.getPlugin('plugin/delete')
        ? this.exts.create(tagDeleteNotice(ext))
        : of(null);
      this.deleting = this.exts.delete(ext.tag + ext.origin).pipe(
        switchMap(() => deleteNotice),
        catchError((err: HttpErrorResponse) => {
          delete this.deleting;
          this.serverError = printError(err);
          return throwError(() => err);
        }),
      ).subscribe(() => {
        delete this.deleting;
        this.router.navigate(['/tag', ext.tag]);
      });
    }
  }
 
  clear() {
    this.router.navigateByUrl('/ext');
  }
}