File size: 9,246 Bytes
71174bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { loadedPlugins } from "@/Plugins/LoadedPlugins";
import { matchesTag } from "@/Plugins/Core/ActivityFocus/ActivityFocusUtils";
import { Vue } from "vue-class-component";

export type IMenuEntry = IMenuItem | IMenuSubmenu;

export enum MenuItemType {
    Action,
    Submenu,
    Separator,
}

export interface IMenuSeparator {
    type: MenuItemType;
}

export interface IMenuSubmenu {
    // This doesn't have an action, but contains items that may have actions (or
    // themselves be other submenus).

    // Using text to match IMenuItem.
    text: string;
    items: IMenuEntry[];
    type: MenuItemType;
    _rank?: number;
}

export interface IMenuItem {
    path: string[] | string | undefined; // Directory structure, ending in text label
    function?: () => void;
    checkPluginAllowed?: (_?: any) => string | boolean;
    type?: MenuItemType; // If absent, will assume MenuItemType.ACTION
    hotkey?: string;
    pluginId?: string;
    text?: string;

    // Below used internally, not from plugin.
    _rank?: number;
    _pathNames?: string[];
}

export interface IMenuPathInfo {
    rank: number | undefined;
    text: string;
}

/**
 * MenuLevelParent component
 */
export class MenuLevelParent extends Vue {
    /**
     * Determines if a menu item is an action.
     *
     * @param {IMenuEntry | IMenuSeparator} item  The menu item to check.
     * @returns {boolean} True if the item is an action.
     */
    isAction(item: IMenuEntry | IMenuSeparator): boolean {
        return item.type === MenuItemType.Action;
    }

    /**
     * Determines if a menu item is a separator.
     *
     * @param {IMenuEntry | IMenuSeparator} item  The menu item to check.
     * @returns {boolean} True if the item is a separator.
     */
    isSeparator(item: IMenuEntry | IMenuSeparator): boolean {
        return item.type === MenuItemType.Separator;
    }

    /**
     * Gets the submenu items for a menu item. They are sorted.
     *
     * @param {IMenuEntry} item  The menu item.
     * @returns {IMenuEntry[]}  The submenu items.
     */
    getItems(item: IMenuEntry): IMenuEntry[] {
        const {items} = item as IMenuSubmenu;
        menuDataSorted(items);
        return items;
    }
}

/**
 * Given a list of menu entries, does one of them have a given name?
 *
 * @param  {IMenuEntry[]} menuDat List of menu entries.
 * @param  {string}       name    Name to look for.
 * @returns {boolean} True if found, false otherwise.
 */
function _isNameInMenuData(menuDat: IMenuEntry[], name: string): boolean {
    return menuDat.map((m: IMenuEntry) => m.text).includes(name);
}

/**
 * Given menu data, get the submenu of an item with a given name.
 *
 * @param  {IMenuEntry[]} menuDat  List of menu entries.
 * @param  {string}       name     Name of submenu to get.
 * @returns {IMenuSubmenu} Submenu with the given name.
 */
function _getSubMenu(menuDat: IMenuEntry[], name: string): IMenuSubmenu {
    return menuDat.find(
        (m) => (m as IMenuSubmenu).text === name
    ) as IMenuSubmenu;
}

/**
 * Given any kind of menu path (string[], string, etc.), returns the menu path
 * info.
 *
 * @param  {string[]|string|null|undefined} menuPath  Menu path.
 * @returns {IMenuPathInfo}  Menu path info.
 */
export function processMenuPath(
    menuPath: string[] | string | null | undefined
): IMenuPathInfo[] | null {
    if (menuPath === null || menuPath === undefined) {
        return null;
    }

    if (typeof menuPath === "string") {
        menuPath = menuPath.split("/");
    }

    // If you get here, it's an array of strings.

    // Extract the rank, if any.
    return menuPath.map((m) => _extractRankFromText(m));
}

/**
 * Extract the rank in menu text, if any.
 *
 * @param  {string} text  Text to extract rank from.
 * @returns {IMenuPathInfo} Contains both the rank and the text with ranked removed.
 */
function _extractRankFromText(text: string): IMenuPathInfo {
    const rankInfo = text.match(/^\[(\d+)\]/);
    let rank: number | undefined = undefined;
    if (rankInfo) {
        rank = parseInt(rankInfo[1]);
        text = text.replace(/^\[\d+\]/, "").trim();

        // If rank is not between 0 and 10, throw an error.
        if (rank < 0 || rank > 10) {
            throw new Error("Rank must be between 0 and 10. Found: " + rank);
        }
    }

    return { rank, text };
}

/**
 * Sets defaults on menu items, for cases when not specified in plugins. All
 * this in place, so no need to return anything.
 *
 * @param  {IMenuItem} newMenuItem  Menu item, with defaults set.
 */
