generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ts
295 lines (260 loc) · 7.74 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import {
App,
MarkdownPostProcessorContext,
parseYaml,
Plugin,
PluginSettingTab,
Setting,
} from "obsidian";
import { PhoneNumberFormat, PhoneNumberUtil } from "google-libphonenumber";
interface ContactCardsPluginSettings {
brandfetchClientId?: string;
defaultCountryCode: string;
}
const DEFAULT_SETTINGS: ContactCardsPluginSettings = {
defaultCountryCode: "US",
};
export default class ContactCardsPlugin extends Plugin {
settings: ContactCardsPluginSettings;
async onload() {
console.log(
`Loading plugin: ${this.manifest.name} v${this.manifest.version}`,
);
await this.loadSettings();
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new ContactCardsSettingTab(this.app, this));
// Register a post-processor for code blocks of language `contact-card`
this.registerMarkdownCodeBlockProcessor(
"contact-card",
(source, el, ctx) => this.renderContactCard(source, el, ctx),
);
window.CodeMirror.defineMode("contact-card", (config) =>
window.CodeMirror.getMode(config, "yaml"),
);
}
onunload() {
console.log(
`Unloading plugin: ${this.manifest.name} v${this.manifest.version}`,
);
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
async saveSettings() {
await this.saveData(this.settings);
}
renderError(el: HTMLElement, error: unknown) {
let errorMsg = "Something went wrong";
if (error instanceof Error) {
errorMsg = `${error.name} - ${error.message}`;
} else if (typeof error === "string") {
errorMsg = error;
} else if (
typeof error === "object" &&
error !== null &&
"toString" in error &&
typeof error.toString === "function"
) {
errorMsg = error.toString();
}
return el.createDiv({ cls: "contact-card-error", text: errorMsg });
}
async renderContactCard(
source: string,
el: HTMLElement,
ctx: MarkdownPostProcessorContext,
) {
try {
const contactData = parseYaml(source) ?? {
name: "John Doe",
title: "The Everyman",
company: "Acme Inc.",
email: "[email protected]",
phone: 5551234567,
location: "Nowhere, OK",
};
const container = el.createDiv({ cls: "contact-card-container" });
const content = container.createDiv({
cls: "contact-card-content",
});
const card = content.createDiv({ cls: "contact-card" });
// Contact Card Photo
let photoUrl = contactData.photo_url;
if (!photoUrl) {
// Only use Gravatar if a photo_url was not provided
const email = contactData.email ?? "";
const emailHash = await sha256(email.trim().toLowerCase());
photoUrl = `https://gravatar.com/avatar/${emailHash}.jpg?s=120&d=mp`;
}
const linkedInUrl = `https://www.linkedin.com/search/results/people/?keywords=${contactData.name}`;
const photo = card.createEl("a", {
title: "Search on LinkedIn",
cls: "contact-card-photo",
attr: { href: linkedInUrl },
});
photo.createEl("img", { attr: { src: photoUrl } });
delete contactData.photo_url;
// Company Logo
let logoUrl = contactData.logo_url;
const domain =
contactData.domain ||
contactData.email
?.slice(contactData.email.indexOf("@") + 1)
.toLowerCase();
if (!logoUrl && domain) {
if (this.settings.brandfetchClientId) {
// Primary logo source: Brandfetch
logoUrl = `https://cdn.brandfetch.io/${domain}/w/100/h/100?c=${this.settings.brandfetchClientId}`;
} else {
// Fallback sources if no Brandfetch API key
logoUrl = `https://logo.clearbit.com/${domain}`;
// logoUrl = `https://www.google.com/s2/favicons?domain=${domain}&sz=128`; // Alternative
}
}
if (logoUrl) {
const companyLogo = card.createEl("a", {
title: "View website",
cls: "contact-card-company-logo",
attr: { href: `https://www.${domain}` },
});
companyLogo.createEl("img", {
attr: {
src: logoUrl,
onerror: "this.style.display='none'", // Hide if logo fails to load
},
});
}
delete contactData.logo_url;
delete contactData.domain;
// Contact Details
const info = card.createDiv({ cls: "contact-card-info" });
info.createDiv({
cls: "contact-card-name",
text: contactData.name,
});
delete contactData.name;
info.createDiv({
cls: "contact-card-title",
text: contactData.title,
});
delete contactData.title;
info.createDiv({ cls: "contact-card-separator", text: "\u00A0" });
info.createDiv({
cls: "contact-card-company",
text: contactData.company,
});
delete contactData.company;
// Clickable Email
if (contactData.email) {
const email = info.createDiv({ cls: "contact-card-email" });
email.createEl("a", {
title: "Send email",
text: contactData.email,
attr: { href: `mailto:${contactData.email}` },
});
delete contactData.email;
}
// Formatted & Clickable Phone Number
if (contactData.phone) {
const phoneUtil = PhoneNumberUtil.getInstance();
const phoneNum = phoneUtil.parse(
contactData.phone.toString(),
this.settings.defaultCountryCode,
);
const regionCode = phoneUtil.getRegionCodeForNumber(phoneNum);
const formattedPhone = phoneUtil.format(
phoneNum,
regionCode === null ||
regionCode === this.settings.defaultCountryCode
? PhoneNumberFormat.NATIONAL
: PhoneNumberFormat.INTERNATIONAL,
);
const phone = info.createDiv({ cls: "contact-card-phone" });
phone.createEl("a", {
title: "Call number",
text: formattedPhone,
attr: {
href: `tel:${phoneUtil.getNationalSignificantNumber(phoneNum)}`,
},
});
delete contactData.phone;
}
// Clickable Location
if (contactData.location) {
const location = info.createDiv({
cls: "contact-card-location",
});
location.createEl("a", {
title: "View on map",
text: contactData.location,
attr: {
href: `https://www.google.com/maps/place/${contactData.location}`,
},
});
delete contactData.location;
}
info.createDiv({ cls: "contact-card-separator", text: "\u00A0" });
// Display all other fields
for (const k in contactData) {
const el = container.find(`.contact-card-${k}`);
if (!el) {
info.createDiv({
cls: `contact-card-${k}`,
text: `${k}: ${contactData[k]}`,
});
}
}
} catch (error) {
this.renderError(el, error);
}
}
}
class ContactCardsSettingTab extends PluginSettingTab {
plugin: ContactCardsPlugin;
constructor(app: App, plugin: ContactCardsPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("Brandfetch client ID")
.setDesc(
"Provide your Brandfetch Client ID for retrieving company logos",
)
.addText((text) =>
text
.setPlaceholder("Brandfetch Client ID")
.setValue(this.plugin.settings.brandfetchClientId ?? "")
.onChange(async (value) => {
this.plugin.settings.brandfetchClientId = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Default country code")
.setDesc("Specify your country code for phone number formatting.")
.addText((text) =>
text
.setPlaceholder("US")
.setValue(this.plugin.settings.defaultCountryCode)
.onChange(async (value) => {
this.plugin.settings.defaultCountryCode = value;
await this.plugin.saveSettings();
}),
);
}
}
async function sha256(message: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
// Convert buffer to hex
const hashArray = [...new Uint8Array(hashBuffer)];
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}