๐Ÿ“ฆ situ2001 / obsidian-tab-group-arrangement

๐Ÿ“„ main.ts ยท 565 lines
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565import { App, Menu, Notice, Plugin, PluginSettingTab, setIcon, Setting, WorkspaceItem, WorkspaceLeaf, WorkspaceSplit, WorkspaceTabs } from 'obsidian';
import { debounce } from 'obsidian';

enum ARRANGEMENT_MODE {
  /**
   * Manual mode, nothing will happen when the active editor is focused or tab is clicked
   */
  MANUAL = "manual",

  /**
   * Automatically expand the active editor when it is focused
   */
  AUTO_EXPAND = "auto_expand",
}

/**
 * Icons for arrangement modes
 */
const iconForMode = {
  [ARRANGEMENT_MODE.MANUAL]: 'columns-2',
  [ARRANGEMENT_MODE.AUTO_EXPAND]: 'expand',
}

/**
 * Settings for the Editor Group Arrangement Plugin
 */
interface EditorGroupArrangementPluginSettings {
  mode: ARRANGEMENT_MODE;

  /**
   * Minimum height for inactive editor groups of a tab node when expanding active group 
   */
  MIN_HEIGHT_PX: number;

  /**
   * Minimum width for inactive editor groups of a tab node when expanding active group
   */
  MIN_WIDTH_PX: number;
}

const DEFAULT_SETTINGS: EditorGroupArrangementPluginSettings = {
  mode: ARRANGEMENT_MODE.MANUAL,
  MIN_HEIGHT_PX: 80,
  MIN_WIDTH_PX: 200,
};

export class EditorGroupArrangementPluginTab extends PluginSettingTab {
  plugin: EditorGroupArrangementPlugin;

  debouncedRearrange: () => void;

  constructor(app: App, plugin: EditorGroupArrangementPlugin) {
    super(app, plugin);
    this.plugin = plugin;

    this.debouncedRearrange = debounce(() => {
      if (this.plugin.settings.mode !== ARRANGEMENT_MODE.AUTO_EXPAND) return;
      this.plugin.executeModeAction();
    }, 100);
  }

  display(): void {
    const { containerEl } = this;
    containerEl.empty();

    new Setting(containerEl)
      .setName('Mode')
      .setDesc('Choose the mode for editor group arrangement')
      .addDropdown((dropdown) => {
        dropdown.addOption(ARRANGEMENT_MODE.MANUAL, "Manual arrangement");
        dropdown.addOption(ARRANGEMENT_MODE.AUTO_EXPAND, "Auto Expand Active Editor");
        dropdown.setValue(this.plugin.settings.mode);
        dropdown.onChange(async (value) => {
          this.plugin.settings.mode = value as ARRANGEMENT_MODE;
          await this.plugin.saveSettings();
        });
      })

    new Setting(containerEl)
      .setName('Minimum Width for Inactive Editor Groups')
      .setDesc('Minimum width for inactive editor groups of a tab node when expanding active group')
      .addSlider((slider) => {
        slider.setLimits(50, 250, 10);
        slider.setValue(this.plugin.settings.MIN_WIDTH_PX);
        slider.setDynamicTooltip();
        slider.onChange(async (value) => {
          this.plugin.settings.MIN_WIDTH_PX = value;
          await this.plugin.saveSettings();
          this.debouncedRearrange();
        });
      })
      .addExtraButton((button) => {
        button
          .setIcon("reset")
          .setTooltip("Reset to default")
          .onClick(async () => {
            this.plugin.settings.MIN_WIDTH_PX = DEFAULT_SETTINGS.MIN_WIDTH_PX;
            await this.plugin.saveSettings();
            this.debouncedRearrange();
            this.display();
          });
      });

    new Setting(containerEl)
      .setName('Minimum Height for Inactive Editor Groups')
      .setDesc('Minimum height for inactive editor groups of a tab node when expanding active group')
      .addSlider((slider) => {
        slider.setLimits(50, 250, 10);
        slider.setValue(this.plugin.settings.MIN_HEIGHT_PX);
        slider.setDynamicTooltip();
        slider.onChange(async (value) => {
          this.plugin.settings.MIN_HEIGHT_PX = value;
          await this.plugin.saveSettings();
          this.debouncedRearrange();
        });
      })
      .addExtraButton((button) => {
        button
          .setIcon("reset")
          .setTooltip("Reset to default")
          .onClick(async () => {
            this.plugin.settings.MIN_HEIGHT_PX = DEFAULT_SETTINGS.MIN_HEIGHT_PX;
            await this.plugin.saveSettings();
            this.debouncedRearrange();
            this.display();
          });
      });
  }
}

