-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.ts
502 lines (430 loc) · 14.1 KB
/
translate.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import * as yaml from "jsr:@std/yaml/parse";
type ConversionRule = {
name: string;
convert: (content: string) => string;
};
type TaskDateType =
| "deadline"
| "scheduled"
| "created"
| "start"
| "done"
| "cancelled";
type TaskDate = {
type: TaskDateType;
date: string;
emoji: string;
};
const TaskStatusMapping: Record<string, string> = {
" ": "TODO",
"/": "DOING",
"x": "DONE",
"-": "CANCELLED",
};
const TaskDateTypeMapping: Record<string, TaskDateType> = {
"📅": "deadline",
"⏳": "scheduled",
"🛫": "start",
"➕": "created",
"✅": "done",
"❌": "cancelled",
};
type TaskPriority = "A" | "B" | "C";
const TaskPriorityMapping: Record<string, TaskPriority> = {
"🔺": "A",
"⏫": "A",
"🔼": "B",
"🔽": "C",
"⏬": "C",
};
// Types at the top of the file
export type TasksConfig = {
globalFilterTag?: string;
priorityMapping: Record<string, TaskPriority>;
convertDates: boolean;
dateProperties: Partial<Record<TaskDateType, string>>;
};
// Default configuration
const defaultTasksConfig: TasksConfig = {
globalFilterTag: "#task",
priorityMapping: TaskPriorityMapping,
convertDates: true,
dateProperties: {
created: ".created",
done: ".completed",
cancelled: ".cancelled",
},
};
export type TranslationConfig = {
tasks?: Partial<TasksConfig>;
};
const defaultTranslationConfig: TranslationConfig = {
tasks: defaultTasksConfig,
};
// Helper to format dates with day names
// TODO: use a fixed format?
function formatTaskDate(date: string): string {
const dayName = new Date(date).toLocaleDateString("en-US", {
weekday: "short",
});
return `${date} ${dayName}`;
}
// Edge case helper function
function isEscaped(str: string, pos: number): boolean {
let count = 0;
pos--;
while (pos >= 0 && str[pos] === "\\") {
count++;
pos--;
}
return count % 2 === 1;
}
// TODO: remove this rule because Logseq supports markdown syntax
const convertHighlights: ConversionRule = {
name: "highlights",
convert: (content: string) => {
// Handle empty highlights first
content = content.replace(/====/g, "^^^^");
content = content.replace(/===/g, "^^^");
// Convert actual highlights, checking for escapes and unterminated highlights
return content.replace(/==([^=]*==)?/g, (match, text) => {
if (!text) {
return match; // Unterminated highlight, preserve as is
}
const pos = content.indexOf(match);
if (isEscaped(content, pos)) {
return match; // Preserve escaped highlights
}
return match.replace(/==/g, "^^"); // Convert to ^^
});
},
};
const convertWikiLinks: ConversionRule = {
name: "wikilinks",
convert: (content: string) => {
// Convert normal wiki links with aliases, checking for escapes and unterminated wiki-links
return content.replace(
/\[\[([^\]|]+)?(\|([^\]]+))?\]\]/g,
(match, page, _, alias, offset) => {
if (!page || !alias) {
return match; // Unterminated wiki-link, preserve as is
}
if (isEscaped(content, offset)) {
return match; // Preserve escaped wiki links
}
// handle asset links
if (page.match(/\.(png|jpg|jpeg|gif|pdf|docx|xlsx|pptx)$/)) {
return `[${alias}](assets/${page})`;
}
if (page === alias) {
return `[[${page}]]`; // Simplify links like [[name|name]] to [[name]]
}
return `[${alias}]([[${page}]])`;
},
);
},
};
// Modified task conversion rule
const convertTasks = (
config?: Partial<TasksConfig>,
): ConversionRule => ({
name: "tasks",
convert: (content: string) => {
const conf = { ...defaultTasksConfig, ...config };
const taskRegex = /^(\s*)- \[([ x\/\-])\](.*?)$/gm;
return content.replace(
taskRegex,
(_, indent, status, text) => {
// Parse the task text to extract dates and priority
const dates: TaskDate[] = [];
let taskText = text;
// Extract and remove dates if enabled
if (conf.convertDates) {
const dateRegex = /(📅|⏳|🛫|➕|✅|❌)\s*(\d{4}-\d{2}-\d{2})/g;
let dateMatch;
while ((dateMatch = dateRegex.exec(text)) !== null) {
const [_, emoji, date] = dateMatch;
const type = TaskDateTypeMapping[emoji] as TaskDateType;
dates.push({ type, date, emoji });
}
taskText = taskText.replace(dateRegex, "");
}
// Extract and remove priority if present
let priority = "";
for (
const [emoji, logseqPriority] of Object.entries(
conf.priorityMapping,
)
) {
if (taskText.includes(emoji)) {
priority = ` [#${logseqPriority}]`;
taskText = taskText.replace(new RegExp(`\\s?${emoji}`), "");
}
}
// Remove global filter tag if configured
if (conf.globalFilterTag) {
taskText = taskText.replace(
new RegExp(` ${conf.globalFilterTag}\\b`),
"",
);
}
// Remove dependency markers (🆔 abcdef, ⛔ abcdef)
taskText = taskText.replace(/ (🆔|⛔) \w+/, "");
// Convert task status
const taskStatus = TaskStatusMapping[status as string];
// Build the converted task
const lines: string[] = [];
// Main task line with status and priority
lines.push(`${indent}- ${taskStatus}${priority}${taskText.trimEnd()}`);
// Add dates with proper indentation
for (const { type, date } of dates) {
const formattedDate = formatTaskDate(date);
const property = conf.dateProperties[type];
switch (type) {
case "deadline":
lines.push(`${indent} DEADLINE: <${formattedDate}>`);
break;
case "scheduled":
lines.push(`${indent} SCHEDULED: <${formattedDate}>`);
break;
default:
if (property) {
lines.push(`${indent} ${property}:: [[${date}]]`);
}
}
}
return lines.join("\n");
},
);
},
});
// Logseq block types: https://docs.logseq.com/#/page/advanced%20commands
type LogseqBlockType =
| "NOTE"
| "TIP"
| "IMPORTANT"
| "CAUTION"
| "WARNING"
| "EXAMPLE"
| "QUOTE";
// Mapping of Logseq block types to supported Obsidian callouts
// https://help.obsidian.md/Editing+and+formatting/Callouts#Supported+types
// TODO: expose this as configuration
const blockTypeMapping: Record<LogseqBlockType, string[]> = {
NOTE: ["note", "info", "summary", "tldr", "abstract"],
TIP: ["tip", "hint", "help", "question", "faq"],
IMPORTANT: ["important", "attention"],
CAUTION: ["caution", "todo"],
WARNING: ["warning", "error", "danger", "bug", "fail", "failure", "missing"],
EXAMPLE: ["example"],
QUOTE: ["quote", "cite"],
};
const blockTypeLookup: Record<string, LogseqBlockType> = Object.fromEntries(
Object.entries(blockTypeMapping).flatMap(([type, aliases]) =>
aliases.map((alias) => [alias.toLowerCase(), type as LogseqBlockType])
),
);
const convertBlocks: ConversionRule = {
name: "blocks",
convert: (content: string) => {
const lines = content.split("\n");
const converted: string[] = [];
const blockLines: string[] = [];
let blockType: LogseqBlockType | null = null;
let blockIndent: string = "";
function commitBlock() {
if (blockType) {
// pass the block content recursively to handle nested blocks
const recurse = convertBlocks.convert(blockLines.join("\n"));
converted.push(recurse);
converted.push(`${blockIndent}#+END_${blockType.toUpperCase()}`);
// reset the block state
blockType = null;
blockLines.length = 0;
blockIndent = "";
}
}
for (const line of lines) {
const blockMatch = line.match(
/^(\s*)>\s?(\[!(?<callout>\w+)\][+-]?\s?)?(?<text>.*)$/,
);
if (blockMatch) {
const groups = blockMatch.groups;
const indent = blockMatch[1] || "";
if (!blockType) { // start a new block
const calloutType = groups?.callout?.toLowerCase() || "";
blockType = blockTypeLookup[calloutType] || "QUOTE";
blockIndent = indent;
converted.push(`${indent}#+BEGIN_${blockType.toUpperCase()}`);
// callouts can have a title
if (groups?.text && blockType !== "QUOTE") {
blockLines.push(`${indent}**${groups.text.trimEnd()}**`);
}
}
if (
!groups?.callout && groups?.text !== undefined
) {
blockLines.push(`${indent}${groups.text.trimEnd()}`);
}
continue;
}
if (blockType && !blockMatch) { // blank line ends the block
commitBlock();
// converted.push(line);
// continue;
}
// Regular line
converted.push(line);
}
// Handle any remaining open blocks
commitBlock();
return converted.join("\n");
},
};
type Frontmatter = Record<string, string | string[]>;
export function parseFrontmatter(
content: string,
): { frontmatter: Frontmatter; body: string } {
const frontmatterRegex = /^---\n([\s\S]*?)\n---\n/;
const match = content.match(frontmatterRegex);
if (!match) return { frontmatter: {}, body: content };
const yamlContent = match[1];
const parsedYaml = yaml.parse(yamlContent, {
schema: "failsafe",
}) as Frontmatter;
const body = content.replace(frontmatterRegex, "");
return { frontmatter: parsedYaml, body };
}
export function renameAndFilterProperties(
frontmatter: Frontmatter,
): Frontmatter {
const renamed: Frontmatter = {};
for (const [key, value] of Object.entries(frontmatter)) {
// Skip the title property because it can cause name conflicts
if (key.toLowerCase() === "title") continue;
// A few special cases for Logseq properties
const keyStr = key === "tag"
? "tags"
: key === "aliases"
? "alias"
: key.replaceAll(/\s+/g, "-");
// Linkify the "created" property
renamed[keyStr] = keyStr === "created" ? `[[${value}]]` : value;
}
return renamed;
}
export function formatProperties(properties: Frontmatter): string[] {
return Object.entries(properties).flatMap(([key, value]) => {
const valueStr = Array.isArray(value) ? value.join(", ") : value;
return valueStr ? [`${key}:: ${valueStr}`] : [];
});
}
export function extractProperties(
content: string,
): { properties: string[]; body: string } {
const { frontmatter, body } = parseFrontmatter(content);
const renamedProperties = renameAndFilterProperties(frontmatter);
const properties = formatProperties(renamedProperties);
return { properties, body };
}
const convertFrontmatter: ConversionRule = {
name: "frontmatter",
convert: (content: string) => {
const { properties, body } = extractProperties(content);
if (!properties.length) return body;
const propertiesBlock = properties.join("\n");
return [propertiesBlock, body].join("\n");
},
};
const PATTERNS = {
// Matches Vimeo video URLs, capturing the video ID
vimeo:
/(?:https?:\/\/)?(?:(?:www|player)\.)?vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|video\/|)(\d+)(?:$|\/|\?|#|\&)/,
// Matches YouTube URLs (regular videos, shorts, and embeds), capturing the video ID
youtube:
/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/).*$/,
// Matches Twitter/X status URLs, capturing the tweet ID
twitter:
/(?:https?:\/\/)?(?:www\.)?(?:twitter\.com|x\.com)\/(?:\w+)\/status\/(\d+)(?:\/?\w*\/?)*(?:\?.*)?$/,
};
const convertEmbeds: ConversionRule = {
name: "embeds",
convert: (content: string) => {
// Handle common asset formats
// TODO: better asset handling (requires a file index to see what is migrated as an asset)
content = content.replace(
/!\[\[(.*?)\.(png|jpg|jpeg|gif|pdf|docx|xlsx|pptx)(\|(.*?))?\]\]/g,
(_match, filename, extension, _aliasPart, alias) => {
const fullName = `${filename}.${extension}`;
const displayAlias = alias || fullName;
return `![${displayAlias}](assets/${fullName})`;
},
);
// Convert Obsidian embeds to Logseq format
content = content.replace(/!\[\[(.*?)\]\]/g, (_match, embed) => {
return `{{embed [[${embed}]]}}`;
});
// Convert embeds from YouTube, Vimeo, and Twitter
content = content.replace(
/!\[(.*?)\]\((https:\/\/[^\s)]+)\)/g,
(_match, _altText, url) => {
if (PATTERNS.youtube.test(url) || PATTERNS.vimeo.test(url)) {
return `{{video ${url}}}`;
} else if (PATTERNS.twitter.test(url)) {
return `{{tweet ${url}}}`;
}
return _match; // Preserve other URLs as is
},
);
return content;
},
};
const convertNumberedLists: ConversionRule = {
name: "numberedLists",
convert: (content: string) => {
const lines = content.split("\n");
const convertedLines: string[] = [];
lines.forEach((line) => {
const match = line.match(/^(\s*)\d+\.\s+(.*)/);
if (match) {
const indent = match[1];
const text = match[2];
convertedLines.push(`${indent}- ${text}`);
convertedLines.push(`${indent} logseq.order-list-type:: number`);
} else {
convertedLines.push(line);
}
});
return convertedLines.join("\n");
},
};
export function translate(
content: string,
config?: Partial<TranslationConfig>,
): string {
// deep merge the configuration with defaults
const conf = { ...defaultTranslationConfig, ...config };
const rules: ConversionRule[] = [
convertFrontmatter,
convertBlocks,
convertTasks(conf.tasks),
convertHighlights,
convertWikiLinks,
convertNumberedLists,
convertEmbeds,
];
return rules.reduce((text, rule) => rule.convert(text), content);
}
if (import.meta.main) { // CLI
const inputFile = Deno.args[0];
const outputFile = Deno.args[1];
if (!inputFile || !outputFile) {
console.log(
"Usage: deno run --allow-read --allow-write translate.ts <input-file> <output-file>",
);
Deno.exit(1);
}
const content = await Deno.readTextFile(inputFile);
const converted = translate(content);
await Deno.writeTextFile(outputFile, converted);
}