All files / app/component/sidebar sidebar.component.ts

55.5% Statements 131/236
23.3% Branches 48/206
33.33% Functions 26/78
57.89% Lines 121/209

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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468                                          7x 7x 7x                         7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x                                                 15x 4x 4x     4x   4x   4x   4x     4x     4x         4x 4x 4x 4x 4x 4x   4x 4x 4x   4x   4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x     4x     4x                         4x 4x   4x 4x       4x 4x 4x                   4x     4x     4x           3x 3x 3x                             3x 3x 3x   3x                                   3x 3x 3x 3x 3x 3x 3x   3x         4x 4x 12x 4x       7x 4x       34x         2x 2x       4x       41x           8x 8x 8x       7x 7x       7x 7x         7x         7x 4x       7x               7x 4x       7x 4x       7x         7x 4x       7x         7x         7x           7x         7x         7x         7x         7x         7x                                       7x               7x 4x       7x 4x       7x                                                                                                                                                  
import { AsyncPipe } from '@angular/common';
import {
  AfterViewInit,
  Component,
  ElementRef,
  forwardRef,
  HostBinding,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  SimpleChanges
} from '@angular/core';
import { NavigationEnd, Router, RouterLink, RouterLinkActive } from '@angular/router';
import { uniq, uniqBy } from 'lodash-es';
import { autorun, IReactionDisposer, runInAction } from 'mobx';
import { MobxAngularModule } from 'mobx-angular';
import { catchError, filter, finalize, forkJoin, map, of, Subject } from 'rxjs';
import { v4 as uuid } from 'uuid';
import { Ext } from '../../model/ext';
import { Plugin } from '../../model/plugin';
import { hydrate } from '../../model/tag';
import { getTemplateScope, Template } from '../../model/template';
import { getMailbox } from '../../mods/mailbox';
import { RootConfig } from '../../mods/root';
import { UserConfig } from '../../mods/user';
import { AccountService } from '../../service/account.service';
import { AdminService } from '../../service/admin.service';
import { ExtService } from '../../service/api/ext.service';
import { TaggingService } from '../../service/api/tagging.service';
import { TemplateService } from '../../service/api/template.service';
import { AuthzService } from '../../service/authz.service';
import { ConfigService } from '../../service/config.service';
import { HelpService } from '../../service/help.service';
import { QueryStore } from '../../store/query';
import { Store } from '../../store/store';
import { encodeBookmarkParams } from '../../util/http';
import { memo, MemoCache } from '../../util/memo';
import { hasPrefix, hasTag, isQuery, localTag, setProtected, setPublic, topAnds } from '../../util/tag';
import { BulkComponent } from '../bulk/bulk.component';
import { ChatVideoComponent } from '../chat/chat-video/chat-video.component';
import { ChatComponent } from '../chat/chat.component';
import { DebugComponent } from '../debug/debug.component';
import { ExtComponent } from '../ext/ext.component';
import { FilterComponent } from '../filter/filter.component';
import { MdComponent } from '../md/md.component';
import { NavComponent } from '../nav/nav.component';
import { QueryComponent } from '../query/query.component';
import { SearchComponent } from '../search/search.component';
import { SortComponent } from '../sort/sort.component';
 
@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.scss'],
  host: { 'class': 'sidebar' },
  imports: [
    ExtComponent,
    forwardRef(() => MdComponent),
    MobxAngularModule,
    SearchComponent,
    QueryComponent,
    FilterComponent,
    SortComponent,
    DebugComponent,
    BulkComponent,
    RouterLink,
    ChatComponent,
    AsyncPipe,
    NavComponent,
    RouterLinkActive,
    ChatVideoComponent,
  ]
})
export class SidebarComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy {
  private disposers: IReactionDisposer[] = [];
  private destroy$ = new Subject<void>();
 
  @Input()
  tag = '';
  @Input()
  activeExts: Ext[] = [];
  @Input()
  showToggle = true;
  @Input()
  home = false;
  @Input()
  @HostBinding('class.floating')
  floating = true;
 
