obsidian#MenuItem TypeScript Examples

The following examples show how to use obsidian#MenuItem. 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: utils.ts    From obsidian-map-view with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Populate a context menu from the user configurable URLs
 * @param menu The menu to attach
 * @param location The geolocation to use in the menu item
 * @param settings Plugin settings
 */
export function populateOpenInItems(
    menu: Menu,
    location: leaflet.LatLng,
    settings: settings.PluginSettings
) {
    for (let setting of settings.openIn) {
        if (!setting.name || !setting.urlPattern) continue;
        const fullUrl = setting.urlPattern
            .replace('{x}', location.lat.toString())
            .replace('{y}', location.lng.toString());
        menu.addItem((item: MenuItem) => {
            item.setTitle(`Open in ${setting.name}`);
            item.onClick((_ev) => {
                open(fullUrl);
            });
        });
    }
}
Example #2
Source File: EventHandler.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
update_file_menu(): void {
        this.plugin.registerEvent(
            this.app.workspace.on("file-menu", (menu: Menu, file: TFile) => {
                if (file instanceof TFolder) {
                    menu.addItem((item: MenuItem) => {
                        item.setTitle("Create new note from template")
                            .setIcon("templater-icon")
                            .onClick(() => {
                                this.plugin.fuzzy_suggester.create_new_note_from_template(
                                    file
                                );
                            });
                    });
                }
            })
        );
    }
Example #3
Source File: mapView.ts    From obsidian-map-view with GNU General Public License v3.0 5 votes vote down vote up
onMoreOptionsMenu(menu: Menu) {
        menu.addItem((item: MenuItem) => {
            item.setTitle('Copy Map View URL').onClick(() => {
                this.copyStateUrl();
            });
        });
        super.onMoreOptionsMenu(menu);
    }
