1d0618c6fcc936b1a8cc05db5b7716f0ceecee62
[arvados-workbench2.git] / src / store / search-bar / search-query / arv-parser.ts
1
2 // Copyright (C) The Arvados Authors. All rights reserved.
3 //
4 // SPDX-License-Identifier: AGPL-3.0
5
6 import * as parser from '~/store/search-bar/search-query/parser';
7
8 interface Property {
9     key: string;
10     value: string;
11 }
12
13 export enum Keywords {
14     TYPE = 'type',
15     CLUSTER = 'cluster',
16     PROJECT = 'project',
17     IS = 'is',
18     FROM = 'from',
19     TO = 'to',
20 }
21
22 export enum States {
23     TRASHED = 'trashed',
24     PAST_VERSION = 'pastVersion'
25 }
26
27 const keyValuePattern = (key: string) => new RegExp(`${key}:([^ ]*)`);
28 const propertyPattern = /has:"(.*?)":"(.*?)"/;
29
30 const patterns = [
31     keyValuePattern(Keywords.TYPE),
32     keyValuePattern(Keywords.CLUSTER),
33     keyValuePattern(Keywords.PROJECT),
34     keyValuePattern(Keywords.IS),
35     keyValuePattern(Keywords.FROM),
36     keyValuePattern(Keywords.TO),
37     propertyPattern
38 ];
39
40 export const parseSearchQuery = parser.parseSearchQuery(patterns);
41
42 export const getValue = (tokens: string[]) => (key: string) => {
43     const pattern = keyValuePattern(key);
44     const token = tokens.find(t => pattern.test(t));
45     if (token) {
46         const [, value] = token.split(':');
47         return value;
48     }
49     return undefined;
50 };
51
52 export const getProperties = (tokens: string[]) =>
53     tokens.reduce((properties, token) => {
54         const match = token.match(propertyPattern);
55         if (match) {
56             const [, key, value] = match;
57             const newProperty = { key, value };
58             return [...properties, newProperty];
59         }
60         return properties;
61     }, [] as Property[]);
62
63
64 export const isTrashed = (tokens: string[]) => isSomeState(States.TRASHED, tokens);
65
66 export const isPastVersion = (tokens: string[]) => isSomeState(States.PAST_VERSION, tokens);
67
68 const isSomeState = (state: string, tokens: string[]) => {
69     for (const token of tokens) {
70         const match = token.match(keyValuePattern(Keywords.IS)) || ['', ''];
71         if (match) {
72             const [, value] = match;
73             if(value === state) {
74                 return true;
75             }
76         }
77     }
78     return false;
79 };