  localTag?: string;
  addTags: string[] = this.rootConfig?.addTags || ['public'];
  plugin?: Plugin;
  mailPlugin?: Plugin;
  tagTemplate?: Template;
  template?: Template;
  writeAccess = false;
  ui: Template[] = [];
  genUrl = 'internal:' + uuid();
  bookmarkExts: Ext[] = [];
  tagSubExts: Ext[] = [];
  userSubExts: Ext[] = [];
 
  savingBookmark = false;
  savingSub = false;
  savingAlarm = false;
 
  private _expanded = false;
  private _ext?: Ext;
  private lastView = this.store.view.current;
 
  constructor(
    public router: Router,
    public admin: AdminService,
    public store: Store,
    public query: QueryStore,
    public config: ConfigService,
    private auth: AuthzService,
    private account: AccountService,
    public ts: TaggingService,
    private exts: ExtService,
    private templates: TemplateService,
    private el: ElementRef,
    private help: HelpService,
  ) {
    Iif (localStorage.getItem('sidebar-expanded') !== null) {
      this.expanded = localStorage.getItem('sidebar-expanded') !== 'false';
    } else {
      this.expanded = window.matchMedia && !!window.matchMedia('(min-width: 1024px)').matches;
    }
 
    router.events.pipe(
      filter(event => event instanceof NavigationEnd),
    ).subscribe(() => {
      if (this.chat) return;
      if (this.config.tablet && this.lastView != this.store.view.current ||
        !this.config.huge  && this.store.view.current === 'ref/summary') {
        this.lastView = this.store.view.current;
        this.expanded = false;
      }
    });
  }
 
  ngOnInit(): void {
    this.disposers.push(autorun(() => {
      this.expanded = this.store.view.sidebarExpanded;
    }));
    this.disposers.push(autorun(() => {
      Iif (this.store.view.ref) {
        MemoCache.clear(this);
      }
    }));
    this.disposers.push(autorun(() => {
      if (!this.store.view.template) {
        this.template = undefined;
      E} else if (!isQuery(this.store.view.template) && this.template?.tag !== this.store.view.template) {
        this.templates.get(this.store.view.template + this.store.account.origin).pipe(
          catchError(() => of(undefined))
        ).subscribe(t => this.template = t);
      }
    }));
  }
 
  ngAfterViewInit() {
    Iif (this.ext?.config.searchHelp) {
      this.help.pushStep(this.el.nativeElement.querySelector('app-search'), this.ext.config.searchHelp);
    }
    Iif (this.ext?.config.filterHelp) {
      this.help.pushStep(this.el.nativeElement.querySelector('app-filter'), this.ext.config.filterHelp);
    }
    Iif (this.ext?.config.sortHelp) {
      this.help.pushStep(this.el.nativeElement.querySelector('app-sort'), this.ext.config.sortHelp);
    }
  }
 