Example #4
Source File: main.ts    From obsidian-map-view with GNU General Public License v3.0 4 votes vote down vote up
async onload() {
        addIcon('globe', consts.RIBBON_ICON);

        await this.loadSettings();

        // Add a new ribbon entry to the left bar
        this.addRibbonIcon('globe', 'Open map view', () => {
            // When clicked change the active view to the map
            this.app.workspace
                .getLeaf()
                .setViewState({ type: consts.MAP_VIEW_NAME });
        });

        this.registerView(consts.MAP_VIEW_NAME, (leaf: WorkspaceLeaf) => {
            return new MapView(leaf, this.settings, this);
        });

        this.registerObsidianProtocolHandler(
            'mapview',
            (params: ObsidianProtocolData) => {
                if (params.action == 'mapview') {
                    const state = stateFromParsedUrl(params);
                    // If a saved URL is opened in another device on which there aren't the same sources, use
                    // the default source instead
                    if (
                        state.chosenMapSource >= this.settings.mapSources.length
                    )
                        state.chosenMapSource =
                            DEFAULT_SETTINGS.defaultState.chosenMapSource;
                    this.openMapWithState(state, false, false);
                }
            }
        );

        this.suggestor = new LocationSuggest(this.app, this.settings);
        this.tagSuggestor = new TagSuggest(this.app, this.settings);
        this.urlConvertor = new UrlConvertor(this.app, this.settings);

        this.registerEditorSuggest(this.suggestor);
        this.registerEditorSuggest(this.tagSuggestor);

        // Convert old settings formats that are no longer supported
        if (convertLegacyMarkerIcons(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: legacy marker icons were converted to the new format'
            );
        }
        if (convertLegacyTilesUrl(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: legacy tiles URL was converted to the new format'
            );
        }
        if (convertLegacyDefaultState(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: legacy default state was converted to the new format'
            );
        }
        if (removeLegacyPresets1(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: legacy URL parsing rules and/or map sources were converted. See the release notes'
            );
        }
        if (convertTagsToQueries(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: legacy tag queries were converted to the new query format'
            );
        }
        if (convertUrlParsingRules1(this.settings)) {
            await this.saveSettings();
            new Notice(
                'Map View: URL parsing rules were converted to the new format'
            );
        }

        // Register commands to the command palette
        // Command that opens the map view (same as clicking the map icon)
        this.addCommand({
            id: 'open-map-view',
            name: 'Open Map View',
            callback: () => {
                this.app.workspace
                    .getLeaf()
                    .setViewState({ type: consts.MAP_VIEW_NAME });
            },
        });

        // Command that looks up the selected text to find the location
        this.addCommand({
            id: 'convert-selection-to-location',
            name: 'Convert Selection to Geolocation',
            editorCheckCallback: (checking, editor, view) => {
                if (checking) return editor.getSelection().length > 0;
                this.suggestor.selectionToLink(editor);
            },
        });

        // Command that adds a blank inline location at the cursor location
        this.addCommand({
            id: 'insert-geolink',
            name: 'Add inline geolocation link',
            editorCallback: (editor, view) => {
                const positionBeforeInsert = editor.getCursor();
                editor.replaceSelection('[](geo:)');
                editor.setCursor({
                    line: positionBeforeInsert.line,
                    ch: positionBeforeInsert.ch + 1,
                });
            },
        });

        // Command that opens the location search dialog and creates a new note from this location
        this.addCommand({
            id: 'new-geolocation-note',
            name: 'New geolocation note',
            callback: () => {
                const dialog = new LocationSearchDialog(
                    this.app,
                    this.settings,
                    'newNote',
                    'New geolocation note'
                );
                dialog.open();
            },
        });

        // Command that opens the location search dialog and adds the location to the current note
        this.addCommand({
            id: 'add-frontmatter-geolocation',
            name: 'Add geolocation (front matter) to current note',
            editorCallback: (editor, view) => {
                const dialog = new LocationSearchDialog(
                    this.app,
                    this.settings,
                    'addToNote',
                    'Add geolocation to note',
                    editor
                );
                dialog.open();
            },
        });

        this.addCommand({
            id: 'open-map-search',
            name: 'Search active map view',
            checkCallback: (checking) => {
                const currentView = this.app.workspace.activeLeaf.view;
                if (
                    currentView &&
                    currentView.getViewType() == consts.MAP_VIEW_NAME
                ) {
                    if (!checking) (currentView as MapView).openSearch();
                    return true;
                } else return false;
            },
        });

        this.addSettingTab(new SettingsTab(this.app, this));

        // Add items to the file context menu (run when the context menu is built)
        // This is the context menu in the File Explorer and clicking "More options" (three dots) from within a file.
        this.app.workspace.on(
            'file-menu',
            async (
                menu: Menu,
                file: TAbstractFile,
                _source: string,
                leaf?: WorkspaceLeaf
            ) => {
                if (file instanceof TFile) {
                    let hasAnyLocation = false;
                    const location = getFrontMatterLocation(file, this.app);
                    if (location) {
                        // If there is a geolocation in the front matter of the file
                        // Add an option to open it in the map
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Show on map');
                            item.setIcon('globe');
                            item.onClick(
                                async (evt: MouseEvent) =>
                                    await this.openMapWithLocation(
                                        location,
                                        evt.ctrlKey
                                    )
                            );
                        });
                        // Add an option to open it in the default app
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Open with default app');
                            item.onClick((_ev) => {
                                open(`geo:${location.lat},${location.lng}`);
                            });
                        });
                        // Populate menu items from user defined "Open In" strings
                        utils.populateOpenInItems(
                            menu,
                            location,
                            this.settings
                        );
                        hasAnyLocation = true;
                    } else {
                        if (leaf && leaf.view instanceof MarkdownView) {
                            // If there is no valid geolocation in the front matter, add a menu item to populate it.
                            const editor = leaf.view.editor;
                            menu.addItem((item: MenuItem) => {
                                item.setTitle('Add geolocation (front matter)');
                                item.setIcon('globe');
                                item.onClick(async (evt: MouseEvent) => {
                                    const dialog = new LocationSearchDialog(
                                        this.app,
                                        this.settings,
                                        'addToNote',
                                        'Add geolocation to note',
                                        editor
                                    );
                                    dialog.open();
                                });
                            });
                        }
                    }
                    const contentMarkers = await getMarkersFromFileContent(
                        file,
                        this.settings,
                        this.app
                    );
                    if (contentMarkers.length > 0) {
                        hasAnyLocation = true;
                    }
                    if (hasAnyLocation) {
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Focus note in Map View');
                            item.setIcon('globe');
                            item.onClick(
                                async (evt: MouseEvent) =>
                                    await this.openMapWithState(
                                        {
                                            query: `path:"${file.path}"`,
                                        } as MapState,
                                        evt.ctrlKey,
                                        true
                                    )
                            );
                        });
                    }
                }
            }
        );

        // Add items to the editor context menu (run when the context menu is built)
        // This is the context menu when right clicking within an editor view.
        this.app.workspace.on(
            'editor-menu',
            async (menu: Menu, editor: Editor, view: MarkdownView) => {
                if (view instanceof FileView) {
                    const location = this.getLocationOnEditorLine(editor, view);
                    if (location) {
                        // If there is a geolocation on the line
                        // Add an option to open it in the map
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Show on map');
                            item.setIcon('globe');
                            item.onClick(
                                async (evt: MouseEvent) =>
                                    await this.openMapWithLocation(
                                        location,
                                        evt.ctrlKey
                                    )
                            );
                        });
                        // Add an option to open it in the default app
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Open with default app');
                            item.onClick((_ev) => {
                                open(`geo:${location.lat},${location.lng}`);
                            });
                        });
                        // Populate menu items from user defined "Open In" strings
                        utils.populateOpenInItems(
                            menu,
                            location,
                            this.settings
                        );
                    }
                    if (editor.getSelection()) {
                        // If there is text selected, add a menu item to convert it to coordinates using geosearch
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Convert to geolocation (geosearch)');
                            item.onClick(
                                async () =>
                                    await this.suggestor.selectionToLink(editor)
                            );
                        });
                    }

                    if (this.urlConvertor.hasMatchInLine(editor))
                        // If the line contains a recognized geolocation that can be converted from a URL parsing rule
                        menu.addItem(async (item: MenuItem) => {
                            item.setTitle('Convert to geolocation');
                            item.onClick(async () => {
                                this.urlConvertor.convertUrlAtCursorToGeolocation(
                                    editor
                                );
                            });
                        });

                    const clipboard = await navigator.clipboard.readText();
                    let clipboardLocation =
                        this.urlConvertor.parseLocationFromUrl(clipboard);
                    if (clipboardLocation) {
                        // If the clipboard contains a recognized geolocation that can be converted from a URL parsing rule
                        menu.addItem((item: MenuItem) => {
                            item.setTitle('Paste as geolocation');
                            item.onClick(async () => {
                                if (clipboardLocation instanceof Promise)
                                    clipboardLocation = await clipboardLocation;
                                if (clipboardLocation)
                                    this.urlConvertor.insertLocationToEditor(
                                        clipboardLocation.location,
                                        editor
                                    );
                            });
                        });
                    }
                }
            }
        );
    }
