Skip to content

Commit

Permalink
Merge pull request #5 from dhurley94/tests
Browse files Browse the repository at this point in the history
Add refresh button to image modal
  • Loading branch information
dhurley94 authored Jan 11, 2024
2 parents 7914199 + eb50a17 commit 6aa1d1e
Show file tree
Hide file tree
Showing 22 changed files with 1,285 additions and 419 deletions.
Empty file added .env.example
Empty file.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,5 @@ data.json

# Exclude macOS Finder (System Explorer) View States
.DS_Store

**.tgz
4 changes: 4 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
data.json
**.ts
scripts/
**.tgz
2 changes: 1 addition & 1 deletion .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
tag-version-prefix=""
tag-version-prefix=""
2 changes: 1 addition & 1 deletion esbuild.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["main.ts"],
entryPoints: ["src/index.ts"],
bundle: true,
external: [
"obsidian",
Expand Down
5 changes: 5 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'],
};
120 changes: 0 additions & 120 deletions main.ts

This file was deleted.

2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "giphy-insert",
"name": "Giphy Insert",
"version": "1.0.1",
"version": "1.0.2",
"minAppVersion": "0.15.0",
"description": "This is a Giphy plugin for Obsidian. This plugin helps users insert Gifs from the Giphy API.",
"author": "drhurley94",
Expand Down
16 changes: 11 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,31 +1,37 @@
{
"name": "obsidian-giphy-plugin",
"version": "1.0.1",
"version": "1.1.0",
"description": "This is a plugin for Obsidian that help you insert Giphy images (https://obsidian.md)",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"dev": "nodemon -e ts --watch src --exec \"npm run build\"",
"debug": "npm run dev",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json",
"version": "node ./scripts/version-bump.mjs && git add manifest.json versions.json",
"lint": "eslint --config .eslintrc --fix --color --ext .ts . --resolve-plugins-relative-to ."
},
"keywords": [],
"author": "",
"license": "MIT",
"devDependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "^6.8.0",
"@typescript-eslint/parser": "^6.8.0",
"builtin-modules": "3.3.0",
"esbuild": "0.17.3",
"eslint": "^8.56.0",
"eslint-config-airbnb-typescript": "^17.1.0",
"eslint-plugin-no-loops": "^0.3.0",
"eslint-plugin-prettier": "^5.0.1",
"obsidian": "latest",
"prettier": "^3.0.0",
"nodemon": "^3.0.2",
"obsidian": "^1.4.11",
"tslib": "2.4.0",
"typescript": "4.7.4"
},
"dependencies": {
"eslint-plugin-import": "^2.28.1"
"eslint-plugin-import": "^2.29.1"
}
}
File renamed without changes.
47 changes: 47 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
export interface ApiClient {
get(url: string, params: Record<string, any>): Promise<any>;
}

export class GiphyApiClient implements ApiClient {
private apiKey: string;

constructor(apiKey: string) {
this.apiKey = apiKey;
}

async get(url: string, params: Record<string, any>): Promise<any> {
const queryString = new URLSearchParams({ ...params, api_key: this.apiKey }).toString();
const response = await fetch(`${url}?${queryString}`);
return response.json();
}
}

export class GiphyService {
private client: ApiClient;

private lastKeywordSearch: string;

private offset: number = 0;

constructor(client: ApiClient) {
this.client = client;
}

getLastKeyword(): string {
return this.lastKeywordSearch;
}

async queryGiphy(keyword: string, limit = 3): Promise<string[] | null> {
const GIPHY_API_ENDPOINT = 'https://api.giphy.com/v1/gifs/search';

if (!keyword) console.warn('No keyword specified');
if (keyword === this.lastKeywordSearch) this.offset += limit;
this.lastKeywordSearch = keyword;

const data = await this.client.get(GIPHY_API_ENDPOINT, { q: keyword, limit, offset: this.offset });

if (data.data.length === 0) return null;

return data.data.map((gif: { images: { original: { url: string } } }) => gif.images.original.url);
}
}
130 changes: 130 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { MarkdownView, Notice, Plugin as ObsidianPlugin } from 'obsidian';
import { GiphyImagePickerModal } from './ui/image-picker';
import { GiphyPluginSettingTab } from './ui/plugin-settings';
import { GiphySearchModal } from './ui/search-modal';
import { GiphyApiClient, GiphyService } from './api';

export interface GiphyPluginSettings {
apiKey: string;
imageCount: number;
imageCss: string;
imageSize: string;
slashCommands: string[];
}

export const DEFAULT_SETTINGS: GiphyPluginSettings = {
apiKey: '',
imageCount: 5,
imageSize: '95px',
imageCss: 'margin: 3px; cursor: pointer; border: 2px solid gray;',
slashCommands: [
'giphy',
'gif',
],
};

export default class GiphyPlugin extends ObsidianPlugin {
settings: GiphyPluginSettings;

private giphyClient: GiphyApiClient;

public giphyService: GiphyService;

private cursor: CodeMirror.Position;

async onload() {
this.settings = { ...DEFAULT_SETTINGS, ...(await this.loadData()) };

this.giphyClient = new GiphyApiClient(this.settings.apiKey);
this.giphyService = new GiphyService(this.giphyClient);

this.registerEvent(this.app.workspace.on('active-leaf-change', this.handleActiveLeafChange.bind(this)));

this.addCommand({
id: 'search-giphy',
name: 'Search Giphy for GIFs',
callback: () => this.searchGiphy(),
});

this.addSettingTab(new GiphyPluginSettingTab(this.app, this));
}

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

async searchGiphy() {
// Save the current cursor position
const editor = this.getEditor();
if (editor) {
this.cursor = editor.getCursor();
}

const keyword = await this.promptForInput();
if (!keyword) return;

const gifUrls = await this.giphyService.queryGiphy(keyword, this.settings.imageCount);
if (!gifUrls) {
new Notice('No GIFs found.').setMessage('No GIFs found.');
return;
}

const selectedGifUrl = await this.promptForGifSelection(gifUrls);
if (!selectedGifUrl) return;

// Restore the cursor position
if (editor && this.cursor) {
editor.setCursor(this.cursor);
}

// Insert the selected image at the current cursor location
editor?.replaceRange(`![Giphy GIF](${selectedGifUrl})`, this.cursor);
}

async promptForGifSelection(gifUrls: string[]): Promise<string | null> {
return new Promise((resolve) => {
const modal = new GiphyImagePickerModal(this.app, this, gifUrls, resolve);
modal.open();
});
}

private handleActiveLeafChange(): void {
const activeLeaf = this.app.workspace.getLeaf();
if (activeLeaf?.view instanceof MarkdownView) {
const editor = activeLeaf.view.editor;
if (editor) {
editor.exec(this.handleEditorChange.bind(this));
}
}
}

private handleEditorChange(cm: any, change: any): void {
const insertedText: string = change?.text?.join('') || '';
if (DEFAULT_SETTINGS.slashCommands.filter((command) => insertedText.includes(`/${command}`))) {
this.searchGiphy();

try {
const from = {
line: change.from.line,
ch: change.from.ch - 6,
};
cm.replaceRange('', from, change.from);
} catch (err) {
console.error("Error while trying to replace '/giphy':", err);
}
}
}

async promptForInput(): Promise<string> {
return new Promise((resolve) => {
const modal = new GiphySearchModal(this.app, this, resolve);
modal.open();
});
}

getEditor(): CodeMirror.Editor | null {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) { return null; }
return view.editor as any;
}
}
1 change: 1 addition & 0 deletions src/ui/history-browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {};
Loading

0 comments on commit 6aa1d1e

Please sign in to comment.