All files / app/component/query query.component.ts

55.75% Statements 92/165
39.82% Branches 45/113
78.94% Functions 15/19
54.6% Lines 77/141

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 2409x             9x 9x                     13x   3x 3x 3x 3x   3x     3x 3x 3x 3x       16x         1x 1x 1x 1x         5x 5x 4x 1x 1x 1x 1x 1x                               1x 1x 1x 1x                                                         1x 1x           1x     1x         1x 1x 3x 3x 3x 3x 3x 2x   1x 1x 1x 1x 1x 1x                               1x 1x 1x 1x 1x         1x 3x 3x 1x         2x 2x 2x 2x 2x 2x   2x 2x 2x 2x     2x 2x         2x 2x             2x                     2x 2x 2x 2x                                           2x                    
import { Component, ElementRef, Input, ViewChild, ChangeDetectionStrategy } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { defer } from 'lodash-es';
import { AdminService } from '../../service/admin.service';
import { ExtService } from '../../service/api/ext.service';
import { Store } from '../../store/store';
import { getEl } from '../../util/html';
import { access, fixClientQuery, getStrictPrefix, localTag, tagOrigin } from '../../util/tag';
 
export type Crumb = { text: string, tag?: string, pos: number, len: number };
 
@Component({
  selector: 'app-query',
  templateUrl: './query.component.html',
  styleUrls: ['./query.component.scss'],
  changeDetection: ChangeDetectionStrategy.Eager,
  imports: [ReactiveFormsModule, RouterLink]
})
export class QueryComponent {
 
  editing = false;
  replaceOnClipboardPaste = false;
  select: boolean | Crumb[] = false;
  breadcrumbs: Crumb[] = [];
 
  private _query = '';
 
  constructor(
    private router: Router,
    private exts: ExtService,
    private admin: AdminService,
    public store: Store,
  ) { }
 
  get query(): string {
    return this._query;
  }
 
  @Input()
  set query(value: string) {
    Iif (this._query === value) return;
    this.editing = false;
    this._query = value;
    this.breadcrumbs = this.queryCrumbs(this._query);
  }
 
  @ViewChild("editor")
  set editor(ref: ElementRef<HTMLInputElement>) {
    const el = ref?.nativeElement;
    if (!el) return;
    if (!this._query) return;
    el.focus();
    Iif (!this.select) return;
    defer(() => {
      if (this.select === true) {
        el.select();
      E} else if (this.select) {
        el.setSelectionRange(this.select[0].pos, this.select[1].pos + this.select[1].len);
      }
    });
  }
 
  click(event: MouseEvent, breadcrumb: Crumb): boolean {
    if (!this.store.hotkey) return true;
    event.preventDefault();
    event.stopImmediatePropagation();
    this.edit([breadcrumb, breadcrumb]);
    return false;
  }
 
  edit(select: boolean | Crumb[]) {
    Eif (!this.editing) this.replaceOnClipboardPaste = true;
    this.editing = true;
    if (select) {
      this.select = select;
    } else E{
      this.select = false;
      const selection = document.getSelection();
      if (selection && selection.rangeCount > 0 && selection.toString()) {
        const range = selection.getRangeAt(0);
        const startCrumb = this.findCrumbFromNode(getEl(range.startContainer));
        const endCrumb = this.findCrumbFromNode(getEl(range.endContainer));
        if (startCrumb && endCrumb) {
          this.select = [startCrumb, endCrumb];
        }
      }
    }
  }
 
  private findCrumbFromNode(el: Element | null): Crumb | undefined {
    while (el) {
      if (el.classList.contains('crumb')) {
        const index = Array.from(el.parentElement?.children || []).indexOf(el);
        if (index >= 0 && index < this.breadcrumbs.length) {
          return this.breadcrumbs[index];
        }
      }
      el = el.parentElement;
    }
    return undefined;
  }
 
  search(query: string) {
    this.editing = false;
    query = query.toLowerCase()
      .replace(/\s+/g, ' ')
      .replace(/\|+/g, '|')
      .replace(/[\s|]*:[\s|]*/g, ':')
      .replace(/\s+/g, '+')
      .replace(/[^_+/a-z-0-9.:|!@*()]+/g, '');
    Iif (this.store.view.current === 'tags') {
      this.router.navigate(['/tags', query], { queryParams: { pageNumber: null }, queryParamsHandling: 'merge' });
    } else {
      this.router.navigate(['/tag', query], { queryParams: { pageNumber: null }, queryParamsHandling: 'merge' });
    }
  }
 