export default class EditorGroupArrangementPlugin extends Plugin {
  settings: EditorGroupArrangementPluginSettings;

  /**
   * Status bar item to show the current status of the plugin
   */
  private _statusBarItem: HTMLElement;

  async onload() {
    console.log("obsidian-editor-group-arrangement-plugin loaded");
    await this.loadSettings();
    this.addSettingTab(new EditorGroupArrangementPluginTab(this.app, this));
    this._registerCommands();
    this._registerEventListeners();
    this._setupStatusBarItem();
  }

  async onunload() {
    console.log("obsidian-editor-group-arrangement-plugin unloaded");
  }

  async loadSettings() {
    const settingsFromStorage = await this.loadData();
    // ensure the settings are valid
    if (settingsFromStorage) {
      this.settings = Object.assign({}, DEFAULT_SETTINGS, settingsFromStorage);
      if (!Object.values(ARRANGEMENT_MODE).includes(this.settings.mode)) {
        this.settings.mode = DEFAULT_SETTINGS.mode;
      }
    } else {
      this.settings = Object.assign({}, DEFAULT_SETTINGS);
    }
  }

  async saveSettings() {
    await this.saveData(this.settings);
  }

  /**
   * Execute the action based on the current mode
   */
  executeModeAction() {
    if (this.settings.mode === ARRANGEMENT_MODE.AUTO_EXPAND) {
      this._expandActiveLeaf();
    } else {
      this._arrangeEvenly();
    }
  }

  private _setupStatusBarItem() {
    this._statusBarItem = this.addStatusBarItem();
    this._statusBarItem.addClass('mod-clickable');

    this._statusBarItem.onClickEvent((e) => {
      const menu = new Menu();

      menu.addItem((item) => {
        item.setIsLabel(true);
        item.setTitle('Actions');
        item.setDisabled(true);
      });
      menu.addItem((item) => {
        item.setTitle('Arrange Evenly');
        item.setIcon("layout-grid");
        item.onClick(() => {
          this._arrangeEvenly();
        });
      });
      menu.addItem((item) => {
        item.setTitle('Expand Active Editor');
        item.setIcon("expand");
        item.onClick(() => {
          if (!this._isLeafUnderRootSplit(this.app.workspace.activeLeaf)) {
            new Notice('Should focus on an editor to expand');
            return;
          }
          this._expandActiveLeaf();
        });
      });

      // Mode switch
      menu.addItem((item) => {
        item.setIsLabel(true);
        item.setTitle('Mode');
        item.setDisabled(true);
      });
      menu.addItem((item) => {
        item.setTitle('Manual arrangement');
        item.setIcon("columns-2");
        item.setChecked(this.settings.mode === ARRANGEMENT_MODE.MANUAL);
        item.onClick((e) => {
          this.settings.mode = ARRANGEMENT_MODE.MANUAL;
          setIcon(this._statusBarItem, iconForMode[this.settings.mode]);
          this.saveSettings();
        });
      });
      menu.addItem((item) => {
        item.setTitle('Auto Expand Active Editor');
        item.setIcon("expand");
        item.setChecked(this.settings.mode === ARRANGEMENT_MODE.AUTO_EXPAND);
        item.onClick(async (e) => {
          this.settings.mode = ARRANGEMENT_MODE.AUTO_EXPAND;
          setIcon(this._statusBarItem, iconForMode[this.settings.mode]);
          await this.saveSettings();
        });
      });

      menu.showAtMouseEvent(e);
    });

    this._updateStatusBarItem();
  }

