aboutsummaryrefslogtreecommitdiff
path: root/pw_web/log-viewer/src/components/log-view/log-view.ts
blob: 900637e5cebb74e7c5b7d65412fa0a9adad50177 (plain)
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
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

import { LitElement, PropertyValues, html } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { styles } from './log-view.styles';
import { LogList } from '../log-list/log-list';
import { TableColumn, LogEntry, State } from '../../shared/interfaces';
import { LocalStorageState, StateStore } from '../../shared/state';
import { LogFilter } from '../../utils/log-filter/log-filter';
import '../log-list/log-list';
import '../log-view-controls/log-view-controls';
import { titleCaseToKebabCase } from '../../utils/strings';

type FilterFunction = (logEntry: LogEntry) => boolean;

/**
 * A component that filters and displays incoming log entries in an encapsulated
 * instance. Each `LogView` contains a log list and a set of log view controls
 * for configurable viewing of filtered logs.
 *
 * @element log-view
 */
@customElement('log-view')
export class LogView extends LitElement {
  static styles = styles;

  /**
   * The component's global `id` attribute. This unique value is set whenever a
   * view is created in a log viewer instance.
   */
  @property({ type: String })
  id = `${this.localName}-${crypto.randomUUID()}`;

  /** An array of log entries to be displayed. */
  @property({ type: Array })
  logs: LogEntry[] = [];

  /** Indicates whether this view is one of multiple instances. */
  @property({ type: Boolean })
  isOneOfMany = false;

  /** Whether line wrapping in table cells should be used. */
  @state()
  _lineWrap = false;

  /** The field keys (column values) for the incoming log entries. */
  @state()
  private _columnData: TableColumn[] = [];

  /** A string representing the value contained in the search field. */
  @state()
  public searchText = '';

  /** A StateStore object that stores state of views */
  @state()
  _stateStore: StateStore = new LocalStorageState();

  @query('log-list') _logList!: LogList;

  /**
   * An array containing the logs that remain after the current filter has been
   * applied.
   */
  private _filteredLogs: LogEntry[] = [];

  /** A function used for filtering rows that contain a certain substring. */
  private _stringFilter: FilterFunction = () => true;

  /**
   * A function used for filtering rows that contain a timestamp within a
   * certain window.
   */
  private _timeFilter: FilterFunction = () => true;

  private _state: State;

  private _debounceTimeout: NodeJS.Timeout | null = null;

  /** The number of elements in the `logs` array since last updated. */
  private _lastKnownLogLength: number = 0;

  /** The amount of time, in ms, before the filter expression is executed. */
  private readonly FILTER_DELAY = 100;

  constructor() {
    super();
    this._state = this._stateStore.getState();
  }

  protected firstUpdated(): void {
    const viewConfigArr = this._state.logViewConfig;
    const index = viewConfigArr.findIndex((i) => this.id === i.viewID);

    // Get column data from local storage, if it exists
    if (index !== -1) {
      const storedColumnData = viewConfigArr[index].columnData;
      this._columnData = storedColumnData;
    }
  }

  updated(changedProperties: PropertyValues) {
    super.updated(changedProperties);

    if (changedProperties.has('logs')) {
      const newLogs = this.logs.slice(this._lastKnownLogLength);
      this._lastKnownLogLength = this.logs.length;

      this.updateFieldsFromNewLogs(newLogs);
    }

    if (changedProperties.has('logs') || changedProperties.has('searchText')) {
      this.filterLogs();
    }

    if (changedProperties.has('_columnData')) {
      this._state = { logViewConfig: this._state.logViewConfig };
      this._stateStore.setState({
        logViewConfig: this._state.logViewConfig,
      });
    }
  }

  /**
   * Updates the log filter based on the provided event type.
   *
   * @param {CustomEvent} event - The custom event containing the information to
   *   update the filter.
   */
  private updateFilter(event: CustomEvent) {
    this.searchText = event.detail.inputValue;
    const logViewConfig = this._state.logViewConfig;
    const index = logViewConfig.findIndex((i) => this.id === i.viewID);

    switch (event.type) {
      case 'input-change':
        if (this._debounceTimeout) {
          clearTimeout(this._debounceTimeout);
        }

        if (index !== -1) {
          logViewConfig[index].search = this.searchText;
          this._state = { logViewConfig: logViewConfig };
          this._stateStore.setState({ logViewConfig: logViewConfig });
        }

        if (!this.searchText) {
          this._stringFilter = () => true;
          return;
        }

        // Run the filter after the timeout delay
        this._debounceTimeout = setTimeout(() => {
          const filters = LogFilter.parseSearchQuery(this.searchText).map(
            (condition) => LogFilter.createFilterFunction(condition),
          );
          this._stringFilter =
            filters.length > 0
              ? (logEntry: LogEntry) =>
                  filters.some((filter) => filter(logEntry))
              : () => true;

          this.filterLogs();
          this.requestUpdate();
        }, this.FILTER_DELAY);
        break;
      case 'clear-logs':
        this._timeFilter = (logEntry) =>
          logEntry.timestamp > event.detail.timestamp;
        break;
      default:
        break;
    }

    this.filterLogs();
    this.requestUpdate();
  }