  private queryCrumbs(query: string): Crumb[] {
    Iif (!query) return [];
    let read = 0;
    const result: Crumb[] = fixClientQuery(query).split(/([:|()])/g).filter(t => !!t).map(part => {
      const pos = read;
      const len = part.length;
      read += len;
      if (/[:|()]+/.test(part)) return { text: part, pos, len };
      return { text: '', tag: part, pos, len };
    });
    for (let i = 0; i < result.length - 2; i++) {
      const a = result[i];
      const op = result[i + 1];
      const b = result[i + 2];
      Iif (!a.tag || op.tag || !b.tag) continue;
      Eif (op.text !== '|') continue;
      if (tagOrigin(a.tag) !== tagOrigin(b.tag)) continue;
      const prefix = getStrictPrefix(a.tag, b.tag);
      if (prefix) {
        const origin = tagOrigin(a.tag);
        const as = access(a.tag) + localTag(a.tag).substring(prefix.length + 1);
        const bs = access(b.tag) + localTag(b.tag).substring(prefix.length + 1);
        if (!as.startsWith('{')) {
          result[i].tag = prefix + '/{' + as + ',' + bs + '}' + origin;
        } else {
          result[i].tag = prefix + '/' + as.substring(0, as.length - 1) + ',' + bs + '}' + origin;
        }
        result.splice(i + 1, 2);
        i--;
      }
    }
    for (let i = 0; i < result.length - 2; i++) {
      const op1 = result[i];
      const a = result[i + 1];
      const op2 = result[i + 2];
      Iif (a.tag && op1.text === '(' && op2.text === ')') {
        result.splice(i + 2, 1);
        result.splice(i, 1);
      }
    }
    return result.flatMap(c => {
      if (!c.tag) c.text = this.store.account.querySymbol(...c.text.split('') as any);
      if (c.tag) return this.tagCrumbs(c.tag, c.pos, c.len);
      return c;
    });
  }
 
  private tagCrumbs(tag: string, pos: number, len: number) {
    let read = pos;
    const crumbs: Crumb[] = localTag(tag).split(/([/{},])/g).filter(t => !!t).map(text => {
      const pos = read;
      const len = text.length;
      read += len;
      return ({text, pos, len});
    });
    let prefix = '';
    for (let i = 0; i < crumbs.length; i++) {
      const previous = i > 1 ? crumbs[i-2].tag + '/' : '';
      Iif (crumbs[i].text === '{') {
        prefix = previous;
      }
      if (!/[/{},]/g.test(crumbs[i].text)) {
        crumbs[i].tag = (prefix || previous) + crumbs[i].text;
      } else E{
        crumbs[i].text = this.store.account.querySymbol(crumbs[i].text as any);
      }
    }
    const origin = tagOrigin(tag);
    Iif (origin) {
      for (const t of crumbs) {
        if (t.tag) t.tag += origin;
      }
      crumbs.push({text: ' ', pos, len: 0 });
      crumbs.push({text: origin, tag: origin, pos: pos + len - origin.length, len: origin.length });
    }
    Iif (tag.startsWith('!')) {
      for (const t of crumbs) {
        if (t.text.startsWith('!')) t.text = t.text.substring(1);
      }
      const notOp = { text: this.store.account.querySymbol('!'), pos, len: 0 };
      if (notOp.text.startsWith(' ')) {
        crumbs.unshift(notOp);
      } else {
        crumbs.push(notOp);
      }
    }
    for (const t of crumbs) {
      const tag = t.tag?.startsWith('!') ? t.tag.substring(1) : t.tag;
      Eif (tag && !tag.startsWith('@')) {
        this.exts.getCachedExt(tag).subscribe(ext => {
          // TODO: possible delayed write
          if (ext.modifiedString && ext.name) {
            t.text = ext.name;
          } else if (ext.tag === 'plugin') {
            t.text = '📦';
          } else if (ext.tag === '+plugin') {
            t.text = '+📦';
          } else if (ext.tag === '_plugin') {
            t.text = '_📦';
          } else {
            const template = this.admin.getTemplate(ext.tag);
            if (template?.name) {
              t.text = template.name;
            } else {
              const plugin = this.admin.getPlugin(ext.tag);
              if (plugin?.name) t.text = plugin.name;
            }
          }
        });
      }
    }
    return crumbs;
  }
 
  blur(value: string) {
    this.replaceOnClipboardPaste = false;
    if (value === this.query) {
      this.editing = false;
    }
  }
}