Example #5
Source File: mapView.ts    From obsidian-map-view with GNU General Public License v3.0 4 votes vote down vote up
async createMap() {
        // LeafletJS compatability: disable tree-shaking for the full-screen module
        var dummy = leafletFullscreen;
        this.display.map = new leaflet.Map(this.display.mapDiv, {
            center: this.defaultState.mapCenter,
            zoom: this.defaultState.mapZoom,
            zoomControl: false,
            worldCopyJump: true,
            maxBoundsViscosity: 1.0,
        });
        leaflet.control
            .zoom({
                position: 'topright',
            })
            .addTo(this.display.map);
        this.updateTileLayerByState(this.state);
        this.display.clusterGroup = new leaflet.MarkerClusterGroup({
            maxClusterRadius:
                this.settings.maxClusterRadiusPixels ??
                DEFAULT_SETTINGS.maxClusterRadiusPixels,
            animate: false,
        });
        this.display.map.addLayer(this.display.clusterGroup);

        this.display.map.on('zoomend', async (event: leaflet.LeafletEvent) => {
            this.ongoingChanges -= 1;
			await this.changeViewAndSaveHistory({
				mapZoom: this.display.map.getZoom(),
				mapCenter: this.display.map.getCenter()
			});
            this.display?.controls?.invalidateActivePreset();
        });
        this.display.map.on('moveend', async (event: leaflet.LeafletEvent) => {
            this.ongoingChanges -= 1;
			await this.changeViewAndSaveHistory({
				mapZoom: this.display.map.getZoom(),
				mapCenter: this.display.map.getCenter()
			});
            this.display?.controls?.invalidateActivePreset();
        });
        this.display.map.on('movestart', (event: leaflet.LeafletEvent) => {
            this.ongoingChanges += 1;
        });
        this.display.map.on('zoomstart', (event: leaflet.LeafletEvent) => {
            this.ongoingChanges += 1;
        });
        this.display.map.on(
            'doubleClickZoom',
            (event: leaflet.LeafletEvent) => {
                this.ongoingChanges += 1;
            }
        );

        this.display.searchControls = new SearchControl(
            { position: 'topright' },
            this,
            this.app,
            this.settings
        );
        this.display.map.addControl(this.display.searchControls);

        if (this.settings.showClusterPreview) {
            this.display.clusterGroup.on('clustermouseover', (cluster) => {
                let content = this.contentEl.createDiv();
                content.classList.add('clusterPreviewContainer');
                for (const m of cluster.propagatedFrom.getAllChildMarkers()) {
                    const marker = m as leaflet.Marker;
                    const iconElement = marker.options.icon.createIcon();
                    iconElement.classList.add('clusterPreviewIcon');
                    content.appendChild(iconElement);
                    if (
                        content.children.length >=
                        consts.MAX_CLUSTER_PREVIEW_ICONS
                    )
                        break;
                }
                cluster.propagatedFrom
                    .bindPopup(content, {
                        closeButton: true,
                        autoPan: false,
                        className: 'marker-popup',
                    })
                    .openPopup();
                cluster.propagatedFrom.activePopup = content;
            });
            this.display.clusterGroup.on('clustermouseout', (cluster) => {
                cluster.propagatedFrom.closePopup();
            });
        }

        // Build the map marker right-click context menu
        this.display.map.on(
            'contextmenu',
            async (event: leaflet.LeafletMouseEvent) => {
                let mapPopup = new Menu(this.app);
                mapPopup.setNoIcon();
                mapPopup.addItem((item: MenuItem) => {
                    const location = `${event.latlng.lat},${event.latlng.lng}`;
                    item.setTitle('New note here (inline)');
                    item.onClick(async (ev) => {
                        const newFileName = utils.formatWithTemplates(
                            this.settings.newNoteNameFormat
                        );
                        const file: TFile = await utils.newNote(
                            this.app,
                            'multiLocation',
                            this.settings.newNotePath,
                            newFileName,
                            location,
                            this.settings.newNoteTemplate
                        );
                        this.goToFile(
                            file,
                            ev.ctrlKey,
                            utils.handleNewNoteCursorMarker
                        );
                    });
                });
                mapPopup.addItem((item: MenuItem) => {
                    const location = `${event.latlng.lat},${event.latlng.lng}`;
                    item.setTitle('New note here (front matter)');
                    item.onClick(async (ev) => {
                        const newFileName = utils.formatWithTemplates(
                            this.settings.newNoteNameFormat
                        );
                        const file: TFile = await utils.newNote(
                            this.app,
                            'singleLocation',
                            this.settings.newNotePath,
                            newFileName,
                            location,
                            this.settings.newNoteTemplate
                        );
                        this.goToFile(
                            file,
                            ev.ctrlKey,
                            utils.handleNewNoteCursorMarker
                        );
                    });
                });
                mapPopup.addItem((item: MenuItem) => {
                    const location = `${event.latlng.lat},${event.latlng.lng}`;
                    item.setTitle(`Copy geolocation`);
                    item.onClick((_ev) => {
                        navigator.clipboard.writeText(`[](geo:${location})`);
                    });
                });
                mapPopup.addItem((item: MenuItem) => {
                    const location = `${event.latlng.lat},${event.latlng.lng}`;
                    item.setTitle(`Copy geolocation as front matter`);
                    item.onClick((_ev) => {
                        navigator.clipboard.writeText(
                            `---\nlocation: [${location}]\n---\n\n`
                        );
                    });
                });
                mapPopup.addItem((item: MenuItem) => {
                    item.setTitle('Open in default app');
                    item.onClick((_ev) => {
                        open(`geo:${event.latlng.lat},${event.latlng.lng}`);
                    });
                });
                utils.populateOpenInItems(
                    mapPopup,
                    event.latlng,
                    this.settings
                );
                mapPopup.showAtPosition(event.originalEvent);
            }
        );
    }