  private _updateStatusBarItem() {
    setIcon(this._statusBarItem, iconForMode[this.settings.mode]);
    this._statusBarItem.setAttribute('data-tooltip-position', 'top');
    this._statusBarItem.setAttribute('aria-label', 'Editor Group Arrangement');
  }

  private _registerCommands() {
    this.addCommand({
      id: 'arrange-evenly',
      name: 'Arrange Evenly',
      callback: () => {
        this._arrangeEvenly();
      },
      hotkeys: [
        // Control + Shift + R
        // {
        //   modifiers: ['Mod', 'Shift'],
        //   key: 'R'
        // }
      ]
    });

    this.addCommand({
      id: 'arrange-expand-active',
      name: 'Expand Active Editor',
      callback: () => {
        this._expandActiveLeaf();
      },
      hotkeys: [
        // Control + Shift + E
        // {
        //   modifiers: ['Mod', 'Shift'],
        //   key: 'E'
        // }
      ]
    });

    this.addCommand({
      id: 'toggle-mode-between-manual-and-auto-expand',
      name: 'Toggle Mode between Manual and Auto Expand',
      callback: async () => {
        if (this.settings.mode === ARRANGEMENT_MODE.MANUAL) {
          this.settings.mode = ARRANGEMENT_MODE.AUTO_EXPAND;
        } else {
          this.settings.mode = ARRANGEMENT_MODE.MANUAL;
        }
        await this.saveSettings();
        this._updateStatusBarItem();
        new Notice(`Mode switched to ${this.settings.mode}`);
      },
      hotkeys: []
    });

    // TODO feature to be implemented in the future
    // this.addCommand({
    //   id: 'arrange-editor-groups-collapse-maximize-active',
    //   name: 'Maximize Active Editor',
    //   callback: () => {
    //     // TODO
    //   },
    //   hotkeys: []
    // })
  }

  private _registerEventListeners() {
    this.registerDomEvent(document, 'click', (event) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.mod-root')) return;

      if (this.settings.mode === ARRANGEMENT_MODE.AUTO_EXPAND) {
        const closestElem = target.closest('.workspace-tab-header')
        if (closestElem) {
          this._expandActiveLeaf();
        }
      }
    });

    // TODO buggy: when we double on tab, the electron window will resize before the plugin can handle the event, and we cannot prevent it
    // this.registerDomEvent(document, 'dblclick', (event) => {
    //   const target = event.target as HTMLElement;
    //   if (!target.closest('.mod-root')) return;

    //   // check if it is in or is a tab item. class name of tab item is "workspace-tab-header" and "tappable"
    //   const closestElem = target.closest('.workspace-tab-header')
    //   if (closestElem) {
    //     // to prevent the default behavior of double click, which is to resize the window
    //     event.stopPropagation();
    //     event.preventDefault();
    //   }
    // });

    this.app.workspace.on('active-leaf-change', (leaf) => {
      // TODO buggy, it you create a new split node from tab node that exists in other split, it will not work. Since the active leaf is not changed...
      // FIXME: maybe we can listen to layout-change event
      if (this.settings.mode === ARRANGEMENT_MODE.AUTO_EXPAND && leaf && this._isLeafUnderRootSplit(leaf)) {
        this._expandActiveLeaf(leaf);
      }
    });

