-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
269 lines (219 loc) · 6.94 KB
/
main.ts
File metadata and controls
269 lines (219 loc) · 6.94 KB
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
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// Remember to rename these classes and interfaces!
interface ThreadNode {
id: string;
content: string;
metadata: {
parent_id?: string;
alias_ids: string[];
};
}
interface MyPluginSettings {
ycbUrl: string;
ycbApiKey: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
ycbUrl: 'https://yourcommonbase.com/',
ycbApiKey: ''
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
private async addToYCB(data: string, parentId?: string): Promise<any> {
const response = await fetch(`${this.settings.ycbUrl}/add`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.settings.ycbApiKey}`,
},
body: JSON.stringify({
data: data,
metadata: {
title: "Thread Entry"
},
...(parentId && { parent_id: parentId })
}),
});
if (!response.ok) {
throw new Error(`Failed to add to YCB: ${response.statusText}`);
}
return await response.json();
}
private async uploadThreadToYCB(threadNodes: ThreadNode[]): Promise<void> {
const idMapping: { [key: string]: string } = {};
// Sort nodes to process parents before children
const sortedNodes = [...threadNodes].sort((a, b) => {
if (!a.metadata.parent_id && b.metadata.parent_id) return -1;
if (a.metadata.parent_id && !b.metadata.parent_id) return 1;
return 0;
});
for (const node of sortedNodes) {
try {
const parentYcbId = node.metadata.parent_id ? idMapping[node.metadata.parent_id] : undefined;
const result = await this.addToYCB(node.content, parentYcbId);
// Store mapping from our node ID to YCB ID
idMapping[node.id] = result.id;
console.log(`Added node ${node.id} -> ${result.id}`);
} catch (error) {
console.error(`Failed to add node ${node.id}:`, error);
new Notice(`Failed to upload node: ${node.content.substring(0, 50)}...`);
throw error;
}
}
new Notice(`Successfully uploaded ${threadNodes.length} nodes to YCB!`);
}
private parseNestedList(text: string): ThreadNode[] {
const lines = text.split('\n');
const nodes: ThreadNode[] = [];
const parentStack: { id: string; level: number }[] = [];
let nodeCounter = 1;
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine.startsWith('-') && !trimmedLine.startsWith('*')) {
continue;
}
const content = trimmedLine.substring(1).trim();
if (!content) continue;
const indentLevel = (line.match(/^\s*/)?.[0].length || 0) / 4;
const nodeId = `node_${nodeCounter++}`;
// Find parent based on indent level
while (parentStack.length > 0 && parentStack[parentStack.length - 1].level >= indentLevel) {
parentStack.pop();
}
const parentId = parentStack.length > 0 ? parentStack[parentStack.length - 1].id : undefined;
const node: ThreadNode = {
id: nodeId,
content: content,
metadata: {
parent_id: parentId,
alias_ids: []
}
};
// Add this node as a child to its parent
if (parentId) {
const parentNode = nodes.find(n => n.id === parentId);
if (parentNode) {
parentNode.metadata.alias_ids.push(nodeId);
}
}
nodes.push(node);
parentStack.push({ id: nodeId, level: indentLevel });
}
return nodes;
}
async onload() {
await this.loadSettings();
// This adds the save thread command
this.addCommand({
id: 'save-thread',
name: 'Save Thread',
editorCallback: (editor: Editor, view: MarkdownView) => {
const selectedText = editor.getSelection();
const textToProcess = selectedText || editor.getValue();
const threadNodes = this.parseNestedList(textToProcess);
const jsonOutput = JSON.stringify(threadNodes, null, 2);
// Copy to clipboard and show notification
navigator.clipboard.writeText(jsonOutput).then(() => {
new Notice('Thread JSON copied to clipboard!');
}).catch(() => {
// Fallback: show in modal if clipboard fails
new ThreadOutputModal(this.app, jsonOutput).open();
});
}
});
// This adds the upload to YCB command
this.addCommand({
id: 'upload-thread-to-ycb',
name: 'Upload Thread to YCB',
editorCallback: async (editor: Editor, view: MarkdownView) => {
if (!this.settings.ycbApiKey) {
new Notice('Please set YCB API Key in plugin settings first!');
return;
}
const selectedText = editor.getSelection();
const textToProcess = selectedText || editor.getValue();
const threadNodes = this.parseNestedList(textToProcess);
if (threadNodes.length === 0) {
new Notice('No valid bullet points found to upload!');
return;
}
try {
new Notice('Uploading thread to YCB...');
await this.uploadThreadToYCB(threadNodes);
} catch (error) {
console.error('Upload failed:', error);
new Notice('Failed to upload thread to YCB. Check console for details.');
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new YCBSettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class ThreadOutputModal extends Modal {
private jsonOutput: string;
constructor(app: App, jsonOutput: string) {
super(app);
this.jsonOutput = jsonOutput;
}
onOpen() {
const {contentEl} = this;
contentEl.createEl('h2', { text: 'Thread JSON Output' });
const pre = contentEl.createEl('pre');
pre.createEl('code', { text: this.jsonOutput });
pre.style.backgroundColor = '#f5f5f5';
pre.style.padding = '10px';
pre.style.borderRadius = '5px';
pre.style.maxHeight = '400px';
pre.style.overflow = 'auto';
const copyButton = contentEl.createEl('button', { text: 'Copy to Clipboard' });
copyButton.onclick = () => {
navigator.clipboard.writeText(this.jsonOutput).then(() => {
new Notice('JSON copied to clipboard!');
this.close();
});
};
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class YCBSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('YCB URL')
.setDesc('Your Common Base URL')
.addText(text => text
.setPlaceholder('https://yourcommonbase.com/backend')
.setValue(this.plugin.settings.ycbUrl)
.onChange(async (value) => {
this.plugin.settings.ycbUrl = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('YCB API Key')
.setDesc('Your Common Base API Key')
.addText(text => text
.setPlaceholder('Enter your API key')
.setValue(this.plugin.settings.ycbApiKey)
.onChange(async (value) => {
this.plugin.settings.ycbApiKey = value;
await this.plugin.saveSettings();
}));
}
}