Example #6
Source File: mapView.ts    From obsidian-map-view with GNU General Public License v3.0 4 votes vote down vote up
private newLeafletMarker(marker: FileMarker): leaflet.Marker {
        let newMarker = leaflet.marker(marker.location, {
            icon: marker.icon || new leaflet.Icon.Default(),
        });
        newMarker.on('click', (event: leaflet.LeafletMouseEvent) => {
            this.goToMarker(marker, event.originalEvent.ctrlKey, true);
        });
        newMarker.on('mouseover', (event: leaflet.LeafletMouseEvent) => {
            if (this.settings.showNotePreview) {
                const previewDetails = {
                    scroll: marker.fileLine,
                    line: marker.fileLine,
                    startLoc: {
                        line: marker.fileLine,
                        col: 0,
                        offset: marker.fileLocation,
                    } as Loc,
                    endLoc: {
                        line: marker.fileLine,
                        col: 0,
                        offset: marker.fileLocation,
                    } as Loc,
                };
                this.app.workspace.trigger(
                    'link-hover',
                    newMarker.getElement(),
                    newMarker.getElement(),
                    marker.file.path,
                    '',
                    previewDetails
                );
            }
            if (this.settings.showNoteNamePopup) {
                const fileName = marker.file.name;
                const fileNameWithoutExtension = fileName.endsWith('.md')
                    ? fileName.substr(0, fileName.lastIndexOf('.md'))
                    : fileName;
                let content = `<p class="map-view-marker-name">${fileNameWithoutExtension}</p>`;
                newMarker
                    .bindPopup(content, {
                        closeButton: true,
                        autoPan: false,
                        className: 'marker-popup',
                    })
                    .openPopup();
            }
        });
        newMarker.on('mouseout', (event: leaflet.LeafletMouseEvent) => {
            newMarker.closePopup();
        });
        newMarker.on('add', (event: leaflet.LeafletEvent) => {
            newMarker
                .getElement()
                .addEventListener('contextmenu', (ev: MouseEvent) => {
                    let mapPopup = new Menu(this.app);
                    mapPopup.setNoIcon();
                    mapPopup.addItem((item: MenuItem) => {
                        item.setTitle('Open note');
                        item.onClick(async (ev) => {
                            this.goToMarker(marker, ev.ctrlKey, true);
                        });
                    });
                    mapPopup.addItem((item: MenuItem) => {
                        item.setTitle('Open geolocation in default app');
                        item.onClick((ev) => {
                            open(
                                `geo:${marker.location.lat},${marker.location.lng}`
                            );
                        });
                    });
                    utils.populateOpenInItems(
                        mapPopup,
                        marker.location,
                        this.settings
                    );
                    mapPopup.showAtPosition(ev);
                    ev.stopPropagation();
                });
        });
        return newMarker;
    }