aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/ContextMenu.tsx
blob: e0eeb3f5300443f90a29cfccc71f059e2993e408 (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
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, IReactionDisposer, makeObservable, observable, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { DivHeight, DivWidth } from '../../ClientUtils';
import { SnappingManager } from '../util/SnappingManager';
import './ContextMenu.scss';
import { ContextMenuItem, ContextMenuProps } from './ContextMenuItem';
import { ObservableReactComponent } from './ObservableReactComponent';

@observer
export class ContextMenu extends ObservableReactComponent<{ noexpand?: boolean }> {
    // eslint-disable-next-line no-use-before-define
    static Instance: ContextMenu;

    private _ignoreUp = false;
    private _reactionDisposer?: IReactionDisposer;
    private _defaultPrefix: string = '';
    private _defaultItem: ((name: string) => void) | undefined;
    private _onDisplay?: () => void = undefined;

    @observable.shallow _items: ContextMenuProps[] = [];
    @observable _pageX: number = 0;
    @observable _pageY: number = 0;
    @observable _display: boolean = false;
    @observable _searchString: string = '';
    @observable _showSearch: boolean = false;
    // afaik displaymenu can be called before all the items are added to the menu, so can't determine in displayMenu what the height of the menu will be
    @observable _yRelativeToTop: boolean = true;
    @observable _selectedIndex = -1;

    @observable _width: number = 0;
    @observable _height: number = 0;

    @observable _mouseX: number = -1;
    @observable _mouseY: number = -1;
    @observable _shouldDisplay: boolean = false;

    constructor(props: object) {
        super(props);
        makeObservable(this);
        ContextMenu.Instance = this;
    }

    public setIgnoreEvents(ignore: boolean) {
        this._ignoreUp = ignore;
    }

    @action
    onPointerDown = (e: PointerEvent) => {
        this._mouseX = e.clientX;
        this._mouseY = e.clientY;
    };
    @action
    onPointerUp = (e: PointerEvent) => {
        if (e.button !== 2 && !e.ctrlKey) return;
        const curX = e.clientX;
        const curY = e.clientY;
        if (this._ignoreUp) {
            this._ignoreUp = false;
            return;
        }
        if (Math.abs(this._mouseX - curX) > 1 || Math.abs(this._mouseY - curY) > 1) {
            this._shouldDisplay = false;
        }

        if (this._shouldDisplay) {
            if (this._onDisplay) {
                this._onDisplay();
            } else {
                this._display = true;
            }
        }
    };
    componentWillUnmount() {
        document.removeEventListener('pointerdown', this.onPointerDown, true);
        document.removeEventListener('pointerup', this.onPointerUp);
        this._reactionDisposer?.();
    }

    componentDidMount() {
        document.addEventListener('pointerdown', this.onPointerDown, true);
        document.addEventListener('pointerup', this.onPointerUp);
    }

    @action
    clearItems() {
        this._items.length = 0;
        this._defaultPrefix = '';
        this._defaultItem = undefined;
    }

    findByDescription = (target: string, toLowerCase = false) =>
        this._items.find(menuItem => 
            (toLowerCase ?  menuItem.description.toLowerCase() : menuItem.description) === target); // prettier-ignore

    @action
    addItem(item: ContextMenuProps) {
        !this._items.includes(item) && this._items.push(item);
    }

    @action
    moveAfter(item: ContextMenuProps, after?: ContextMenuProps) {
        const curInd = this._items.findIndex(i => i.description === item.description);
        this._items.splice(curInd, 1);
        const afterInd = after && this.findByDescription(after.description) ? this._items.findIndex(i => i.description === after.description) : this._items.length;
        this._items.splice(afterInd, 0, item);
    }

    @action
    setDefaultItem(prefix: string, item: (name: string) => void) {
        this._defaultPrefix = prefix;
        this._defaultItem = item;
    }

    static readonly buffer = 20;
    get pageX() {
        return this._pageX + this._width > window.innerWidth - ContextMenu.buffer ? window.innerWidth - ContextMenu.buffer - this._width : Math.max(0, this._pageX);
    }

    get pageY() {
        return this._pageY + this._height > window.innerHeight - ContextMenu.buffer ? window.innerHeight - ContextMenu.buffer - this._height : Math.max(0, this._pageY);
    }

    @action
    displayMenu = (x: number, y: number, initSearch = '', showSearch = false, onDisplay?: () => void) => {
        // maxX and maxY will change if the UI/font size changes, but will work for any amount
        // of items added to the menu

        this._showSearch = showSearch;
        this._pageX = x;
        this._pageY = y;
        this._searchString = initSearch;
        this._shouldDisplay = true;
        this._onDisplay = onDisplay;
        this._display = !onDisplay;
    };

    @action
    closeMenu = () => {
        const wasOpen = this._display;
        this.clearItems();
        this._display = false;
        this._shouldDisplay = false;
        return wasOpen;
    };

    @computed get filteredItems(): (ContextMenuProps | string[])[] {
        const searchString = this._searchString.toLowerCase().split(' ');
        const matches = (descriptions: string[]) => searchString.every(s => descriptions.some(desc => desc.toLowerCase().includes(s)));
        const flattenItems = (items: ContextMenuProps[], groupFunc: (groupName: string) => string[]) => {
            let eles: (ContextMenuProps | string[])[] = [];

            const leaves: ContextMenuProps[] = [];
            items.forEach(item => {
                const { description } = item;
                const path = groupFunc(description);
                if (item.subitems) {
                    const children = flattenItems(item.subitems, name => [...groupFunc(description), name]);
                    if (children.length || matches(path)) {
                        eles.push(path);
                        eles = eles.concat(children);
                    }
                } else if (matches(path)) {
                    leaves.push(item as ContextMenuProps);
                }
            });

            eles = [...leaves, ...eles];

            return eles;
        };
        return flattenItems(this._items.slice(), name => [name]);
    }

    @computed get flatItems(): ContextMenuProps[] {
        return this.filteredItems.filter(item => !Array.isArray(item)) as ContextMenuProps[];
    }

    @computed get menuItems() {
        if (!this._searchString) {
            return this._items.map((item, ind) => <ContextMenuItem key={item.description + ind} {...item} selected={ind === this._selectedIndex} noexpand={this.itemsNeedSearch ? true : item.noexpand} closeMenu={this.closeMenu} />);
        }
        return this.filteredItems.map((value, index) =>
            Array.isArray(value) ? (
                <div
                    key={index + value.join(' -> ')}
                    className="contextMenu-group"
                    style={{
                        background: SnappingManager.userVariantColor,
                    }}>
                    <div className="contextMenu-description">{value.join(' -> ')}</div>
                </div>
            ) : (
                <ContextMenuItem {...value} key={index + value.description} closeMenu={this.closeMenu} selected={index === this._selectedIndex} />
            )
        );
    }

    @computed get itemsNeedSearch() {
        return this._showSearch ? 1 : this._items.reduce((p, mi) => p + (mi.noexpand ? 1 : mi.subitems?.length || 1), 0) > 15;
    }

    _searchRef = React.createRef<HTMLInputElement>(); // bcz: we shouldn't need this, since we set autoFocus on the <input> tag, but for some reason we do...

    render() {
        this.itemsNeedSearch && setTimeout(() => this._searchRef.current?.focus());
        return (
            <div
                className="contextMenu-cont"
                ref={r =>
                    runInAction(() => {
                        if (r) {
                            this._width = DivWidth(r);
                            this._height = DivHeight(r);
                        }
                        this._searchRef.current?.focus();
                    })
                }
                style={{
                    display: this._display ? '' : 'none',
                    left: this.pageX,
                    ...(this._yRelativeToTop ? { top: Math.max(0, this.pageY) } : { bottom: this.pageY }),
                    background: SnappingManager.userBackgroundColor,
                    color: SnappingManager.userColor,
                }}>
                {!this.itemsNeedSearch ? null : (
                    <span className="contextMenu-search">
                        <span className="contextMenu-searchIcon">
                            <FontAwesomeIcon icon="search" size="lg" />
                        </span>
                        <input ref={this._searchRef} style={{ color: 'black' }} className="contextMenu-searchInput" type="text" placeholder="Filter Menu..." value={this._searchString} onKeyDown={this.onKeyDown} onChange={this.onChange} autoFocus />
                    </span>
                )}
                {this.menuItems}
            </div>
        );
    }

    @action
    setLangIndex = (ind: number) => {
        this._selectedIndex = ind;
    };

    @action
    onKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'ArrowDown') {
            if (this._selectedIndex < this.flatItems.length - 1) {
                this._selectedIndex++;
            }
            e.preventDefault();
        } else if (e.key === 'ArrowUp') {
            if (this._selectedIndex > 0) {
                this._selectedIndex--;
            }
            e.preventDefault();
        } else if (e.key === 'Enter' || e.key === 'Tab') {
            const item = this.flatItems[this._selectedIndex];
            if (item.event) {
                item.event({ x: this.pageX, y: this.pageY });
            } else {
                // if (this._searchString.startsWith(this._defaultPrefix)) {
                this._defaultItem?.(this._searchString.substring(this._defaultPrefix.length));
            }
            this.closeMenu();
            e.preventDefault();
            e.stopPropagation();
        }
    };

    @action
    onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        this._searchString = e.target.value;
        if (!this._searchString) {
            this._selectedIndex = -1;
        } else if (this._selectedIndex === -1) {
            this._selectedIndex = 0;
        } else {
            this._selectedIndex = Math.min(this.flatItems.length - 1, this._selectedIndex);
        }
    };
}