obsidian#Command TypeScript Examples

The following examples show how to use obsidian#Command. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: commandHandler.ts    From obsidian-switcher-plus with GNU General Public License v3.0 6 votes vote down vote up
getItems(): Command[] {
    // Sort commands by their name
    const items: Command[] = this.app.commands.listCommands().sort((a, b) => {
      if (a.name < b.name) return -1;
      if (a.name > b.name) return 1;
      return 0;
    });

    // Pinned commands should be at the top (if any)
    if (
      this.isCommandPalettePluginEnabled() &&
      this.getCommandPalettePluginInstance()?.options.pinned?.length > 0
    ) {
      const pinnedCommandIds = this.getCommandPalettePluginInstance().options.pinned;

      // We're gonna find the pinned command in `items` and move it to the beginning
      // Therefore we need to perform "for each right"
      for (let i = pinnedCommandIds.length - 1; i >= 0; i--) {
        const commandId = pinnedCommandIds[i];
        const commandIndex = items.findIndex((c) => c.id === commandId);
        if (commandIndex > -1) {
          const command = items[commandIndex];
          items.splice(commandIndex, 1);
          items.unshift(command);
        }
      }
    }

    return items;
  }
Example #2
Source File: commandSuggester.ts    From obsidian-customizable-sidebar with MIT License 6 votes vote down vote up
async onChooseItem(item: Command, evt: MouseEvent | KeyboardEvent): Promise<void> {
		if (item.icon) {
			this.plugin.addRibbonIcon(item.icon ?? "", item.name, () => {
				//@ts-ignore
				this.app.commands.executeCommandById(item.id);
			})
			this.plugin.settings.sidebarCommands.push(item);
			await this.plugin.saveSettings();
			setTimeout(() => {
				dispatchEvent(new Event("CS-addedCommand"));
			}, 100);
		} else {
			new IconPicker(this.plugin, item).open()
		}
	}
Example #3
Source File: commandSuggester.ts    From obsidian-customizable-sidebar with MIT License 6 votes vote down vote up
export default class CommandSuggester extends FuzzySuggestModal<Command> {

	constructor(private plugin: CustomSidebarPlugin) {
		super(plugin.app);
	}

	getItems(): Command[] {
		//@ts-ignore
		return this.app.commands.listCommands();
	}

	getItemText(item: Command): string {
		return item.name;
	}

	async onChooseItem(item: Command, evt: MouseEvent | KeyboardEvent): Promise<void> {
		if (item.icon) {
			this.plugin.addRibbonIcon(item.icon ?? "", item.name, () => {
				//@ts-ignore
				this.app.commands.executeCommandById(item.id);
			})
			this.plugin.settings.sidebarCommands.push(item);
			await this.plugin.saveSettings();
			setTimeout(() => {
				dispatchEvent(new Event("CS-addedCommand"));
			}, 100);
		} else {
			new IconPicker(this.plugin, item).open()
		}
	}

}
Example #4
Source File: settingsTab.ts    From obsidian-customizable-sidebar with MIT License 6 votes vote down vote up
private async moveCommand(command: Command, direction: 'up' | 'down') {
		// Move command in settings
		const commands = this.plugin.settings.sidebarCommands;
		const index = commands.indexOf(command);
		if (direction === 'up') {
			commands.splice(index - 1, 0, commands.splice(index, 1)[0]);
		} else {
			commands.splice(index + 1, 0, commands.splice(index, 1)[0]);
		}
		await this.plugin.saveSettings();
		this.display();

		// Move command button in left ribbon
		const ribbonButton = Array.from(this.leftRibbonPanel.children)
			.find((btn) => command.name === btn.getAttribute('aria-label'));
		if (direction === 'up') {
			ribbonButton.previousSibling.before(ribbonButton);
		} else {
			ribbonButton.nextSibling.after(ribbonButton);
		}
	}
Example #5
Source File: commandMode.fixture.ts    From obsidian-switcher-plus with GNU General Public License v3.0 5 votes vote down vote up
export function makeCommandItem(options?: { id?: string; name?: string }): Command {
  return {
    id: options?.id ?? chance.word(),
    name: options?.name ?? chance.word(),
  };
}
Example #6
Source File: commandSuggester.ts    From obsidian-customizable-sidebar with MIT License 5 votes vote down vote up
getItems(): Command[] {
		//@ts-ignore
		return this.app.commands.listCommands();
	}
