obsidian#Keymap TypeScript Examples
The following examples show how to use
obsidian#Keymap.
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: editorHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
override onChooseSuggestion(
sugg: EditorSuggestion,
evt: MouseEvent | KeyboardEvent,
): void {
if (sugg) {
this.navigateToLeafOrOpenFile(
Keymap.isModEvent(evt),
sugg.file,
'Unable to reopen existing editor in new Leaf.',
null,
sugg.item,
);
}
}
Example #2
Source File: headingsHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
override onChooseSuggestion(
sugg: HeadingSuggestion,
evt: MouseEvent | KeyboardEvent,
): void {
if (sugg) {
const {
start: { line, col },
end: endLoc,
} = sugg.item.position;
// state information to highlight the target heading
const eState = {
active: true,
focus: true,
startLoc: { line, col },
endLoc,
line,
cursor: {
from: { line, ch: col },
to: { line, ch: col },
},
};
this.navigateToLeafOrOpenFile(
Keymap.isModEvent(evt),
sugg.file,
'Unable to navigate to heading for file.',
{ active: true, eState },
);
}
}
Example #3
Source File: relatedItemsHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
override onChooseSuggestion(
sugg: RelatedItemsSuggestion,
evt: MouseEvent | KeyboardEvent,
): void {
if (sugg) {
const { file } = sugg;
this.navigateToLeafOrOpenFile(
Keymap.isModEvent(evt),
file,
`Unable to open related file ${file.path}`,
);
}
}
Example #4
Source File: starredHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
override onChooseSuggestion(
sugg: StarredSuggestion,
evt: MouseEvent | KeyboardEvent,
): void {
if (sugg) {
const { item } = sugg;
if (isFileStarredItem(item)) {
const { file } = sugg;
this.navigateToLeafOrOpenFile(
Keymap.isModEvent(evt),
file,
`Unable to open Starred file ${file.path}`,
);
}
}
}
Example #5
Source File: symbolHandler.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 6 votes |
override onChooseSuggestion(
sugg: SymbolSuggestion,
evt: MouseEvent | KeyboardEvent,
): void {
if (sugg) {
const symbolCmd = this.inputInfo.parsedCommand() as SourcedParsedCommand;
this.navigateToSymbol(sugg, symbolCmd, Keymap.isModEvent(evt));
}
}
Example #6
Source File: PumlView.ts From obsidian-plantuml with MIT License | 6 votes |
// function to switch between source and preview mode
async switchMode(arg: 'source' | 'preview' | MouseEvent) {
let mode = arg;
// if force mode not provided, switch to opposite of current mode
if (!mode || mode instanceof MouseEvent) mode = this.currentView === 'source' ? 'preview' : 'source';
if (arg instanceof MouseEvent) {
if (Keymap.isModEvent(arg)) {
this.app.workspace.duplicateLeaf(this.leaf).then(async () => {
const viewState = this.app.workspace.activeLeaf?.getViewState();
if (viewState) {
viewState.state = {...viewState.state, mode: mode};
await this.app.workspace.activeLeaf?.setViewState(viewState);
}
});
} else {
await this.setState({...this.getState(), mode: mode}, {});
}
}
}
Example #7
Source File: index.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 5 votes |
mockKeymap = mock<typeof Keymap>()
Example #8
Source File: editorHandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 4 votes |
describe('editorHandler', () => {
let settings: SwitcherPlusSettings;
let mockApp: MockProxy<App>;
let mockWorkspace: MockProxy<Workspace>;
let sut: EditorHandler;
beforeAll(() => {
mockWorkspace = mock<Workspace>({
rootSplit: mock<WorkspaceSplit>(),
leftSplit: mock<WorkspaceSplit>(),
rightSplit: mock<WorkspaceSplit>(),
});
mockApp = mock<App>({ workspace: mockWorkspace });
settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'editorListCommand', 'get').mockReturnValue(editorTrigger);
sut = new EditorHandler(mockApp, settings);
});
describe('commandString', () => {
it('should return editorListCommand trigger', () => {
expect(sut.commandString).toBe(editorTrigger);
});
});
describe('validateCommand', () => {
let inputText: string;
let startIndex: number;
const filterText = 'foo';
beforeAll(() => {
inputText = `${editorTrigger}${filterText}`;
startIndex = editorTrigger.length;
});
it('should validate parsed input', () => {
const inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, null);
expect(inputInfo.mode).toBe(Mode.EditorList);
const editorCmd = inputInfo.parsedCommand();
expect(editorCmd.parsedInput).toBe(filterText);
expect(editorCmd.isValidated).toBe(true);
});
});
describe('getSuggestions', () => {
const mockPrepareQuery = jest.mocked(prepareQuery);
const mockFuzzySearch = jest.mocked(fuzzySearch);
const rootFixture = rootSplitEditorFixtures[0];
const leftFixture = leftSplitEditorFixtures[0];
const rightFixture = rightSplitEditorFixtures[0];
let mockRootSplitLeaf: MockProxy<WorkspaceLeaf>;
let mockLeftSplitLeaf: MockProxy<WorkspaceLeaf>;
let mockRightSplitLeaf: MockProxy<WorkspaceLeaf>;
beforeAll(() => {
mockWorkspace.iterateAllLeaves.mockImplementation(
(callback: (leaf: WorkspaceLeaf) => void) => {
const leaves = [mockRootSplitLeaf, mockLeftSplitLeaf, mockRightSplitLeaf];
leaves.forEach((leaf) => callback(leaf));
},
);
});
beforeEach(() => {
mockRootSplitLeaf = makeLeafWithRoot(
rootFixture.displayText,
mockWorkspace.rootSplit,
);
mockLeftSplitLeaf = makeLeafWithRoot(
leftFixture.displayText,
mockWorkspace.leftSplit,
);
mockRightSplitLeaf = makeLeafWithRoot(
rightFixture.displayText,
mockWorkspace.rightSplit,
);
});
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('that EditorSuggestion have a file property to enable interop with other plugins (like HoverEditor)', () => {
const inputInfo = new InputInfo(editorTrigger);
const results = sut.getSuggestions(inputInfo);
expect(results.every((v) => v.file !== null)).toBe(true);
});
test('with default settings, it should return suggestions for editor mode', () => {
const inputInfo = new InputInfo(editorTrigger, Mode.EditorList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(3);
const resultLeaves = new Set(results.map((sugg: EditorSuggestion) => sugg.item));
expect(resultLeaves.has(mockRootSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockLeftSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockRightSplitLeaf)).toBe(true);
expect(results.every((sugg) => sugg.type === 'editor')).toBe(true);
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockWorkspace.iterateAllLeaves).toHaveBeenCalled();
expect(mockRootSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockLeftSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockRightSplitLeaf.getRoot).toHaveBeenCalled();
});
test('with filter search term, it should return only matching suggestions for editor mode', () => {
mockPrepareQuery.mockReturnValueOnce(rootFixture.prepQuery);
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
return text === rootFixture.displayText ? rootFixture.fuzzyMatch : null;
});
const inputInfo = new InputInfo(rootFixture.inputText, Mode.EditorList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(1);
const resultLeaves = new Set(results.map((sugg: EditorSuggestion) => sugg.item));
expect(resultLeaves.has(mockRootSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockLeftSplitLeaf)).toBe(false);
expect(resultLeaves.has(mockRightSplitLeaf)).toBe(false);
expect(results[0]).toHaveProperty('type', 'editor');
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockWorkspace.iterateAllLeaves).toHaveBeenCalled();
expect(mockRootSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockLeftSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockRightSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockRootSplitLeaf.getDisplayText).toHaveBeenCalled();
expect(mockLeftSplitLeaf.getDisplayText).toHaveBeenCalled();
expect(mockRightSplitLeaf.getDisplayText).toHaveBeenCalled();
mockFuzzySearch.mockReset();
});
test('with INCLUDED side view type, it should return included side panel editor suggestions for editor mode', () => {
const includeViewType = 'foo';
const includeViewTypesSpy = jest
.spyOn(settings, 'includeSidePanelViewTypes', 'get')
.mockReturnValue([includeViewType]);
const mockView = mockLeftSplitLeaf.view as MockProxy<View>;
mockView.getViewType.mockReturnValue(includeViewType);
const inputInfo = new InputInfo(editorTrigger, Mode.EditorList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(2);
const resultLeaves = new Set(results.map((sugg: EditorSuggestion) => sugg.item));
expect(resultLeaves.has(mockRootSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockLeftSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockRightSplitLeaf)).toBe(false);
expect(results.every((sugg) => sugg.type === 'editor')).toBe(true);
expect(includeViewTypesSpy).toHaveBeenCalled();
expect(mockView.getViewType).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockWorkspace.iterateAllLeaves).toHaveBeenCalled();
expect(mockRootSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockLeftSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockRightSplitLeaf.getRoot).toHaveBeenCalled();
includeViewTypesSpy.mockRestore();
});
test('with EXCLUDED main view type, it should not return excluded main panel editor suggestions for editor mode', () => {
const excludeViewType = 'foo';
const excludeViewTypesSpy = jest
.spyOn(settings, 'excludeViewTypes', 'get')
.mockReturnValue([excludeViewType]);
const mockView = mockRootSplitLeaf.view as MockProxy<View>;
mockView.getViewType.mockReturnValue(excludeViewType);
const inputInfo = new InputInfo(editorTrigger, Mode.EditorList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(2);
const resultLeaves = new Set(results.map((sugg: EditorSuggestion) => sugg.item));
expect(resultLeaves.has(mockRootSplitLeaf)).toBe(false);
expect(resultLeaves.has(mockLeftSplitLeaf)).toBe(true);
expect(resultLeaves.has(mockRightSplitLeaf)).toBe(true);
expect(results.every((sugg) => sugg.type === 'editor')).toBe(true);
expect(excludeViewTypesSpy).toHaveBeenCalled();
expect(mockView.getViewType).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockWorkspace.iterateAllLeaves).toHaveBeenCalled();
expect(mockRootSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockLeftSplitLeaf.getRoot).toHaveBeenCalled();
expect(mockRightSplitLeaf.getRoot).toHaveBeenCalled();
excludeViewTypesSpy.mockRestore();
});
});
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 displayText = 'foo';
const mockLeaf = makeLeafWithRoot(displayText, null);
const mockRenderResults = jest.mocked(renderResults);
const sugg: EditorSuggestion = {
type: 'editor',
file: null,
item: mockLeaf,
match: makeFuzzyMatch(),
};
sut.renderSuggestion(sugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(
mockParentEl,
displayText,
sugg.match,
);
expect(mockLeaf.getDisplayText).toHaveBeenCalled();
});
});
describe('onChooseSuggestion', () => {
beforeAll(() => {
const fileContainerLeaf = makeLeaf();
fileContainerLeaf.openFile.mockResolvedValueOnce();
mockWorkspace.getLeaf.mockReturnValueOnce(fileContainerLeaf);
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});
it('should activate the selected leaf', () => {
const activateLeafSpy = jest.spyOn(Handler.prototype, 'activateLeaf');
const mockLeaf = makeLeafWithRoot(null, null);
const sugg: EditorSuggestion = {
type: 'editor',
file: new TFile(),
item: mockLeaf,
match: makeFuzzyMatch(),
};
sut.onChooseSuggestion(sugg, null);
expect(activateLeafSpy).toHaveBeenCalledWith(
sugg.item,
true,
defaultOpenViewState.eState,
);
activateLeafSpy.mockRestore();
});
it('should open file in new leaf when Mod is down', () => {
const isModDown = true;
const mockLeaf = makeLeafWithRoot(null, null);
const mockKeymap = jest.mocked<typeof Keymap>(Keymap);
const navigateToLeafOrOpenFileSpy = jest.spyOn(
Handler.prototype,
'navigateToLeafOrOpenFile',
);
mockKeymap.isModEvent.mockReturnValueOnce(isModDown);
const sugg: EditorSuggestion = {
type: 'editor',
file: new TFile(),
item: mockLeaf,
match: null,
};
sut.onChooseSuggestion(sugg, null);
expect(mockKeymap.isModEvent).toHaveBeenCalled();
expect(navigateToLeafOrOpenFileSpy).toHaveBeenCalledWith(
isModDown,
sugg.file,
expect.any(String),
null,
mockLeaf,
);
navigateToLeafOrOpenFileSpy.mockRestore();
});
});
});
Example #9
Source File: headingshandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 4 votes |
describe('headingsHandler', () => {
let settings: SwitcherPlusSettings;
let headingSugg: HeadingSuggestion;
const mockPrepareQuery = jest.mocked<typeof prepareQuery>(prepareQuery);
const mockFuzzySearch = jest.mocked<typeof fuzzySearch>(fuzzySearch);
beforeAll(() => {
settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'headingsListCommand', 'get').mockReturnValue(headingsTrigger);
headingSugg = {
item: makeHeading('foo heading', 1),
file: new TFile(),
match: null,
type: 'heading',
};
});
describe('commandString', () => {
it('should return headingsListCommand trigger', () => {
const sut = new HeadingsHandler(mock<App>(), settings);
expect(sut.commandString).toBe(headingsTrigger);
});
});
describe('validateCommand', () => {
it('should validate parsed input for headings mode', () => {
const filterText = 'foo';
const inputText = `${headingsTrigger}${filterText}`;
const startIndex = headingsTrigger.length;
const inputInfo = new InputInfo(inputText);
const sut = new HeadingsHandler(mock<App>(), settings);
sut.validateCommand(inputInfo, startIndex, filterText, null, null);
expect(inputInfo.mode).toBe(Mode.HeadingsList);
const headingsCmd = inputInfo.parsedCommand();
expect(headingsCmd.parsedInput).toBe(filterText);
expect(headingsCmd.isValidated).toBe(true);
});
});
describe('getSuggestions', () => {
let sut: HeadingsHandler;
let mockWorkspace: MockProxy<Workspace>;
let mockVault: MockProxy<Vault>;
let mockMetadataCache: MockProxy<MetadataCache>;
let mockViewRegistry: MockProxy<ViewRegistry>;
let builtInSystemOptionsSpy: jest.SpyInstance;
beforeAll(() => {
mockWorkspace = mock<Workspace>();
mockVault = mock<Vault>();
mockMetadataCache = mock<MetadataCache>();
mockViewRegistry = mock<ViewRegistry>();
mockViewRegistry.isExtensionRegistered.mockReturnValue(true);
const mockApp = mock<App>({
workspace: mockWorkspace,
vault: mockVault,
metadataCache: mockMetadataCache,
viewRegistry: mockViewRegistry,
});
sut = new HeadingsHandler(mockApp, settings);
builtInSystemOptionsSpy = jest
.spyOn(settings, 'builtInSystemOptions', 'get')
.mockReturnValue({
showAllFileTypes: true,
showAttachments: true,
showExistingOnly: false,
});
});
afterAll(() => {
builtInSystemOptionsSpy.mockRestore();
});
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('without any filter text, it should return most recent opened file suggestions for headings mode', () => {
const fileData: Record<string, TFile> = {};
let file = new TFile();
fileData[file.path] = file;
file = new TFile();
fileData[file.path] = file;
file = new TFile();
fileData[file.path] = file;
const fileDataKeys = Object.keys(fileData);
mockWorkspace.getLastOpenFiles.mockReturnValueOnce(fileDataKeys);
mockVault.getAbstractFileByPath.mockImplementation(
(path: string) => fileData[path],
);
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
return f === file ? {} : getCachedMetadata();
});
const inputInfo = new InputInfo(headingsTrigger);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(fileDataKeys.length);
const expectedFiles = new Set(Object.values(fileData));
const headingSuggestions = results.filter((sugg) =>
isHeadingSuggestion(sugg),
) as HeadingSuggestion[];
expect(headingSuggestions).toHaveLength(2);
expect(headingSuggestions.every((sugg) => expectedFiles.has(sugg.file))).toBe(true);
const fileSuggestions = results.filter((sugg) =>
isFileSuggestion(sugg),
) as FileSuggestion[];
expect(fileSuggestions).toHaveLength(1);
expect(fileSuggestions.every((sugg) => expectedFiles.has(sugg.file))).toBe(true);
expect(mockWorkspace.getLastOpenFiles).toHaveBeenCalled();
expect(mockVault.getAbstractFileByPath).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockWorkspace.getLastOpenFiles.mockReset();
mockVault.getAbstractFileByPath.mockReset();
mockMetadataCache.getFileCache.mockReset();
});
test('with filter search term, it should return matching suggestions for all headings', () => {
const expected = new TFile();
const h1 = makeHeading('foo heading H1', 1, makeLoc(1));
const h2 = makeHeading('foo heading H2', 2, makeLoc(2));
const filterText = 'foo';
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
return f === expected ? { headings: [h1, h2] } : getCachedMetadata();
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(2);
expect(results.every((r) => isHeadingSuggestion(r))).toBe(true);
expect(
results.every((r: HeadingSuggestion) => r.item === h1 || r.item === h2),
).toBe(true);
const result = results[0] as HeadingSuggestion;
expect(result.file).toBe(expected);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
});
test('with filter search term, and searchAllHeadings set to false, it should return only matching suggestions using first H1 in file', () => {
const expected = new TFile();
const expectedHeading = makeHeading('foo heading H1', 1, makeLoc(1));
const heading2 = makeHeading('foo heading H1', 1, makeLoc(2));
const filterText = 'foo';
const searchAllHeadingsSpy = jest
.spyOn(settings, 'searchAllHeadings', 'get')
.mockReturnValue(false);
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
return f === expected
? { headings: [expectedHeading, heading2] }
: getCachedMetadata();
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
let result = results[0];
expect(isHeadingSuggestion(result)).toBe(true);
result = result as HeadingSuggestion;
expect(result.file).toBe(expected);
expect(result.item).toBe(expectedHeading);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
searchAllHeadingsSpy.mockRestore();
});
test("with filter search term, it should return matching suggestions using file name (leaf segment) when H1 doesn't exist", () => {
const filterText = 'foo';
const expected = new TFile();
expected.path = 'path/to/bar/foo filename.md'; // only path matters for this test
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
// don't return any heading metadata for expected
return f === expected ? {} : getCachedMetadata();
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
const result = results[0];
expect(isFileSuggestion(result)).toBe(true);
expect((result as FileSuggestion).file).toBe(expected);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
});
test("with filter search term, it should fallback to match against file path when H1 doesn't exist and there's no match against the filename (leaf segment)", () => {
const filterText = 'foo';
const expected = new TFile();
expected.path = 'foo/path/to/filename.md'; // only path matters for this test
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.getFileCache.mockReturnValue({});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
const result = results[0];
expect(isFileSuggestion(result)).toBe(true);
expect((result as FileSuggestion).file).toBe(expected);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
});
test('with filter search term and shouldShowAlias set to true, it should match against aliases', () => {
const expected = new TFile();
const filterText = 'foo';
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
settings.shouldShowAlias = true;
const fm: CachedMetadata = {
frontmatter: {
aliases: ['bar', 'foo'],
position: null,
},
};
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
return f === expected ? fm : getCachedMetadata();
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
const result = results[0];
expect(isAliasSuggestion(result)).toBe(true);
expect((result as AliasSuggestion).file).toBe(expected);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
settings.shouldShowAlias = false;
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
});
test('with filter search term and showExistingOnly set to false, it should match against unresolved linktext', () => {
const expected = new TFile();
const filterText = 'foo';
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.unresolvedLinks[expected.path] = {
'foo link noexist': 1,
'another link': 1,
};
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
const result = results[0];
expect(isUnresolvedSuggestion(result)).toBe(true);
expect((result as UnresolvedSuggestion).linktext).toBe('foo link noexist');
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
mockMetadataCache.unresolvedLinks = {};
});
test('with filter search term and strictHeadingsOnly enabled, it should not match against file name, or path when there is no H1', () => {
const filterText = 'foo';
const expected = new TFile();
expected.path = 'foo/path/to/filename.md'; // only path matters for this test
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected));
mockMetadataCache.getFileCache.mockReturnValue({});
const strictHeadingsOnlySpy = jest
.spyOn(settings, 'strictHeadingsOnly', 'get')
.mockReturnValue(true);
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(0);
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
expect(strictHeadingsOnlySpy).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockPrepareQuery.mockReset();
strictHeadingsOnlySpy.mockRestore();
});
it('should not return suggestions from excluded folders', () => {
const filterText = 'foo';
const excludedFolderName = 'ignored';
const h1 = makeHeading('foo heading H1', 1, makeLoc(1));
const expected = new TFile();
expected.path = 'foo/path/to/foo filename.md';
mockPrepareQuery.mockReturnValue(makePreparedQuery(filterText));
mockVault.getRoot.mockReturnValueOnce(makeFileTree(expected, excludedFolderName));
mockMetadataCache.getFileCache.mockImplementation((f: TFile) => {
return f === expected ? { headings: [h1] } : {};
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.startsWith(filterText) ? match : null;
});
const excludeFoldersSpy = jest
.spyOn(settings, 'excludeFolders', 'get')
.mockReturnValue([excludedFolderName]);
const inputInfo = new InputInfo(`${headingsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, null);
const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(0);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockVault.getRoot).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalled();
expect(builtInSystemOptionsSpy).toHaveBeenCalled();
expect(mockViewRegistry.isExtensionRegistered).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
mockPrepareQuery.mockReset();
excludeFoldersSpy.mockRestore();
});
});
describe('addSuggestionsFromFile', () => {
let sut: HeadingsHandler;
let mockWorkspace: MockProxy<Workspace>;
// let mockVault: MockProxy<Vault>;
let mockMetadataCache: MockProxy<MetadataCache>;
let mockViewRegistry: MockProxy<ViewRegistry>;
let builtInSystemOptionsSpy: jest.SpyInstance;
beforeAll(() => {
mockWorkspace = mock<Workspace>();
// mockVault = mock<Vault>();
mockMetadataCache = mock<MetadataCache>();
mockViewRegistry = mock<ViewRegistry>();
mockViewRegistry.isExtensionRegistered.mockReturnValue(true);
const mockApp = mock<App>({
workspace: mockWorkspace,
// vault: mockVault,
metadataCache: mockMetadataCache,
viewRegistry: mockViewRegistry,
});
builtInSystemOptionsSpy = jest
.spyOn(settings, 'builtInSystemOptions', 'get')
.mockReturnValue({
showAllFileTypes: true,
showAttachments: true,
showExistingOnly: false,
});
sut = new HeadingsHandler(mockApp, settings);
});
afterAll(() => {
builtInSystemOptionsSpy.mockRestore();
});
test('with filter search term, it should return matching suggestions using file name (leaf segment) when there is no H1 match', () => {
const filterText = 'foo';
const filename = `${filterText} filename`;
const path = `path/${filterText}/bar/${filename}`; // only path matters for this test
const results: Array<FileSuggestion> = [];
const expectedMatch = makeFuzzyMatch();
const expectedFile = new TFile();
expectedFile.path = path;
mockMetadataCache.getFileCache.calledWith(expectedFile).mockReturnValue({
headings: [makeHeading("words that don't match", 1)],
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
return text === filename ? expectedMatch : null;
});
sut.addSuggestionsFromFile(results, expectedFile, makePreparedQuery(filterText));
const result = results[0];
expect(results).toHaveLength(1);
expect(isFileSuggestion(result)).toBe(true);
expect(result.file).toBe(expectedFile);
expect(result.match).toBe(expectedMatch);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(expectedFile);
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
});
test('with filter search term, it should fallback match against file path when there is no H1 match and no match against the filename (leaf segment)', () => {
const filterText = 'foo';
const path = `path/${filterText}/bar/filename`; // only path matters for this test
const results: Array<FileSuggestion> = [];
const expectedMatch = makeFuzzyMatch();
const expectedFile = new TFile();
expectedFile.path = path;
mockMetadataCache.getFileCache.calledWith(expectedFile).mockReturnValue({
headings: [makeHeading("words that don't match", 1)],
});
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
return text === path ? expectedMatch : null;
});
sut.addSuggestionsFromFile(results, expectedFile, makePreparedQuery(filterText));
const result = results[0];
expect(results).toHaveLength(1);
expect(isFileSuggestion(result)).toBe(true);
expect(result.file).toBe(expectedFile);
expect(result.match).toBe(expectedMatch);
expect(mockFuzzySearch).toHaveBeenCalled();
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(expectedFile);
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
});
});
describe('renderSuggestion', () => {
let sut: HeadingsHandler;
let mockParentEl: MockProxy<HTMLElement>;
beforeAll(() => {
sut = new HeadingsHandler(mock<App>(), settings);
mockParentEl = mock<HTMLElement>();
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.renderSuggestion(null, null)).not.toThrow();
});
it('should render a span with the heading level indicator', () => {
sut.renderSuggestion(headingSugg, mockParentEl);
expect(mockParentEl.createSpan).toHaveBeenCalledWith(
expect.objectContaining({
cls: ['suggestion-flair', 'qsp-headings-indicator'],
text: HeadingIndicators[headingSugg.item.level],
prepend: true,
}),
);
});
test('with HeadingCache, it should render a suggestion with match offsets', () => {
const mockRenderResults = jest.mocked<typeof renderResults>(renderResults);
sut.renderSuggestion(headingSugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(
mockParentEl,
headingSugg.item.heading,
headingSugg.match,
);
});
it('should render a div element with the text of the suggestion file path', () => {
sut.renderSuggestion(headingSugg, mockParentEl);
expect(mockParentEl.createDiv).toHaveBeenCalledWith(
expect.objectContaining({
cls: 'suggestion-note',
text: stripMDExtensionFromPath(headingSugg.file),
}),
);
});
});
describe('onChooseSuggestion', () => {
const mockKeymap = jest.mocked<typeof Keymap>(Keymap);
let sut: HeadingsHandler;
let mockWorkspace: MockProxy<Workspace>;
beforeAll(() => {
mockWorkspace = mock<Workspace>();
const mockApp = mock<App>({
workspace: mockWorkspace,
});
const fileContainerLeaf = makeLeaf();
fileContainerLeaf.openFile.mockResolvedValueOnce();
mockWorkspace.getLeaf.mockReturnValueOnce(fileContainerLeaf);
sut = new HeadingsHandler(mockApp, settings);
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});
it('should open the file associated with the suggestion', () => {
const isModDown = false;
const navigateToLeafOrOpenFileSpy = jest.spyOn(
Handler.prototype,
'navigateToLeafOrOpenFile',
);
mockKeymap.isModEvent.mockReturnValueOnce(isModDown);
sut.onChooseSuggestion(headingSugg, null);
expect(mockKeymap.isModEvent).toHaveBeenCalled();
expect(navigateToLeafOrOpenFileSpy).toHaveBeenCalledWith(
isModDown,
headingSugg.file,
expect.any(String),
expect.anything(),
);
navigateToLeafOrOpenFileSpy.mockRestore();
});
});
});
Example #10
Source File: relatedItemsHandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 4 votes |
describe('relatedItemsHandler', () => {
const rootFixture = rootSplitEditorFixtures[0];
let settings: SwitcherPlusSettings;
let mockApp: MockProxy<App>;
let mockWorkspace: MockProxy<Workspace>;
let sut: RelatedItemsHandler;
let mockMetadataCache: MockProxy<MetadataCache>;
let mockRootSplitLeaf: MockProxy<WorkspaceLeaf>;
let filterText: string;
beforeAll(() => {
mockMetadataCache = mock<MetadataCache>();
mockMetadataCache.getFileCache.mockImplementation((_f) => rootFixture.cachedMetadata);
mockWorkspace = mock<Workspace>({ activeLeaf: null });
mockApp = mock<App>({
workspace: mockWorkspace,
metadataCache: mockMetadataCache,
vault: mock<Vault>(),
});
settings = new SwitcherPlusSettings(null);
jest
.spyOn(settings, 'relatedItemsListCommand', 'get')
.mockReturnValue(relatedItemsTrigger);
const rootSplitSourceFile = new TFile();
rootSplitSourceFile.parent = makeFileTree(rootSplitSourceFile);
mockRootSplitLeaf = makeLeaf();
mockRootSplitLeaf.view.file = rootSplitSourceFile;
});
beforeEach(() => {
// reset for each test because symbol mode will use saved data from previous runs
sut = new RelatedItemsHandler(mockApp, settings);
});
describe('commandString', () => {
it('should return relatedItemsListCommand trigger', () => {
expect(sut.commandString).toBe(relatedItemsTrigger);
});
});
describe('validateCommand', () => {
filterText = 'foo';
it('should validate parsed input in prefix (active editor) mode', () => {
const inputInfo = new InputInfo(`${relatedItemsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand();
expect(cmd.parsedInput).toBe(filterText);
expect(cmd.isValidated).toBe(true);
});
it('should validate parsed input for file based suggestion', () => {
const targetFile = new TFile();
const inputInfo = new InputInfo('', Mode.Standard);
const sugg: AliasSuggestion = {
file: targetFile,
alias: 'foo',
type: 'alias',
match: null,
};
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.isValidated).toBe(true);
expect(cmd.source).toEqual(
expect.objectContaining({
file: targetFile,
leaf: null,
suggestion: sugg,
isValidSource: true,
}),
);
});
it('should validate parsed input for editor suggestion', () => {
const targetLeaf = makeLeaf();
const inputInfo = new InputInfo('', Mode.EditorList);
mockWorkspace.activeLeaf = targetLeaf; // <-- set the target as a currently open leaf
const sugg: EditorSuggestion = {
item: targetLeaf,
file: targetLeaf.view.file,
type: 'editor',
match: null,
};
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.isValidated).toBe(true);
expect(cmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.activeLeaf = null;
});
it('should validate parsed input for starred file suggestion', () => {
const targetFile = new TFile();
const inputInfo = new InputInfo('', Mode.StarredList);
const item = makeFileStarredItem(targetFile.basename);
const sugg: StarredSuggestion = {
item,
type: 'starred',
file: targetFile,
match: null,
};
(mockApp.vault as MockProxy<Vault>).getAbstractFileByPath
.calledWith(targetFile.path)
.mockReturnValueOnce(targetFile);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.isValidated).toBe(true);
expect(cmd.source).toEqual(
expect.objectContaining({
file: targetFile,
leaf: null,
suggestion: sugg,
isValidSource: true,
}),
);
});
it('should validate and identify active editor as matching the file suggestion target', () => {
const targetLeaf = makeLeaf();
const inputInfo = new InputInfo('', Mode.Standard);
mockWorkspace.activeLeaf = targetLeaf; // <-- set the target as a currently open leaf
const sugg: AliasSuggestion = {
file: targetLeaf.view.file,
alias: 'foo',
type: 'alias',
match: null,
};
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.isValidated).toBe(true);
expect(cmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.activeLeaf = null;
});
it('should validate and identify in-active editor as matching the file suggestion target file', () => {
const targetLeaf = makeLeaf();
const inputInfo = new InputInfo('', Mode.Standard);
const sugg: AliasSuggestion = {
file: targetLeaf.view.file,
alias: 'foo',
type: 'alias',
match: null,
};
mockWorkspace.activeLeaf = null; // <-- clear out active leaf
mockWorkspace.iterateAllLeaves.mockImplementation((callback) => {
callback(targetLeaf); // <-- report targetLeaf and an in-active open leaf
});
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
const cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.isValidated).toBe(true);
expect(cmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.iterateAllLeaves.mockReset();
});
});
describe('getSuggestions', () => {
const mockPrepareQuery = jest.mocked<typeof prepareQuery>(prepareQuery);
const mockFuzzySearch = jest.mocked<typeof fuzzySearch>(fuzzySearch);
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('that RelatedItemsSuggestion have a file property to enable interop with other plugins (like HoverEditor)', () => {
const inputInfo = new InputInfo(relatedItemsTrigger);
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
const results = sut.getSuggestions(inputInfo);
expect(results.every((v) => v.file !== null)).toBe(true);
});
test('with default settings, it should return suggestions', () => {
const inputInfo = new InputInfo(relatedItemsTrigger);
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
const results = sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(2);
expect(results.every((sugg) => sugg.type === 'relatedItems')).toBe(true);
expect(results.every((sugg) => sugg.relationType === 'diskLocation')).toBe(true);
const files = results.map((v) => v.file);
expect(files).toEqual(expect.arrayContaining([file1, file2]));
expect(mockPrepareQuery).toHaveBeenCalled();
});
test('with filter search term, it should return only matching symbol suggestions', () => {
filterText = file1.basename;
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation(
(_q: PreparedQuery, text: string): SearchResult => {
const match = makeFuzzyMatch();
return text.includes(filterText) ? match : null;
},
);
const inputInfo = new InputInfo(`${relatedItemsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, mockRootSplitLeaf);
const results = sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(1);
expect(results.every((sugg) => sugg.type === 'relatedItems')).toBe(true);
expect(results.every((sugg) => sugg.relationType === 'diskLocation')).toBe(true);
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockFuzzySearch).toHaveBeenCalled();
mockFuzzySearch.mockReset();
});
test('with existing filter search term, it should continue refining suggestions for the previous target', () => {
// 1) setup first initial run
filterText = file1.basename.slice(0, file1.basename.length / 2);
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.includes(filterText) ? match : null;
});
let inputInfo = new InputInfo(`${relatedItemsTrigger}${filterText}`);
sut.validateCommand(inputInfo, 0, filterText, null, mockRootSplitLeaf);
let results = sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
expect(results).toBeInstanceOf(Array);
expect(results.every((sugg) => sugg.type === 'relatedItems')).toBe(true);
expect(results.every((sugg) => sugg.relationType === 'diskLocation')).toBe(true);
let cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.source.file).toBe(mockRootSplitLeaf.view.file);
mockFuzzySearch.mockReset();
// 2) setup second run, which refines the filterText from the first run
filterText = file1.basename;
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation((q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text.endsWith(q.query) ? match : null;
});
const mockTempLeaf = makeLeaf();
inputInfo = new InputInfo(`${relatedItemsTrigger}${filterText}`);
// note the use of a different leaf than the first run, because it should use the
// leaf from the previous run
sut.validateCommand(inputInfo, 0, filterText, null, mockTempLeaf);
results = sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.RelatedItemsList);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(1);
expect(results[0].file).toEqual(file1);
expect(results.every((sugg) => sugg.type === 'relatedItems')).toBe(true);
expect(results.every((sugg) => sugg.relationType === 'diskLocation')).toBe(true);
expect(mockPrepareQuery).toHaveBeenCalled();
cmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(cmd.source.file).not.toBe(mockTempLeaf.view.file);
// expect the source file to be the same as the first run
expect(cmd.source.file).toBe(mockRootSplitLeaf.view.file);
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 sugg = mock<RelatedItemsSuggestion>({ file: file1, match });
sut.renderSuggestion(sugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(
mockParentEl,
stripMDExtensionFromPath(file1),
match,
);
});
});
describe('onChooseSuggestion', () => {
const mockKeymap = jest.mocked<typeof Keymap>(Keymap);
beforeAll(() => {
const fileContainerLeaf = makeLeaf();
fileContainerLeaf.openFile.mockResolvedValueOnce();
mockWorkspace.getLeaf.mockReturnValueOnce(fileContainerLeaf);
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});
test('with Mod down, it should it should create a new workspaceLeaf for the target file', () => {
const isModDown = true;
const navigateToLeafOrOpenFileSpy = jest.spyOn(
Handler.prototype,
'navigateToLeafOrOpenFile',
);
mockKeymap.isModEvent.mockReturnValueOnce(isModDown);
const sugg: RelatedItemsSuggestion = {
type: 'relatedItems',
relationType: 'diskLocation',
file: file1,
match: null,
};
sut.onChooseSuggestion(sugg, null);
expect(mockKeymap.isModEvent).toHaveBeenCalled();
expect(navigateToLeafOrOpenFileSpy).toHaveBeenCalledWith(
isModDown,
sugg.file,
expect.any(String),
);
navigateToLeafOrOpenFileSpy.mockRestore();
});
});
describe('getRelatedFiles', () => {
test('with excludeRelatedFolders unset, it should include files from subfolders', () => {
const sourceFile = new TFile();
sourceFile.parent = makeFileTree(sourceFile);
// don't set any folder filter
jest.spyOn(settings, 'excludeRelatedFolders', 'get').mockReturnValueOnce([]);
const results = sut.getRelatedFiles(sourceFile);
expect(results).toHaveLength(4);
expect(results).toEqual(expect.arrayContaining([file1, file2, file3, file4]));
});
it('should exclude files from subfolders', () => {
const sourceFile = new TFile();
sourceFile.parent = makeFileTree(sourceFile);
const results = sut.getRelatedFiles(sourceFile);
expect(results).toHaveLength(2);
expect(results).toEqual(expect.arrayContaining([file1, file2]));
});
it('should include files that are already open in an editor', () => {
const findOpenEditorSpy = jest.spyOn(sut, 'findOpenEditor');
const sourceFile = new TFile();
sourceFile.parent = makeFileTree(sourceFile);
// set file1 as the active leaf
mockWorkspace.activeLeaf = makeLeaf();
// set file1 as the file for active leaf
mockWorkspace.activeLeaf.view.file = file1;
const results = sut.getRelatedFiles(sourceFile);
expect(results).toHaveLength(2);
expect(results).toEqual(expect.arrayContaining([file1, file2]));
expect(findOpenEditorSpy).not.toHaveBeenCalled();
findOpenEditorSpy.mockRestore();
});
test('with excludeOpenRelatedFiles enabled, it should exclude files that are already open in an editor', () => {
const sourceFile = new TFile();
sourceFile.parent = makeFileTree(sourceFile);
// exclude files already open
jest.spyOn(settings, 'excludeOpenRelatedFiles', 'get').mockReturnValueOnce(true);
mockWorkspace.activeLeaf = makeLeaf();
// set file1 as the file for active leaf
mockWorkspace.activeLeaf.view.file = file1;
const results = sut.getRelatedFiles(sourceFile);
expect(results).toHaveLength(1);
expect(results).toEqual(expect.arrayContaining([file2]));
});
});
});
Example #11
Source File: starredHandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 4 votes |
describe('starredHandler', () => {
let settings: SwitcherPlusSettings;
let mockWorkspace: MockProxy<Workspace>;
let mockVault: MockProxy<Vault>;
let mockApp: MockProxy<App>;
let mockInternalPlugins: MockProxy<InternalPlugins>;
let mockPluginInstance: MockProxy<StarredPluginInstance>;
let sut: StarredHandler;
beforeAll(() => {
const pluginInstall = makeStarredPluginInstall();
mockPluginInstance = pluginInstall.instance as StarredPluginInstance;
mockInternalPlugins = makeInternalPluginList(pluginInstall);
mockWorkspace = mock<Workspace>();
mockVault = mock<Vault>();
mockApp = mock<App>({
workspace: mockWorkspace,
vault: mockVault,
internalPlugins: mockInternalPlugins,
});
settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'starredListCommand', 'get').mockReturnValue(starredTrigger);
sut = new StarredHandler(mockApp, settings);
});
describe('commandString', () => {
it('should return starredListCommand trigger', () => {
expect(sut.commandString).toBe(starredTrigger);
});
});
describe('validateCommand', () => {
const filterText = 'foo';
const inputText = `${starredTrigger}${filterText}`;
const startIndex = starredTrigger.length;
it('should validate parsed input with starred plugin enabled', () => {
const inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, null);
expect(inputInfo.mode).toBe(Mode.StarredList);
const starredCmd = inputInfo.parsedCommand();
expect(starredCmd.parsedInput).toBe(filterText);
expect(starredCmd.isValidated).toBe(true);
expect(mockApp.internalPlugins.getPluginById).toHaveBeenCalledWith(
STARRED_PLUGIN_ID,
);
});
it('should not validate parsed input with starred plugin disabled', () => {
mockInternalPlugins.getPluginById.mockReturnValueOnce({
enabled: false,
instance: null,
});
const inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, null);
expect(inputInfo.mode).toBe(Mode.Standard);
const starredCmd = inputInfo.parsedCommand();
expect(starredCmd.parsedInput).toBe(null);
expect(starredCmd.isValidated).toBe(false);
expect(mockInternalPlugins.getPluginById).toHaveBeenCalledWith(STARRED_PLUGIN_ID);
});
});
describe('getSuggestions', () => {
let expectedStarredPaths: string[];
beforeAll(() => {
expectedStarredPaths = mockPluginInstance.items
.filter((v): v is FileStarredItem => isFileStarredItem(v))
.map((v) => v.path);
mockVault.getAbstractFileByPath.mockImplementation((path) => {
let file: TFile = null;
if (expectedStarredPaths.includes(path)) {
file = new TFile();
file.extension = 'md';
file.path = path;
file.basename = filenameFromPath(stripMDExtensionFromPath(file));
}
return file;
});
});
afterAll(() => {
mockReset(mockVault);
});
test('with falsy input, it should return an empty array', () => {
const results = sut.getSuggestions(null);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(0);
});
test('that StarredSuggestion have a file property to enable interop with other plugins (like HoverEditor)', () => {
const inputInfo = new InputInfo(starredTrigger);
const results = sut.getSuggestions(inputInfo);
const fileSuggs = results.filter((v) => isFileStarredItem(v.item));
expect(fileSuggs.every((v) => v.file !== null)).toBe(true);
});
test('with default settings, it should return suggestions for files that have been starred', () => {
const inputInfo = new InputInfo(starredTrigger);
const results = sut.getSuggestions(inputInfo);
const resultStarredPaths = new Set(
results.map((sugg) => (sugg.item as FileStarredItem).path),
);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(expectedStarredPaths.length);
expect(expectedStarredPaths.every((item) => resultStarredPaths.has(item))).toBe(
true,
);
expect(results.every((sugg) => sugg.type === 'starred')).toBe(true);
expect(mockInternalPlugins.getPluginById).toHaveBeenCalledWith(STARRED_PLUGIN_ID);
expect(results.every((sugg) => sugg.item.type === 'file')).toBe(true);
});
test('with filter search term, it should return only matching suggestions for starred mode', () => {
const filterText = expectedStarredFileTitle;
const expectedItem = mockPluginInstance.items.find((v): v is FileStarredItem => {
return isFileStarredItem(v) && v.title === filterText;
});
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(`${starredTrigger}${filterText}`);
const results = sut.getSuggestions(inputInfo);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(1);
const onlyResult = results[0];
expect(onlyResult).toHaveProperty('type', 'starred');
expect((onlyResult.item as FileStarredItem).path).toBe(expectedItem.path);
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 = mockPluginInstance.items.find((v): v is FileStarredItem =>
isFileStarredItem(v),
);
const sugg = mock<StarredSuggestion>({ item, match });
sut.renderSuggestion(sugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(mockParentEl, item.title, match);
});
});
describe('onChooseSuggestion', () => {
let sugg: MockProxy<StarredSuggestion>;
const evt = mock<MouseEvent>();
const mockKeymap = jest.mocked<typeof Keymap>(Keymap);
beforeAll(() => {
const item = mockPluginInstance.items.find((v): v is FileStarredItem =>
isFileStarredItem(v),
);
const fileContainerLeaf = makeLeaf();
fileContainerLeaf.openFile.mockResolvedValueOnce();
mockWorkspace.getLeaf.mockReturnValue(fileContainerLeaf);
sugg = mock<StarredSuggestion>({ item, file: new TFile() });
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});
it('should open a new leaf for the chosen suggestion', () => {
const isModDown = true;
const navigateToLeafOrOpenFileSpy = jest.spyOn(
Handler.prototype,
'navigateToLeafOrOpenFile',
);
mockKeymap.isModEvent.mockReturnValueOnce(isModDown);
sut.onChooseSuggestion(sugg, evt);
expect(mockKeymap.isModEvent).toHaveBeenCalledWith(evt);
expect(navigateToLeafOrOpenFileSpy).toHaveBeenCalledWith(
isModDown,
sugg.file,
expect.any(String),
);
navigateToLeafOrOpenFileSpy.mockRestore();
});
});
describe('getTFileByPath', () => {
it('should return TFile object for path that exists', () => {
const file = new TFile();
mockVault.getAbstractFileByPath.calledWith(file.path).mockReturnValueOnce(file);
const result = sut.getTFileByPath(file.path);
expect(result).toBe(file);
expect(mockVault.getAbstractFileByPath).toHaveBeenCalledWith(file.path);
});
it('should return return null for a path that does not exist', () => {
const file = new TFile();
mockVault.getAbstractFileByPath.calledWith(file.path).mockReturnValueOnce(null);
const result = sut.getTFileByPath(file.path);
expect(result).toBe(null);
expect(mockVault.getAbstractFileByPath).toHaveBeenCalledWith(file.path);
});
});
describe('getItems', () => {
let oldItems: StarredPluginItem[];
beforeAll(() => {
oldItems = mockPluginInstance.items;
});
afterAll(() => {
mockPluginInstance.items = oldItems;
});
it('should always use the file basename instead of the starred item title property', () => {
const file = new TFile();
const starredItem = makeFileStarredItem('starredItemTitle', file.path);
mockPluginInstance.items = [starredItem];
mockVault.getAbstractFileByPath.calledWith(file.path).mockReturnValueOnce(file);
const results = sut.getItems();
const resultItem = results[0].item;
expect(results).toHaveLength(1);
expect(resultItem.title).toBe(file.basename);
expect(mockVault.getAbstractFileByPath).toBeCalledWith(file.path);
});
it('should not return items for starred items where the source file does not exist', () => {
const file = new TFile();
mockVault.getAbstractFileByPath.calledWith(file.path).mockReturnValueOnce(null);
const starredItem = makeFileStarredItem('starredItemTitle', file.path);
mockPluginInstance.items = [starredItem];
const results = sut.getItems();
expect(results).toHaveLength(0);
expect(mockVault.getAbstractFileByPath).toBeCalledWith(file.path);
});
});
});
Example #12
Source File: symbolHandler.test.ts From obsidian-switcher-plus with GNU General Public License v3.0 | 4 votes |
describe('symbolHandler', () => {
const rootFixture = rootSplitEditorFixtures[0];
const leftFixture = leftSplitEditorFixtures[0];
let settings: SwitcherPlusSettings;
let mockApp: MockProxy<App>;
let mockWorkspace: MockProxy<Workspace>;
let sut: SymbolHandler;
let mockMetadataCache: MockProxy<MetadataCache>;
let mockRootSplitLeaf: MockProxy<WorkspaceLeaf>;
let mockLeftSplitLeaf: MockProxy<WorkspaceLeaf>;
let inputText: string;
let startIndex: number;
let filterText: string;
let symbolSugg: SymbolSuggestion;
beforeAll(() => {
mockMetadataCache = mock<MetadataCache>();
mockMetadataCache.getFileCache.mockImplementation((_f) => rootFixture.cachedMetadata);
mockWorkspace = mock<Workspace>({ activeLeaf: null });
mockApp = mock<App>({
workspace: mockWorkspace,
metadataCache: mockMetadataCache,
vault: mock<Vault>(),
});
settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'symbolListCommand', 'get').mockReturnValue(symbolTrigger);
mockRootSplitLeaf = makeLeaf();
mockLeftSplitLeaf = makeLeaf();
symbolSugg = {
type: 'symbol',
file: new TFile(),
item: {
type: 'symbolInfo',
symbol: getHeadings()[0],
symbolType: SymbolType.Heading,
},
match: null,
};
});
beforeEach(() => {
// reset for each test because symbol mode will use saved data from previous runs
sut = new SymbolHandler(mockApp, settings);
});
describe('commandString', () => {
it('should return symbolListCommand trigger', () => {
expect(sut.commandString).toBe(symbolTrigger);
});
});
describe('validateCommand', () => {
filterText = 'foo';
beforeAll(() => {
inputText = `${symbolTrigger}${filterText}`;
startIndex = 0;
});
it('should validate parsed input in symbol prefix (active editor) mode', () => {
const inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand();
expect(symbolCmd.parsedInput).toBe(filterText);
expect(symbolCmd.isValidated).toBe(true);
});
it('should validate parsed input for file based suggestion', () => {
const targetFile = new TFile();
const sugg: AliasSuggestion = {
file: targetFile,
alias: 'foo',
type: 'alias',
match: null,
};
const inputInfo = new InputInfo('', Mode.Standard);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(true);
expect(symbolCmd.source).toEqual(
expect.objectContaining({
file: targetFile,
leaf: null,
suggestion: sugg,
isValidSource: true,
}),
);
});
it('should validate parsed input for editor suggestion', () => {
const targetLeaf = makeLeaf();
mockWorkspace.activeLeaf = targetLeaf; // <-- set the target as a currently open leaf
const sugg: EditorSuggestion = {
item: targetLeaf,
file: targetLeaf.view.file,
type: 'editor',
match: null,
};
const inputInfo = new InputInfo('', Mode.EditorList);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(true);
expect(symbolCmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.activeLeaf = null;
});
it('should validate parsed input for starred file suggestion', () => {
const targetFile = new TFile();
const item = makeFileStarredItem(targetFile.basename);
const sugg: StarredSuggestion = {
item,
type: 'starred',
file: targetFile,
match: null,
};
(mockApp.vault as MockProxy<Vault>).getAbstractFileByPath
.calledWith(targetFile.path)
.mockReturnValueOnce(targetFile);
const inputInfo = new InputInfo('', Mode.StarredList);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(true);
expect(symbolCmd.source).toEqual(
expect.objectContaining({
file: targetFile,
leaf: null,
suggestion: sugg,
isValidSource: true,
}),
);
});
it('should not validate parsed input for starred search suggestion', () => {
const item = makeSearchStarredItem();
const sugg: StarredSuggestion = {
item,
file: null,
type: 'starred',
match: null,
};
const inputInfo = new InputInfo('', Mode.StarredList);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.StarredList);
const symbolCmd = inputInfo.parsedCommand(Mode.SymbolList) as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(false);
expect(symbolCmd.source).toBeNull();
});
it('should validate and identify active editor as matching the file suggestion target', () => {
const targetLeaf = makeLeaf();
mockWorkspace.activeLeaf = targetLeaf; // <-- set the target as a currently open leaf
const sugg: AliasSuggestion = {
file: targetLeaf.view.file,
alias: 'foo',
type: 'alias',
match: null,
};
const inputInfo = new InputInfo('', Mode.Standard);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(true);
expect(symbolCmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.activeLeaf = null;
});
it('should validate and identify in-active editor as matching the file suggestion target file', () => {
const targetLeaf = makeLeaf();
const sugg: AliasSuggestion = {
file: targetLeaf.view.file,
alias: 'foo',
type: 'alias',
match: null,
};
mockWorkspace.activeLeaf = null; // <-- clear out active leaf
mockWorkspace.iterateAllLeaves.mockImplementation((callback) => {
callback(targetLeaf); // <-- report targetLeaf and an in-active open leaf
});
const inputInfo = new InputInfo('', Mode.Standard);
sut.validateCommand(inputInfo, 0, '', sugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const symbolCmd = inputInfo.parsedCommand() as SourcedParsedCommand;
expect(symbolCmd.isValidated).toBe(true);
expect(symbolCmd.source).toEqual(
expect.objectContaining({
file: targetLeaf.view.file,
leaf: targetLeaf,
suggestion: sugg,
isValidSource: true,
}),
);
mockWorkspace.iterateAllLeaves.mockReset();
});
});
describe('getSuggestions', () => {
const mockPrepareQuery = jest.mocked<typeof prepareQuery>(prepareQuery);
const mockFuzzySearch = jest.mocked<typeof fuzzySearch>(fuzzySearch);
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('that SymbolSuggestion have a file property to enable interop with other plugins (like HoverEditor)', () => {
const inputInfo = new InputInfo(symbolTrigger);
const results = sut.getSuggestions(inputInfo);
expect(results.every((v) => v.file !== null)).toBe(true);
});
test('with default settings, it should return symbol suggestions', () => {
const inputInfo = new InputInfo(symbolTrigger);
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results.every((sugg) => sugg.type === 'symbol')).toBe(true);
const set = new Set(results.map((sugg) => sugg.item.symbol));
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const cached: AnySymbolInfoPayload[] = Object.values(
rootFixture.cachedMetadata,
).flat();
expect(results).toHaveLength(cached.length);
expect(cached.every((item) => set.has(item))).toBe(true);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockRootSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
});
test('with selectNearestHeading set to true, it should set the isSelected property of the nearest preceding heading suggestion to true when the file is open in the active editor for any file based suggestion modes', () => {
const selectNearestHeadingSpy = jest
.spyOn(settings, 'selectNearestHeading', 'get')
.mockReturnValue(true);
// there should be a heading in the fixture that starts on this line number
const expectedHeadingStartLineNumber = 9;
const expectedSelectedHeading = rootFixture.cachedMetadata.headings.find(
(val) => val.position.start.line === expectedHeadingStartLineNumber,
);
expect(expectedSelectedHeading).not.toBeNull();
const mockEditor = (mockRootSplitLeaf.view as MarkdownView)
.editor as MockProxy<Editor>;
mockEditor.getCursor.mockReturnValue({
line: expectedHeadingStartLineNumber + 1,
ch: 0,
});
mockWorkspace.activeLeaf = mockRootSplitLeaf;
const activeSugg: HeadingSuggestion = {
item: makeHeading('foo heading', 1),
file: mockWorkspace.activeLeaf.view.file, // <-- here, use the same TFile as ActiveLeaf
match: null,
type: 'heading',
};
// use headings prefix mode along with heading suggestion, note that the suggestion
// has to point to the same TFile as 'activeLeaf'
const inputInfo = new InputInfo('', Mode.HeadingsList);
sut.validateCommand(
inputInfo,
headingsTrigger.length,
'',
activeSugg,
mockWorkspace.activeLeaf,
);
const results = sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.SymbolList);
expect(results).toBeInstanceOf(Array);
expect(results.every((sugg) => sugg.type === 'symbol')).toBe(true);
const selectedSuggestions = results.filter((v) => v.item.isSelected === true);
expect(selectedSuggestions).toHaveLength(1);
expect(selectedSuggestions[0].item.symbol).toBe(expectedSelectedHeading);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockWorkspace.activeLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
selectNearestHeadingSpy.mockReset();
mockEditor.getCursor.mockReset();
mockWorkspace.activeLeaf = null;
});
test('with selectNearestHeading set to true, it should set the isSelected property of the nearest preceding heading suggestion to true', () => {
const selectNearestHeadingSpy = jest
.spyOn(settings, 'selectNearestHeading', 'get')
.mockReturnValue(true);
// there should be a heading in the fixture that starts on this line number
const expectedHeadingStartLineNumber = 9;
const expectedSelectedHeading = rootFixture.cachedMetadata.headings.find(
(val) => val.position.start.line === expectedHeadingStartLineNumber,
);
expect(expectedSelectedHeading).not.toBeNull();
const mockEditor = (mockRootSplitLeaf.view as MarkdownView)
.editor as MockProxy<Editor>;
mockEditor.getCursor.mockReturnValueOnce({
line: expectedHeadingStartLineNumber + 1,
ch: 0,
});
const inputInfo = new InputInfo(symbolTrigger);
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results.every((sugg) => sugg.type === 'symbol')).toBe(true);
const selectedSuggestions = results.filter((v) => v.item.isSelected === true);
expect(selectedSuggestions).toHaveLength(1);
expect(selectedSuggestions[0].item.symbol).toBe(expectedSelectedHeading);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockRootSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
selectNearestHeadingSpy.mockReset();
});
test('with filter search term, it should return only matching symbol suggestions', () => {
mockMetadataCache.getFileCache.mockReturnValueOnce(leftFixture.cachedMetadata);
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation(
(_q: PreparedQuery, text: string): SearchResult => {
const match = makeFuzzyMatch();
return text === 'tag1' || text === 'tag2' ? match : null;
},
);
filterText = 'tag';
inputText = `${symbolTrigger}${filterText}`;
startIndex = 0;
const inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, mockLeftSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(2);
expect(results.every((sugg) => sugg.type === 'symbol')).toBe(true);
const { tags } = leftFixture.cachedMetadata;
const resTags = new Set(results.map((sugg) => sugg.item.symbol));
expect(tags.every((tag) => resTags.has(tag))).toBe(true);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockLeftSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
expect(mockFuzzySearch).toHaveBeenCalled();
mockFuzzySearch.mockReset();
});
test('with existing filter search term, it should continue refining suggestions for the previous target', () => {
mockMetadataCache.getFileCache.mockReturnValue(leftFixture.cachedMetadata);
// 1) setup first initial run
filterText = 'tag';
inputText = `${symbolTrigger}${filterText}`;
startIndex = 0;
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation((_q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch();
return text === 'tag1' || text === 'tag2' ? match : null;
});
let inputInfo = new InputInfo(inputText);
sut.validateCommand(inputInfo, startIndex, filterText, null, mockLeftSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
let results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(2);
expect(results.every((sugg) => sugg.type === 'symbol')).toBe(true);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockLeftSplitLeaf.view.file,
);
mockFuzzySearch.mockReset();
// 2) setup second run, which refines the filterText from the first run
filterText = 'tag2';
mockPrepareQuery.mockReturnValueOnce(makePreparedQuery(filterText));
mockFuzzySearch.mockImplementation((q: PreparedQuery, text: string) => {
const match = makeFuzzyMatch([[0, 4]], -0.0104);
return text === q.query ? match : null;
});
const mockTempLeaf = makeLeaf();
const mockTempLeafFile = mockTempLeaf.view.file;
inputText = `${symbolTrigger}${filterText}`;
inputInfo = new InputInfo(inputText);
// note the use of a different leaf than the first run
sut.validateCommand(inputInfo, startIndex, filterText, null, mockTempLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
results = sut.getSuggestions(inputInfo);
expect(results).not.toBeNull();
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(1); // expect just 1 this time
expect(results[0]).toHaveProperty('type', 'symbol');
const tag = leftFixture.cachedMetadata.tags.find((item) => item.tag === '#tag2');
expect(results[0]).toHaveProperty('item.symbol', tag);
// getFileCache should be called with leftSplitLeaf.view.file both times
expect(mockMetadataCache.getFileCache).not.toHaveBeenCalledWith(mockTempLeafFile);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockLeftSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
mockMetadataCache.getFileCache.mockReset();
mockFuzzySearch.mockReset();
});
it('should not return suggestions for a symbol type that is disabled', () => {
const inputInfo = new InputInfo(symbolTrigger);
const isSymbolTypeEnabledSpy = jest
.spyOn(settings, 'isSymbolTypeEnabled')
.mockImplementation((type) => (type === SymbolType.Tag ? false : true));
mockMetadataCache.getFileCache.mockReturnValueOnce({ tags: getTags() });
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(0);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockRootSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
isSymbolTypeEnabledSpy.mockRestore();
});
it('should not return suggestions for links if the Link symbol type is disabled', () => {
const inputInfo = new InputInfo(symbolTrigger);
const isSymbolTypeEnabledSpy = jest
.spyOn(settings, 'isSymbolTypeEnabled')
.mockImplementation((type) => (type === SymbolType.Link ? false : true));
mockMetadataCache.getFileCache.mockReturnValueOnce({ links: getLinks() });
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).toBeInstanceOf(Array);
expect(results).toHaveLength(0);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockRootSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
isSymbolTypeEnabledSpy.mockRestore();
});
it('should not return suggestions for a sub-link type that is disabled', () => {
const inputInfo = new InputInfo(symbolTrigger);
const excludeLinkSubTypesSpy = jest
.spyOn(settings, 'excludeLinkSubTypes', 'get')
.mockReturnValue(LinkType.Block | LinkType.Heading);
mockMetadataCache.getFileCache.mockReturnValueOnce({ links: getLinks() });
sut.validateCommand(inputInfo, 0, '', null, mockRootSplitLeaf);
expect(inputInfo.mode).toBe(Mode.SymbolList);
const results = sut.getSuggestions(inputInfo);
expect(results).toBeInstanceOf(Array);
// getLinks fixture returns 2 links, 1 block, 1 normal
expect(results).toHaveLength(1);
expect(mockMetadataCache.getFileCache).toHaveBeenCalledWith(
mockRootSplitLeaf.view.file,
);
expect(mockPrepareQuery).toHaveBeenCalled();
excludeLinkSubTypesSpy.mockRestore();
});
});
describe('renderSuggestion', () => {
const mockRenderResults = jest.mocked<typeof renderResults>(renderResults);
let mockTextSpan: MockProxy<HTMLSpanElement>;
let mockParentEl: MockProxy<HTMLElement>;
beforeAll(() => {
mockTextSpan = mock<HTMLSpanElement>();
mockParentEl = mock<HTMLElement>();
mockParentEl.createSpan.mockImplementation(() => mockTextSpan);
});
it('should not throw an error with a null suggestion', () => {
expect(() => sut.renderSuggestion(null, null)).not.toThrow();
});
it('should render Heading suggestion', () => {
sut.renderSuggestion(symbolSugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(
mockTextSpan,
(symbolSugg.item.symbol as HeadingCache).heading,
symbolSugg.match,
);
expect(mockParentEl.createSpan).toHaveBeenCalledWith(
expect.objectContaining({ cls: 'qsp-symbol-text' }),
);
});
it('should render Tag suggestion', () => {
const tagSugg: SymbolSuggestion = {
type: 'symbol',
file: null,
item: {
type: 'symbolInfo',
symbol: getTags()[0],
symbolType: SymbolType.Tag,
},
match: null,
};
sut.renderSuggestion(tagSugg, mockParentEl);
expect(mockRenderResults).toHaveBeenCalledWith(
mockTextSpan,
(tagSugg.item.symbol as TagCache).tag.slice(1),
tagSugg.match,
);
expect(mockParentEl.createSpan).toHaveBeenCalledWith(
expect.objectContaining({ cls: 'qsp-symbol-text' }),
);
});
it('should render Link suggestion', () => {
const linkSugg: SymbolSuggestion = {
type: 'symbol',
file: null,
item: {
type: 'symbolInfo',
symbol: getLinks()[1],
symbolType: SymbolType.Link,
},
match: null,
};
sut.renderSuggestion(linkSugg, mockParentEl);
const { link, displayText } = linkSugg.item.symbol as ReferenceCache;
expect(mockRenderResults).toHaveBeenCalledWith(
mockTextSpan,
`${link}|${displayText}`,
linkSugg.match,
);
expect(mockParentEl.createSpan).toHaveBeenCalledWith(
expect.objectContaining({ cls: 'qsp-symbol-text' }),
);
});
it('should add a symbol indicator', () => {
sut.renderSuggestion(symbolSugg, mockParentEl);
expect(mockParentEl.createDiv).toHaveBeenCalledWith(
expect.objectContaining({
text: HeadingIndicators[(symbolSugg.item.symbol as HeadingCache).level],
cls: 'qsp-symbol-indicator',
}),
);
});
test('with symbolsInLineOrder enabled and no search term, it should indent symbols', () => {
const settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'symbolsInLineOrder', 'get').mockReturnValue(true);
const inputInfo = new InputInfo(symbolTrigger);
sut.validateCommand(inputInfo, 0, 'foo', null, mockRootSplitLeaf);
sut = new SymbolHandler(mockApp, settings);
sut.getSuggestions(inputInfo);
sut.renderSuggestion(symbolSugg, mockParentEl);
expect(mockParentEl.addClass).toHaveBeenCalledWith(
`qsp-symbol-l${symbolSugg.item.indentLevel}`,
);
});
});
describe('onChooseSuggestion', () => {
const mockKeymap = jest.mocked<typeof Keymap>(Keymap);
beforeAll(() => {
const fileContainerLeaf = makeLeaf();
fileContainerLeaf.openFile.mockResolvedValueOnce();
mockWorkspace.getLeaf.mockReturnValue(fileContainerLeaf);
});
const getExpectedEphemeralState = (sugg: SymbolSuggestion): OpenViewState => {
const {
start: { line, col },
end: endLoc,
} = sugg.item.symbol.position;
const state: Record<string, unknown> = {
active: true,
eState: {
active: true,
focus: true,
startLoc: { line, col },
endLoc,
line,
cursor: {
from: { line, ch: col },
to: { line, ch: col },
},
},
};
return state;
};
it('should not throw an error with a null suggestion', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});
it('should activate the existing workspaceLeaf that contains the target symbol and scroll that view via eState', () => {
const isModDown = false;
const expectedState = getExpectedEphemeralState(symbolSugg);
const mockLeaf = makeLeaf(symbolSugg.file);
mockKeymap.isModEvent.mockReturnValueOnce(isModDown);
const navigateToLeafOrOpenFileSpy = jest.spyOn(
Handler.prototype,
'navigateToLeafOrOpenFile',
);
const inputInfo = new InputInfo(symbolTrigger);
sut.validateCommand(inputInfo, 0, '', null, mockLeaf);
sut.getSuggestions(inputInfo);
expect(inputInfo.mode).toBe(Mode.SymbolList);
sut.onChooseSuggestion(symbolSugg, null);
expect(inputInfo.mode).toBe(Mode.SymbolList);
expect(mockKeymap.isModEvent).toHaveBeenCalled();
expect(navigateToLeafOrOpenFileSpy).toHaveBeenCalledWith(
isModDown,
symbolSugg.file,
expect.any(String),
expectedState,
mockLeaf,
Mode.SymbolList,
);
navigateToLeafOrOpenFileSpy.mockRestore();
});
});
});