    this.registerDomEvent(window, 'resize',
      debounce(
        async () => {
          if (this.settings.mode === ARRANGEMENT_MODE.AUTO_EXPAND) {
            this._expandActiveLeaf();
          }
        },
        100
      )
    );
  }

  private _collectedNonLeafNodes() {
    const collectedNonLeafNodes: Set<WorkspaceItem> = new Set();
    this.app.workspace.iterateRootLeaves((leaf) => {
      let parent = leaf.parent;

      while (parent) {
        if (parent === this.app.workspace.rootSplit) {
          break;
        }
        if (collectedNonLeafNodes.has(parent)) {
          break;
        }

        collectedNonLeafNodes.add(parent);

        parent = parent.parent;
      }
    });

    return collectedNonLeafNodes;
  }

  /**
   * Remove all flex-grow style from node with type "tabs" and "split"
   */
  private _arrangeEvenly() {
    const collectedNonLeafNodes = this._collectedNonLeafNodes();

    collectedNonLeafNodes.forEach((node) => {
      // @ts-ignore. Since it is a private property
      const el = node.containerEl as HTMLElement;
      if (!el) return;
      el.style.flexGrow = '';
    });
  }

  /**
   * Get the path ascendants of a node (not including the root node)
   */
  private _getPathAscendants(node: WorkspaceLeaf): Array<WorkspaceItem> {
    const pathAscendants: Array<WorkspaceItem> = [];
    let parent = node.parent;
    while (parent) {
      if (parent === this.app.workspace.rootSplit) {
        break;
      }

      pathAscendants.push(parent);
      parent = parent.parent;
    }

    return pathAscendants;
  }

  private _isLeafUnderRootSplit(leaf: WorkspaceItem | null): boolean {
    if (!leaf) return false;

    let parent = leaf.parent;
    while (parent) {
      if (parent === this.app.workspace.rootSplit) {
        return true;
      }
      parent = parent.parent;
    }

    return false;
  }

  /**
   * Enlarge the active tab node and shrink the rest to a minimum size
   */
  private _expandActiveLeaf(leaf?: WorkspaceLeaf) {
    const activeLeaf = leaf || this.app.workspace.activeLeaf;
    if (
      !activeLeaf
      || !this._isLeafUnderRootSplit(activeLeaf)
    ) {
      throw new Error('The active leaf is not under root split');
    }

    /**
     * calculate the minimum size for each tab node and split node, in a bottom-up manner
     * 
     * the size(width and height) will be saved in @param minSizeMap
     */
    const doRecurForSizeCalculation = (root: WorkspaceItem, minSizeMap: Map<WorkspaceItem, [number, number]>): [number, number] => {
      if (root instanceof WorkspaceSplit) {
        // @ts-ignore Since it is a private property
        const children = root.children;
        for (const child of children) {
          const [width, height] = doRecurForSizeCalculation(child, minSizeMap);
          minSizeMap.set(child, [width, height]);
        }

        // get horizontal or vertical split, then calculate the minimum size for this split node itself
        // @ts-ignore Since it is a private property
        const isVertical = root.direction === "vertical";
        // @ts-ignore Since it is a private property
        const isHorizontal = root.direction === "horizontal";

        let minSizeOfCurrentNode = [0, 0];
        for (const child of children) {
          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
          const [width, height] = minSizeMap.get(child)!;
          if (isVertical) {
            minSizeOfCurrentNode = [minSizeOfCurrentNode[0] + width, Math.max(minSizeOfCurrentNode[1], height)];
          } else if (isHorizontal) {
            minSizeOfCurrentNode = [Math.max(minSizeOfCurrentNode[0], width), minSizeOfCurrentNode[1] + height];
          } else {
            throw new Error('Unexpected direction');
          }
        }

        return [minSizeOfCurrentNode[0], minSizeOfCurrentNode[1]];
      } else {
        // reach the bottom, time to return. Here, we ensure bottom is a tab node
        if (!(root instanceof WorkspaceTabs)) throw new Error('Unexpected node type'); // TODO show error message
        return [this.settings.MIN_WIDTH_PX, this.settings.MIN_HEIGHT_PX];
      }
    }

    /**
     * Resize based on the minimum size calculated before.
     * 
     * After resizing, the expanded node should have a large enough size, and the rest should have a minimum size.
     */
    const doRecurForResize = (root: WorkspaceItem, minSizeMap: Map<WorkspaceItem, [number, number]>, pathAscendants: Array<WorkspaceItem>) => {
      if (!(root instanceof WorkspaceSplit)) return;

      // @ts-ignore Since it is a private property
      const children = root.children;

      // @ts-ignore Since it is a private property
      const containerEl = root.containerEl as HTMLElement;
      const containerSize = containerEl.getBoundingClientRect();
      const containerWidth = containerSize.width;
      const containerHeight = containerSize.height;

      // get horizontal or vertical split, then calculate the minimum size for this split node itself
      // @ts-ignore Since it is a private property
      const isVertical = root.direction === "vertical";
      // @ts-ignore Since it is a private property
      const isHorizontal = root.direction === "horizontal";

      // sum up the width or height of non-path nodes
      let weightOrHeightOfNonPathNode = 0;
      for (const child of children) {
        // On the path or it is a leaf node
        if (
          pathAscendants.includes(child)
          || child instanceof WorkspaceLeaf
        ) {
          continue;
        }

        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const [width, height] = minSizeMap.get(child)!;
        if (isVertical) {
          weightOrHeightOfNonPathNode += width;
        } else if (isHorizontal) {
          weightOrHeightOfNonPathNode += height;
        } else {
          throw new Error('Unexpected direction');
        }
      }

      let weightOrHeightOfPathNode = 0;
      if (isVertical) {
        weightOrHeightOfPathNode = containerWidth - weightOrHeightOfNonPathNode;
      } else if (isHorizontal) {
        weightOrHeightOfPathNode = containerHeight - weightOrHeightOfNonPathNode;
      } else {
        throw new Error('Unexpected direction');
      }

      // ensure the minimum size
      weightOrHeightOfPathNode = Math.max(weightOrHeightOfPathNode,
        isHorizontal ? this.settings.MIN_HEIGHT_PX : this.settings.MIN_WIDTH_PX
      );

      // transform px to percentage
      const isPathNodeExist = (children as WorkspaceItem[]).some((child: WorkspaceItem) => pathAscendants.includes(child));
      const flexGrowOfPathNode = 100 * weightOrHeightOfPathNode / (weightOrHeightOfPathNode + weightOrHeightOfNonPathNode);
      const flexGrowOfNonPathNode = isPathNodeExist
        ? (100 * weightOrHeightOfNonPathNode / (weightOrHeightOfPathNode + weightOrHeightOfNonPathNode)) / Math.max(children.length - 1, 1)
        : (100 * weightOrHeightOfNonPathNode / (weightOrHeightOfNonPathNode)) / Math.max(children.length, 1)

      // set flexGrow for each child
      for (const child of children) {
        const containerEl = child.containerEl as HTMLElement;
        if (pathAscendants.includes(child)) {
          containerEl.style.flexGrow = flexGrowOfPathNode.toString();
        } else {
          containerEl.style.flexGrow = flexGrowOfNonPathNode.toString();
        }
        doRecurForResize(child, minSizeMap, pathAscendants);
      }
    }

    const rootNode = this.app.workspace.rootSplit;
    const minSizeMap = new Map<WorkspaceItem, [number, number]>();
    const pathAscendants = this._getPathAscendants(activeLeaf);

    const rootSize = doRecurForSizeCalculation(rootNode, minSizeMap);
    minSizeMap.set(rootNode, [rootSize[0], rootSize[1]]);

    // TODO if small root split is small, we need to handle it differently
    doRecurForResize(rootNode, minSizeMap, pathAscendants);
  }
}