All files / app/component/notebook/note note.component.ts

47.75% Statements 85/178
24.06% Branches 45/187
32.14% Functions 18/56
49.67% Lines 76/153

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                                                    67x 67x 67x                 67x 67x 67x 67x 67x 67x 67x 67x                                   67x 1x     1x         1x   1x         1x       1x 1x 1x   1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                   1x               1x 1x                     67x 1x       67x         67x   1x       67x 1x       67x 1x       67x         67x 1x 1x 1x 1x       67x 1x         67x           67x           67x           67x 1x       67x 1x       67x             67x 1x         67x           67x 1x         67x 1x 1x         67x 1x       67x           2x                                 67x 1x 1x                                                                                                                                                                                                                    
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { AsyncPipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import {
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  forwardRef,
  HostBinding,
  HostListener,
  Input,
  NgZone,
  OnChanges,
  OnDestroy,
  Output,
  SimpleChanges,
  TemplateRef,
  ViewChild,
  ViewContainerRef
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { defer, delay, difference, intersection, uniq } from 'lodash-es';
import { catchError, of, Subject, Subscription, switchMap, takeUntil, throwError } from 'rxjs';
import { Ext } from '../../../model/ext';
import { equalsRef, Ref } from '../../../model/ref';
import { CssUrlPipe } from '../../../pipe/css-url.pipe';
import { ThumbnailPipe } from '../../../pipe/thumbnail.pipe';
import { AdminService } from '../../../service/admin.service';
import { ExtService } from '../../../service/api/ext.service';
import { RefService } from '../../../service/api/ref.service';
import { TaggingService } from '../../../service/api/tagging.service';
import { AuthzService } from '../../../service/authz.service';
import { BookmarkService } from '../../../service/bookmark.service';
import { ConfigService } from '../../../service/config.service';
import { Store } from '../../../store/store';
import { getTitle, hasComment } from '../../../util/format';
import { printError } from '../../../util/http';
import { memo, MemoCache } from '../../../util/memo';
import { expandedTagsInclude, hasTag, repost } from '../../../util/tag';
import { ChessComponent } from '../../chess/chess.component';
import { LoadingComponent } from '../../loading/loading.component';
import { MdComponent } from '../../md/md.component';
import { TodoComponent } from '../../todo/todo.component';
 
@Component({
  selector: 'app-note',
  templateUrl: './note.component.html',
  styleUrls: ['./note.component.scss'],
  host: { 'class': 'note' },
  imports: [
    forwardRef(() => MdComponent),
    LoadingComponent,
    RouterLink,
    ChessComponent,
    TodoComponent,
    AsyncPipe,
    ThumbnailPipe,
    CssUrlPipe,
  ],
})
export class NoteComponent implements OnChanges, AfterViewInit, OnDestroy {
  private destroy$ = new Subject<void>();
 
  @HostBinding('class.unlocked')
  unlocked = false;
 
  @Input()
  ref!: Ref;
  @Input()
  pressToUnlock = false;
  @Input()
  hideSwimLanes = true;
  @Input()
  ext?: Ext;
 
  @Output()
  copied = new EventEmitter<Ref>();
 
  repostRef?: Ref;
  @HostBinding('class.full-size')
  todo = false;
  chess = false;
  chessWhite = true;
  overlayRef?: OverlayRef;
  autoClose = true;
 
  @ViewChild('cardMenu')
  cardMenu!: TemplateRef<any>;
 
  private overlayEvents?: Subscription;
 
  constructor(
    public store: Store,
    public bookmarks: BookmarkService,
    private admin: AdminService,
    private config: ConfigService,
    private auth: AuthzService,
    private refs: RefService,
    private tags: TaggingService,
    private exts: ExtService,
    private overlay: Overlay,
    private el: ElementRef,
    private viewContainerRef: ViewContainerRef,
    private zone: NgZone,
  ) { }
 
  init() {
    MemoCache.clear(this);
    this.todo = !!this.admin.getPlugin('plugin/todo') && !!this.ref.tags?.includes('plugin/todo');
    this.chess = !!this.admin.getPlugin('plugin/chess') && !!this.ref.tags?.includes('plugin/chess');
    this.chessWhite = !!this.ref.tags?.includes(this.store.account.localTag);
    if (this.repost && this.ref && this.repostRef?.url != repost(this.ref)) {
      (this.store.view.top?.url === this.ref.sources![0]
          ? of(this.store.view.top)
          : this.refs.getCurrent(this.url)
      ).pipe(
        catchError(err => err.status === 404 ? of(undefined) : throwError(() => err)),
        takeUntil(this.destroy$),
      ).subscribe(ref => this.repostRef = ref);
    }
  }
 
  ngOnChanges(changes: SimpleChanges) {
    if (changes.ref) {
      this.init();
    }
  }
 
  ngAfterViewInit(): void {
    delay(() => {
      if (this.lastSelected) {
        this.el.nativeElement.scrollIntoView({ behavior: 'smooth' });
      }
    }, 400);
  }
 
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
 
  @HostListener('click')
  onClick() {
    if (!this.lastSelected && this.store.view.lastSelected) {
      this.store.view.clearLastSelected();
    }
  }
 
  @memo
  get remote() {
    return this.ref.modified && this.origin !== this.store.account.origin;
  }
 
  @memo
  get origin() {
    return this.repost ? this.repostRef?.origin : this.ref.origin;
  }
 
  @memo
  @HostBinding('class.no-write')
  get noWrite() {
    return !this.auth.writeAccess(this.ref);
  }
 
  @memo
  get repost() {
    return this.ref?.sources?.[0] && hasTag('plugin/repost', this.ref);
  }
 
  @memo
  get bareRepost() {
    return this.repost && !this.ref.title && !this.ref.comment;
  }
 
  @memo
  get url() {
    return this.repost ? this.ref.sources![0] : this.ref.url;
  }
 
  @memo
  get currentText() {
    Iif (this.chess || this.todo) return '';
    const value = this.ref?.comment || this.repostRef?.comment || '';
    Iif (this.ref?.title || hasComment(value)) return value;
    return '';
  }
 
  @memo
  get thumbnail() {
    return this.admin.getPlugin('plugin/thumbnail') &&
      hasTag('plugin/thumbnail', this.ref) || hasTag('plugin/thumbnail', this.repostRef);
  }
 
  @memo
  get thumbnailColor() {
    return this.thumbnail &&
      (this.ref?.plugins?.['plugin/thumbnail']?.color || this.repostRef?.plugins?.['plugin/thumbnail']?.color);
  }
 
  @memo
  get thumbnailEmoji() {
    return this.thumbnail &&
      (this.ref?.plugins?.['plugin/thumbnail']?.emoji || this.repostRef?.plugins?.['plugin/thumbnail']?.emoji) || '';
  }
 
  @memo
  get thumbnailRadius() {
    return this.thumbnail &&
      (this.ref?.plugins?.['plugin/thumbnail']?.radius || this.repostRef?.plugins?.['plugin/thumbnail']?.radius) || 0;
  }
 
  @memo
  get dependents() {
    return !hasTag('plugin/comment', this.ref) && !hasTag('plugin/thread', this.ref) && this.ref.sources?.length || 0;
  }
 
  @memo
  get dependencies() {
    return this.ref.metadata?.responses || 0;
  }
 
  @memo
  get thread() {
    if (!this.admin.getPlugin('plugin/thread')) return '';
    if (!hasTag('plugin/thread', this.ref) && !this.threads) return '';
    return this.ref.sources?.[1] || this.ref.sources?.[0] || this.ref.url;
  }
 
  @memo
  get threads() {
    Eif (!this.admin.getPlugin('plugin/thread')) return 0;
    return this.ref.metadata?.plugins?.['plugin/thread'] || 0;
  }
 
  @memo
  get comment() {
    if (!this.admin.getPlugin('plugin/comment')) return 0;
    return hasTag('plugin/comment', this.ref) || this.comments;
  }
 
  @memo
  get comments() {
    Eif (!this.admin.getPlugin('plugin/comment')) return 0;
    return this.ref.metadata?.plugins?.['plugin/comment'] || 0;
  }
 
  @memo
  get badges() {
    const badges = intersection(this.ref.tags, this.ext?.config?.badges || []);
    Eif (this.hideSwimLanes) return badges;
    return difference(badges, this.ext?.config?.swimLanes || []);
  }
 
  @memo
  get badgeExts$() {
    return this.exts.getCachedExts(this.badges, this.ref.origin || '');
  }
 
  @memo
  get allBadgeExts$() {
    return this.exts.getCachedExts(this.ext?.config?.badges || [], this.ref.origin || '');
  }
 
  @HostBinding('class.last-selected')
  get lastSelected() {
    return this.store.view.lastSelected?.url === this.ref.url;
  }
 
  @HostListener('touchend', ['$event'])
  touchend(e: TouchEvent) {
    this.zone.run(() => this.unlocked = false);
  }
 
  @HostListener('press', ['$event'])
  unlock(event: any) {
    if (!this.config.mobile) return;
    this.unlocked = true;
    this.el.nativeElement.scrollIntoView({ block: 'nearest', inline: 'center', behavior: 'smooth' });
    if ('vibrate' in navigator) navigator.vibrate([2, 32, 4]);
  }
 
  @memo
  get title() {
    Iif (this.bareRepost) return getTitle(this.repostRef) || $localize`Repost`;
    return getTitle(this.ref);
  }
 
  @HostListener('contextmenu', ['$event'])
  contextMenu(event: MouseEvent) {
    if (this.pressToUnlock) {
      // no badge menu on mobile
      return;
    }
    event.preventDefault();
    this.close();
    defer(() => {
      const positionStrategy = this.overlay.position()
        .flexibleConnectedTo({x: event.x, y: event.y})
        .withPositions([{
          originX: 'center',
          originY: 'center',
          overlayX: 'start',
          overlayY: 'top',
        }]);
      this.overlayRef = this.overlay.create({
        positionStrategy,
        scrollStrategy: this.overlay.scrollStrategies.close(),
      });
      this.overlayRef.attach(new TemplatePortal(this.cardMenu, this.viewContainerRef));
      this.overlayEvents = this.overlayRef.outsidePointerEvents().subscribe((event: MouseEvent) => {
        switch (event.type) {
          case 'click':
          case 'pointerdown':
          case 'touchstart':
          case 'mousedown':
          case 'contextmenu':
            this.zone.run(() => this.close());
        }
      });
    });
  }
 
  saveRef() {
    this.store.view.preloadRef(this.ref, this.repostRef);
  }
 
  close() {
    this.autoClose = true;
    this.overlayRef?.dispose();
    this.overlayEvents?.unsubscribe();
    this.overlayRef = undefined;
    this.overlayEvents = undefined;
  }
 
  toggleBadge(tag: string, event?: MouseEvent) {
    if (hasTag(tag, this.ref.tags)) {
      this.tags.delete(tag, this.ref.url, this.ref.origin).subscribe(() => {
        this.ref.tags = this.ref.tags!.filter(t => expandedTagsInclude(t, tag));
        this.init();
      });
    } else {
      this.tags.create(tag, this.ref.url, this.ref.origin).subscribe(() => {
        this.ref.tags ||= [];
        this.ref.tags.push(tag);
        this.init();
      });
    }
    if (this.autoClose || !event?.button) {
      this.close();
    } else {
      event.preventDefault();
    }
  }
 
  copy() {
    const tags = uniq([
      ...(this.store.account.localTag ? [this.store.account.localTag] : []),
      ...(this.ref.tags || []).filter(t => this.auth.canAddTag(t))
    ]);
    const copied = {
      ...this.ref,
      origin: this.store.account.origin,
      tags,
    };
    this.refs.create(copied).pipe(
      catchError((err: HttpErrorResponse) => {
        if (err.status === 409) {
          return this.refs.get(this.ref.url, this.store.account.origin).pipe(
            switchMap(existing => {
              if (equalsRef(existing, copied) || confirm('An old version already exists. Overwrite it?')) {
                // TODO: Show diff and merge or split
                return this.refs.update({ ...copied, modifiedString: existing.modifiedString });
              } else {
                return throwError(() => 'Cancelled')
              }
            })
          );
        }
        // TODO: better error messages
        console.error(printError(err));
        return throwError(() => err);
      }),
      switchMap(() => this.refs.get(copied.url, this.store.account.origin).pipe(takeUntil(this.destroy$))),
    ).subscribe(ref => {
      this.ref = ref;
      this.init();
      this.copied.emit(ref);
    });
  }
}