Example #7
Source File: commandSuggester.ts    From obsidian-customizable-sidebar with MIT License 5 votes vote down vote up
getItemText(item: Command): string {
		return item.name;
	}
Example #8
Source File: iconPicker.ts    From obsidian-customizable-sidebar with MIT License 5 votes vote down vote up
constructor(plugin: CustomSidebarPlugin, command: Command, editMode = false) {
		super(plugin.app);
		this.plugin = plugin;
		this.command = command;
		this.editMode = editMode;
		this.setPlaceholder("Pick an icon");
	}
Example #9
Source File: iconPicker.ts    From obsidian-customizable-sidebar with MIT License 5 votes vote down vote up
command: Command;
Example #10
Source File: commandHandler.test.ts    From obsidian-switcher-plus with GNU General Public License v3.0 4 votes vote down vote up
describe('commandHandler', () => {
  let settings: SwitcherPlusSettings;
  let mockApp: MockProxy<App>;
  let mockInternalPlugins: MockProxy<InternalPlugins>;
  let mockCommandPalettePluginInstance: MockProxy<CommandPalettePluginInstance>;
  let mockCommands: Command[];
  let sut: CommandHandler;

  beforeAll(() => {
    const commandPalettePluginInstall = makeCommandPalettePluginInstall();
    mockCommandPalettePluginInstance =
      commandPalettePluginInstall.instance as MockProxy<CommandPalettePluginInstance>;

    mockCommands = [
      makeCommandItem(),
      makeCommandItem(),
      makeCommandItem(),
      makeCommandItem(),
      makeCommandItem({ name: expectedCommandName }),
    ];

    mockInternalPlugins = makeInternalPluginList(commandPalettePluginInstall);
    mockApp = mock<App>({
      internalPlugins: mockInternalPlugins,
      commands: {
        listCommands: jest.fn(() => mockCommands),
        executeCommandById: jest.fn(),
      },
    });

    settings = new SwitcherPlusSettings(null);
    jest.spyOn(settings, 'commandListCommand', 'get').mockReturnValue(commandTrigger);

    sut = new CommandHandler(mockApp, settings);
  });

  describe('commandString', () => {
    it('should return commandListCommand trigger', () => {
      expect(sut.commandString).toBe(commandTrigger);
    });
  });

  describe('validateCommand', () => {
    let inputText: string;
    let startIndex: number;
    const filterText = 'foo';

    beforeAll(() => {
      inputText = `${commandTrigger}${filterText}`;
      startIndex = commandTrigger.length;
    });

    it('should validate parsed input', () => {
      const inputInfo = new InputInfo(inputText);

      sut.validateCommand(inputInfo, startIndex, filterText, null, null);
      expect(inputInfo.mode).toBe(Mode.CommandList);

      const commandListCmd = inputInfo.parsedCommand();
      expect(commandListCmd.parsedInput).toBe(filterText);
      expect(commandListCmd.isValidated).toBe(true);
    });
  });

  describe('getSuggestions', () => {
    test('with falsy input, it should return an empty array', () => {
      const results = sut.getSuggestions(null);

      expect(results).not.toBeNull();
      expect(results).toBeInstanceOf(Array);
      expect(results).toHaveLength(0);
    });

    test('with default settings, it should return suggestions for command list mode', () => {
      const inputInfo = new InputInfo(commandTrigger);
      const results = sut.getSuggestions(inputInfo);

      expect(results).not.toBeNull();
      expect(results).toBeInstanceOf(Array);

      const resultCommandIds = new Set(results.map((sugg) => sugg.item.id));

      expect(results).toHaveLength(mockCommands.length);
      expect(mockCommands.every((command) => resultCommandIds.has(command.id))).toBe(
        true,
      );
      expect(results.every((sugg) => sugg.type === 'command')).toBe(true);
      expect(mockInternalPlugins.getPluginById).toHaveBeenCalledWith(
        COMMAND_PALETTE_PLUGIN_ID,
      );
    });

    test('with filter search term, it should return only matching suggestions for command list mode', () => {
      const filterText = expectedCommandName;

      const expectedItem = mockCommands.find(
        (command) => command.name === expectedCommandName,
      );

      const mockPrepareQuery = jest.mocked<typeof prepareQuery>(prepareQuery);
      mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));

      const mockFuzzySearch = jest.mocked<typeof fuzzySearch>(fuzzySearch);

      mockFuzzySearch.mockImplementation((_q, text: string) => {
        const match = makeFuzzyMatch();
        return text.startsWith(filterText) ? match : null;
      });

      const inputInfo = new InputInfo(`${commandTrigger}${filterText}`);
      const results = sut.getSuggestions(inputInfo);

      expect(results).toBeInstanceOf(Array);
      expect(results).toHaveLength(1);

      const onlyResult = results[0];
      expect(onlyResult).toHaveProperty('type', 'command');
      expect(onlyResult.item.id).toBe(expectedItem.id);
      expect(onlyResult.item.name).toBe(expectedItem.name);

      expect(mockFuzzySearch).toHaveBeenCalled();
      expect(mockPrepareQuery).toHaveBeenCalled();
      expect(mockInternalPlugins.getPluginById).toHaveBeenCalled();

      mockFuzzySearch.mockReset();
    });
  });

  describe('renderSuggestion', () => {
    it('should not throw an error with a null suggestion', () => {
      expect(() => sut.renderSuggestion(null, null)).not.toThrow();
    });

    it('should render a suggestion with match offsets', () => {
      const mockParentEl = mock<HTMLElement>();
      const mockRenderResults = jest.mocked<typeof renderResults>(renderResults);

      const match = makeFuzzyMatch();
      const item = mockCommands[0];

      const sugg = mock<CommandSuggestion>({ item, match });
      sut.renderSuggestion(sugg, mockParentEl);

      expect(mockRenderResults).toHaveBeenCalledWith(mockParentEl, item.name, match);
    });
  });

  describe('onChooseSuggestion', () => {
    it('should not throw an error with a null suggestion', () => {
      expect(() => sut.onChooseSuggestion(null)).not.toThrow();
    });

    it('should tell the app to execute the command with the chosen ID', () => {
      const match = makeFuzzyMatch();
      const item = mockCommands[0];

      const sugg = mock<CommandSuggestion>({ item, match });

      sut.onChooseSuggestion(sugg);

      expect(mockInternalPlugins.getPluginById).toHaveBeenCalled();
      expect(mockApp.commands.executeCommandById).toHaveBeenCalledWith(item.id);
    });
  });

  describe('getItems', () => {
    let oldCommands: Command[];
    let oldPinnedCommandIds: string[] | null;

    beforeAll(() => {
      oldCommands = mockCommands;
      oldPinnedCommandIds = mockCommandPalettePluginInstance.options.pinned;
    });

    afterAll(() => {
      mockCommands = oldCommands;
      mockCommandPalettePluginInstance.options.pinned = oldPinnedCommandIds;
    });

    it('should order commands by name', () => {
      mockCommands = [
        makeCommandItem({ name: 'Command C' }),
        makeCommandItem({ name: 'Command B' }),
        makeCommandItem({ name: 'Command A' }),
        makeCommandItem({ name: 'Command D' }),
        makeCommandItem({ name: 'Command C' }),
      ];

      const results = sut.getItems();
      expect(results).toHaveLength(5);
      expect(results[0].name).toBe('Command A');
      expect(results[1].name).toBe('Command B');
      expect(results[2].name).toBe('Command C');
      expect(results[3].name).toBe('Command C');
      expect(results[4].name).toBe('Command D');
    });

    it('should order pinned commands first', () => {
      mockCommands = [
        makeCommandItem({ name: 'Command B' }),
        makeCommandItem({ name: 'Command A' }),
        makeCommandItem({ name: 'Command Pinned 1', id: 'pinned:command1' }),
        makeCommandItem({ name: 'Command Pinned 2', id: 'pinned:command2' }),
      ];
      mockCommandPalettePluginInstance.options.pinned = [
        'pinned:command1',
        'pinned:command2',
      ];

      const results = sut.getItems();
      expect(results).toHaveLength(4);
      expect(results[0].name).toBe('Command Pinned 1');
      expect(results[1].name).toBe('Command Pinned 2');
      expect(results[2].name).toBe('Command A');
      expect(results[3].name).toBe('Command B');
    });
  });
});