  ngOnChanges(changes: SimpleChanges) {
    Eif (changes.home || changes.tag || changes.ext) {
      MemoCache.clear(this);
      Iif (this.ext) {
        this.bookmarks$.subscribe(xs => this.bookmarkExts = xs);
        this.tagSubs$.subscribe(xs => this.tagSubExts = xs);
        this.userSubs$.subscribe(xs => this.userSubExts = xs);
        this.tag ||= this.ext.tag || '';
        if (this.ext.config?.searchHelp) {
          this.help.pushStep(this.el.nativeElement.querySelector('app-search'), this.ext.config.searchHelp);
        }
        if (this.ext.config?.filterHelp) {
          this.help.pushStep(this.el.nativeElement.querySelector('app-filter'), this.ext.config.filterHelp);
        }
        if (this.ext.config?.sortHelp) {
          this.help.pushStep(this.el.nativeElement.querySelector('app-sort'), this.ext.config.sortHelp);
        }
      } else {
        this.bookmarkExts = [];
        this.tagSubExts = [];
        this.userSubExts = [];
      }
      Iif (this.tag) {
        this.localTag = localTag(this.tag);
        this.plugin = this.admin.getPlugin(this.tag);
        if (this.home) {
          this.addTags = this.rootConfig?.addTags || this.plugin?.config?.reply || ['public'];
        } else if (this.plugin) {
          this.addTags = uniq([
            ...this.rootConfig?.addTags || this.plugin?.config?.reply || ['public'],
            ...this.plugin?.config?.submit ? [this.plugin.tag] : [],
            ...this.plugin?.config?.internal ? ['internal'] : []]);
        } else {
          this.addTags = uniq([...this.rootConfig?.addTags || ['public'], ...topAnds(this.tag).map(localTag)]);
        }
        this.mailPlugin = this.admin.getPlugin(getMailbox(this.tag, this.store.account.origin));
        this.tagTemplate = this.admin.getTemplate(this.tag);
        this.writeAccess = this.auth.tagWriteAccess(this.tag);
        this.ui = this.admin.getTemplateUi(this.tag);
      } else {
        this.localTag = undefined;
        this.addTags = this.rootConfig?.addTags || this.plugin?.config?.reply || ['public'];
        this.plugin = undefined;
        this.mailPlugin = undefined;
        this.tagTemplate = undefined;
        this.writeAccess = false;
        this.ui = [];
      }
      this.addTags = this.addTags.filter(t => this.auth.canAddTag(t));
    }
  }
 
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
    for (const dispose of this.disposers) dispose();
    this.disposers.length = 0;
  }
 
  @memo
  get local() {
    return !this.existing || this.ext?.origin === this.store.account.origin;
  }
 
  get ext(): Ext | undefined {
    return this._ext;
  }
 
  @Input()
  set ext(value: Ext | undefined) {
    this._ext = value;
    runInAction(() => this.store.view.floatingSidebar = !value?.config?.noFloatingSidebar && value?.config?.defaultCols === undefined);
  }
 
  get existing() {
    return this.ext?.modified;
  }
 
  get expanded(): boolean {
    return this._expanded;
  }
 
  @Input()
  @HostBinding('class.expanded')
  set expanded(value: boolean) {
    localStorage.setItem('sidebar-expanded', ''+value);
    this._expanded = value;
    runInAction(() => this.store.view.sidebarExpanded = value);
  }
 
  @memo
  get root() {
    return !!this.admin.getTemplate('');
  }
 
  @memo
  get rootConfig() {
    Eif (!this.root) return undefined;
    return (this.ext?.config || this.tagTemplate?.defaults || this.admin.getTemplate('')!.defaults) as RootConfig;
  }
 
  @memo
  get modmail() {
    return !this.store.view.query && this.rootConfig?.modmail;
  }
 
  @memo
  get dm() {
    return this.admin.getTemplate('dm') && this.store.view.current === 'inbox/dms';
  }
 
  @memo
  get dms() {
    return uniq([
      ...this.plugin?.config?.reply ? [ this.plugin.tag ] : [],
      ...this.rootConfig?.dms ? [this.rootConfig?.dms] : [],
    ]);
  }
 
  @memo
  get canAddTag() {
    return !this.plugin?.tag || this.auth.canAddTag(this.plugin.tag);
  }
 
  @memo
  get videoChat() {
    return !!this.admin.getPlugin('plugin/user/video') && (this.chat || hasPrefix(this.ext?.tag || this.tag, 'chat'));
  }
 
  @memo
  get chat() {
    return !!this.admin.getPlugin('plugin/user/lobby') && !!this.admin.getPlugin('plugin/chat') && hasTag('plugin/chat', this.store.view.ref);
  }
 
  @memo
  get user() {
    return !this.store.view.query && !!this.admin.getTemplate('user') && hasPrefix(this.tag, 'user') && !this.store.view.userTemplate;
  }
 
  @memo
  get inbox() {
    return setPublic(this.tag);
  }
 
  @memo
  get outbox() {
    return setProtected(this.tag);
  }
 
  @memo
  get userConfig() {
    if (!this.user && !this.home) return null;
    return this.store.account.ext?.config as UserConfig;
  }
 
  @memo
  get bookmarks$() {
    return this.exts.getCachedExts(this.store.account.bookmarkQueries).pipe(this.admin.extFallbacks);
  }
 
  @memo
  get userSubs() {
    return this.userConfig?.subscriptions?.filter((s: string) => hasPrefix(s, 'user'));
  }
 
  @memo
  get userSubs$() {
    return this.exts.getCachedExts(this.userSubs || []).pipe(this.admin.extFallbacks);
  }
 
  @memo
  get tagSubs() {
    return this.userConfig?.subscriptions?.filter((s: string) => !hasPrefix(s, 'user'));
  }
 
  @memo
  get tagSubs$() {
    return this.exts.getCachedExts(this.tagSubs || []).pipe(this.admin.extFallbacks);
  }
 
  @memo
  get queryExts$() {
    if (!this.store.view.exts.length) return of([]);
    return forkJoin(this.store.view.exts.map(x => this.exts.page({
      query: x.tag,
      sort: ['origin', 'tag:len', 'tag', 'modified,DESC'],
      size: x.config?.childTags || 5,
    }).pipe(
      map(page => ({
        x: x,
        children: uniqBy(page.content, c => c.tag).filter(c => c.tag !== x.tag),
        more: page.page.totalPages > 1,
      })),
      map(res => res.children.length ? res : null),
      catchError(() => of(null))
    ))).pipe(
      map(ress => ress.filter(res => !!res)),
    );
  }
 
  @memo
  get messages() {
    if (!this.admin.getPlugin('plugin/inbox')) return false;
    if (!this.admin.getTemplate('dm')) return false;
    if (!this.store.account.user) return false;
    return this.dm || this.user || this.modmail || this.dms.length;
  }
 
  @memo
  get notes() {
    return this.admin.getTemplate('notes') && this.store.account.user;
  }
 
  @memo
  get homeWriteAccess() {
    return this.home && this.admin.home && this.auth.tagWriteAccess('config/home');
  }
 
  @memo
  get uiMarkdown() {
    if (!this.ext) return '';
    return this.ui.map(t => hydrate(t.config, 'ui', getTemplateScope(this.store.account.roles, t, this.ext!, this.el.nativeElement))).join();
  }
 
  subscribe() {
    this.savingSub = true;
    this.account.addSub$(this.tag!).pipe(
      finalize(() => this.savingSub = false),
    ).subscribe();
  }
 
  unsubscribe() {
    this.savingSub = true;
    this.account.removeSub$(this.tag!).pipe(
      finalize(() => this.savingSub = false),
    ).subscribe();
  }
 
  addBookmark() {
    this.savingBookmark = true;
    this.account.addBookmark$(this.bookmark).pipe(
      finalize(() => this.savingBookmark = false),
    ).subscribe();
  }
 
  removeBookmark() {
    this.savingBookmark = true;
    this.account.removeBookmark$(this.bookmark).pipe(
      finalize(() => this.savingBookmark = false),
    ).subscribe();
  }
 
  addAlarm() {
    this.savingAlarm = true;
    this.account.addAlarm$(this.tag!).pipe(
      finalize(() => this.savingAlarm = false),
    ).subscribe();
  }
 
  removeAlarm() {
    this.savingAlarm = true;
    this.account.removeAlarm$(this.tag!).pipe(
      finalize(() => this.savingAlarm = false),
    ).subscribe();
  }
 
  get inSubs() {
    return this.store.account.subs.includes(this.tag!);
  }
 
  get bookmark() {
    const qs = encodeBookmarkParams(this.router.url);
    return qs ? `${this.tag}?${qs}` : this.tag!;
  }
 
  get inBookmarks() {
    return this.store.account.bookmarks.includes(this.bookmark);
  }
 
  get inAlarms() {
    return this.store.account.alarms.includes(this.tag!);
  }
 
  set showRemotes(value: boolean) {
    this.router.navigate([], { queryParams: { showRemotes: value ? true : null }, queryParamsHandling: 'merge' })
  }
 
  startChat() {
    runInAction(() => this.store.view.ref?.tags?.push('plugin/chat'));
    this.ts.create('plugin/chat', this.store.view.ref!.url, this.store.account.origin).subscribe();
  }
}