  private updateFieldsFromNewLogs(newLogs: LogEntry[]): void {
    if (!this._columnData) {
      this._columnData = [];
    }

    newLogs.forEach((log) => {
      log.fields.forEach((field) => {
        if (!this._columnData.some((col) => col.fieldName === field.key)) {
          this._columnData.push({
            fieldName: field.key,
            characterLength: 0,
            manualWidth: null,
            isVisible: true,
          });
        }
      });
    });
  }

  public getFields(): string[] {
    return this._columnData
      .filter((column) => column.isVisible)
      .map((column) => column.fieldName);
  }

  /**
   * Toggles the visibility of columns in the log list based on the provided
   * event.
   *
   * @param {CustomEvent} event - The click event containing the field being
   *   toggled.
   */
  private toggleColumns(event: CustomEvent) {
    const logViewConfig = this._state.logViewConfig;
    const index = logViewConfig.findIndex((i) => this.id === i.viewID);

    if (index === -1) {
      return;
    }

    // Find the relevant column in _columnData
    const column = this._columnData.find(
      (col) => col.fieldName === event.detail.field,
    );

    if (!column) {
      return;
    }

    // Toggle the column's visibility
    column.isVisible = event.detail.isChecked;

    // Clear the manually-set width of the last visible column
    const lastVisibleColumn = this._columnData
      .slice()
      .reverse()
      .find((col) => col.isVisible);
    if (lastVisibleColumn) {
      lastVisibleColumn.manualWidth = null;
    }

    // Trigger the change in column data and request an update
    this._columnData = [...this._columnData];
    this._logList.requestUpdate();
  }

  /**
   * Toggles the wrapping of text in each row.
   *
   * @param {CustomEvent} event - The click event.
   */
  private toggleWrapping() {
    this._lineWrap = !this._lineWrap;
  }

  /**
   * Combines filter expressions and filters the logs. The filtered
   * logs are stored in the `_filteredLogs` property.
   */
  private filterLogs() {
    const combinedFilter = (logEntry: LogEntry) =>
      this._timeFilter(logEntry) && this._stringFilter(logEntry);

    const newFilteredLogs = this.logs.filter(combinedFilter);

    if (
      JSON.stringify(newFilteredLogs) !== JSON.stringify(this._filteredLogs)
    ) {
      this._filteredLogs = newFilteredLogs;
    }
  }

  private updateColumnData(event: CustomEvent) {
    this._columnData = event.detail;
  }

  /**
   * Generates a log file in the specified format and initiates its download.
   *
   * @param {CustomEvent} event - The click event.
   */
  private downloadLogs(event: CustomEvent) {
    const headers = this.logs[0]?.fields.map((field) => field.key) || [];
    const maxWidths = headers.map((header) => header.length);
    const viewTitle = event.detail.viewTitle;
    const fileName = viewTitle ? titleCaseToKebabCase(viewTitle) : 'logs';

    this.logs.forEach((log) => {
      log.fields.forEach((field, columnIndex) => {
        maxWidths[columnIndex] = Math.max(
          maxWidths[columnIndex],
          field.value.toString().length,
        );
      });
    });

    const headerRow = headers
      .map((header, columnIndex) => header.padEnd(maxWidths[columnIndex]))
      .join('\t');
    const separator = '';
    const logRows = this.logs.map((log) => {
      const values = log.fields.map((field, columnIndex) =>
        field.value.toString().padEnd(maxWidths[columnIndex]),
      );
      return values.join('\t');
    });

    const formattedLogs = [headerRow, separator, ...logRows].join('\n');
    const blob = new Blob([formattedLogs], { type: 'text/plain' });
    const downloadLink = document.createElement('a');
    downloadLink.href = URL.createObjectURL(blob);
    downloadLink.download = `${fileName}.txt`;
    downloadLink.click();

    URL.revokeObjectURL(downloadLink.href);
  }

  render() {
    return html` <log-view-controls
        .columnData=${this._columnData}
        .viewId=${this.id}
        .hideCloseButton=${!this.isOneOfMany}
        .stateStore=${this._stateStore}
        @input-change="${this.updateFilter}"
        @clear-logs="${this.updateFilter}"
        @column-toggle="${this.toggleColumns}"
        @wrap-toggle="${this.toggleWrapping}"
        @download-logs="${this.downloadLogs}"
        role="toolbar"
      >
      </log-view-controls>

      <log-list
        .columnData=${[...this._columnData]}
        .lineWrap=${this._lineWrap}
        .viewId=${this.id}
        .logs=${this._filteredLogs}
        .searchText=${this.searchText}
        @update-column-data="${this.updateColumnData}"
      >
      </log-list>`;
  }
}