xref: /aosp_15_r20/external/perfetto/ui/src/plugins/com.example.ExampleState/index.ts (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {createStore, Store} from '../../base/store';
16import {exists} from '../../base/utils';
17import {Trace} from '../../public/trace';
18import {PerfettoPlugin} from '../../public/plugin';
19import {addQueryResultsTab} from '../../components/query_table/query_result_tab';
20
21interface State {
22  counter: number;
23}
24
25// This example plugin shows using state that is persisted in the
26// permalink.
27export default class implements PerfettoPlugin {
28  static readonly id = 'com.example.ExampleState';
29  private store: Store<State> = createStore({counter: 0});
30
31  private migrate(initialState: unknown): State {
32    if (
33      exists(initialState) &&
34      typeof initialState === 'object' &&
35      'counter' in initialState &&
36      typeof initialState.counter === 'number'
37    ) {
38      return {counter: initialState.counter};
39    } else {
40      return {counter: 0};
41    }
42  }
43
44  async onTraceLoad(ctx: Trace): Promise<void> {
45    this.store = ctx.mountStore((init: unknown) => this.migrate(init));
46    ctx.trash.use(this.store);
47
48    ctx.commands.registerCommand({
49      id: 'com.example.ExampleState#ShowCounter',
50      name: 'Show ExampleState counter',
51      callback: () => {
52        const counter = this.store.state.counter;
53        addQueryResultsTab(ctx, {
54          query: `SELECT ${counter} as counter;`,
55          title: `Show counter ${counter}`,
56        });
57        this.store.edit((draft) => {
58          ++draft.counter;
59        });
60      },
61    });
62  }
63}
64