function _setNewMenuItemDefaults(newMenuItem: IMenuItem) {
    // If type is not set, default to MenuItemType.ACTION.
    if (newMenuItem.type === undefined) {
        newMenuItem.type = MenuItemType.Action;
    }

    // If rank is not set, default to 5.
    // if (newMenuItem._rank === undefined) {
    //     newMenuItem._rank = 5;
    // }

    // // If rank is not between 0 and 10, throw an error.
    // if (newMenuItem._rank < 0 || newMenuItem._rank > 10) {
    //     throw new Error("Rank must be between 0 and 10.");
    // }
}

/**
 * Add an entry to the menu system.
 *
 * @param  {IMenuItem} newMenuItem           Menu item to add.
 * @param  {IMenuEntry[]} existingMenuItems  List of existing menu items.
 * @param  {string} [pluginId]               Plugin id to add. Optional.
 * @returns {IMenuEntry[]}  The new menu, with the entry added.
 */
export function addMenuItem(
    newMenuItem: IMenuItem,
    existingMenuItems: IMenuEntry[],
    pluginId?: string
): IMenuEntry[] {
    // if (api.sys.loadStatus.menuFinalized) {
    //     // Error: Menu already finalized. Assert
    //     throw new Error("Menu already finalized.");
    // }
    if (newMenuItem.path === null) {
        // One of the rare plugins that does't use the menu system.
        return existingMenuItems;
    }

    // If tags don't match, don't add the menu item.
    if (pluginId !== undefined) {
        const plugin = loadedPlugins[pluginId as string]
        const {tags} = plugin;
        if (!matchesTag(tags)) {
            return existingMenuItems;
        }
    }

    // Plugin is excluded per the plugin user parameter
    // if (
    //     pluginId !== undefined &&
    //     LoadedPlugins.alwaysEnabledPlugins.indexOf(pluginId) === -1
    // ) {
    //     return existingMenuItems;
    // }

    const menuPathInfo = processMenuPath(newMenuItem.path);
    const actionItem = menuPathInfo?.pop();

    // Separate path data to _text and _pathNames rather than path.
    newMenuItem.text = actionItem?.text;
    newMenuItem._pathNames = menuPathInfo?.map((m) => m.text);
    newMenuItem.path = undefined;

    // Add rank too
    newMenuItem._rank = actionItem?.rank;

    _setNewMenuItemDefaults(newMenuItem);

    let existingMenuItemsPlaceholder = existingMenuItems;
    for (let i = 0; i < (menuPathInfo as IMenuPathInfo[]).length; i++) {
        // Get rank and pathName from text.
        const pathNameWithoutRank = (menuPathInfo as IMenuPathInfo[])[i].text;
        const {rank} = (menuPathInfo as IMenuPathInfo[])[i];

        if (
            !_isNameInMenuData(
                existingMenuItemsPlaceholder,
                pathNameWithoutRank
            )
        ) {
            // This level doesn't exist, so add it.
            existingMenuItemsPlaceholder.push({
                type: MenuItemType.Submenu,
                text: pathNameWithoutRank,
                items: [],
                _rank: rank,
            } as IMenuSubmenu);
        }

        const subMenu = _getSubMenu(
            existingMenuItemsPlaceholder,
            pathNameWithoutRank
        );

        // Check whether to update rank.
        if (rank !== undefined) {
            if (subMenu._rank === undefined) {
                subMenu._rank = rank;
            } else if (subMenu._rank !== rank) {
                // Error: Rank already set. Assert
                throw new Error(
                    `Plugin "${pluginId}" set rank of "${subMenu.text}" menu item to ${rank}, but it is already set to ${subMenu._rank}.`
                );
            }
        }

        existingMenuItemsPlaceholder = subMenu.items;
    }

    // You've gone down all the levels in pathNames, so add the item.
    existingMenuItemsPlaceholder.push(newMenuItem);

    // Return the whole menu-data object.
    return existingMenuItems;
}

/**
 * Sort menu data by rank, then by text if rank equal. In place, so no need to
 * return anything.
 *
 * @param  {IMenuEntry[]} menuData  Menu data to sort.
 */
export function menuDataSorted(menuData: IMenuEntry[]) {
    menuData.sort((a: IMenuEntry, b: IMenuEntry) => {
        // Sort the items by rank. Defaults to 5 if not set.
        const a_rank = a._rank !== undefined ? a._rank : 5;
        const b_rank = b._rank !== undefined ? b._rank : 5;
        if (a_rank < b_rank) {
            return -1;
        }
        if (a_rank > b_rank) {
            return 1;
        }

        // If ranks are equal, sort by text.
        const a_text = a.text as string;
        const b_text = b.text as string;
        if (a_text < b_text) {
            return -1;
        }
        if (a_text > b_text) {
            return 1;
        }

        return 0;
    });
}