fl0werpowers
2025-05-28 951d1dec24eb8e0bea4ec548cc79c5ce718bf02f
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
import { QuartzTransformerPlugin } from "../types"
import { PluggableList } from "unified"
import { visit } from "unist-util-visit"
import { ReplaceFunction, findAndReplace as mdastFindReplace } from "mdast-util-find-and-replace"
import { Root, Html, Paragraph, Text, Link, Parent } from "mdast"
import { BuildVisitor } from "unist-util-visit"
 
export interface Options {
  orComponent: boolean
  TODOComponent: boolean
  DONEComponent: boolean
  videoComponent: boolean
  audioComponent: boolean
  pdfComponent: boolean
  blockquoteComponent: boolean
  tableComponent: boolean
  attributeComponent: boolean
}
 
const defaultOptions: Options = {
  orComponent: true,
  TODOComponent: true,
  DONEComponent: true,
  videoComponent: true,
  audioComponent: true,
  pdfComponent: true,
  blockquoteComponent: true,
  tableComponent: true,
  attributeComponent: true,
}
 
const orRegex = new RegExp(/{{or:(.*?)}}/, "g")
const TODORegex = new RegExp(/{{.*?\bTODO\b.*?}}/, "g")
const DONERegex = new RegExp(/{{.*?\bDONE\b.*?}}/, "g")
 
const blockquoteRegex = new RegExp(/(\[\[>\]\])\s*(.*)/, "g")
const roamHighlightRegex = new RegExp(/\^\^(.+)\^\^/, "g")
const roamItalicRegex = new RegExp(/__(.+)__/, "g")
 
function isSpecialEmbed(node: Paragraph): boolean {
  if (node.children.length !== 2) return false
 
  const [textNode, linkNode] = node.children
  return (
    textNode.type === "text" &&
    textNode.value.startsWith("{{[[") &&
    linkNode.type === "link" &&
    linkNode.children[0].type === "text" &&
    linkNode.children[0].value.endsWith("}}")
  )
}
 
function transformSpecialEmbed(node: Paragraph, opts: Options): Html | null {
  const [textNode, linkNode] = node.children as [Text, Link]
  const embedType = textNode.value.match(/\{\{\[\[(.*?)\]\]:/)?.[1]?.toLowerCase()
  const url = linkNode.url.slice(0, -2) // Remove the trailing '}}'
 
  switch (embedType) {
    case "audio":
      return opts.audioComponent
        ? {
            type: "html",
            value: `<audio controls>
          <source src="${url}" type="audio/mpeg">
          <source src="${url}" type="audio/ogg">
          Your browser does not support the audio tag.
        </audio>`,
          }
        : null
    case "video":
      if (!opts.videoComponent) return null
      // Check if it's a YouTube video
      const youtubeMatch = url.match(
        /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/,
      )
      if (youtubeMatch) {
        const videoId = youtubeMatch[1].split("&")[0] // Remove additional parameters
        const playlistMatch = url.match(/[?&]list=([^#\&\?]*)/)
        const playlistId = playlistMatch ? playlistMatch[1] : null
 
        return {
          type: "html",
          value: `<iframe 
            class="external-embed youtube"
            width="600px"
            height="350px"
            src="https://www.youtube.com/embed/${videoId}${playlistId ? `?list=${playlistId}` : ""}"
            frameborder="0"
            allow="fullscreen"
          ></iframe>`,
        }
      } else {
        return {
          type: "html",
          value: `<video controls>
            <source src="${url}" type="video/mp4">
            <source src="${url}" type="video/webm">
            Your browser does not support the video tag.
          </video>`,
        }
      }
    case "pdf":
      return opts.pdfComponent
        ? {
            type: "html",
            value: `<embed src="${url}" type="application/pdf" width="100%" height="600px" />`,
          }
        : null
    default:
      return null
  }
}
 
export const RoamFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options> | undefined> = (
  userOpts,
) => {
  const opts = { ...defaultOptions, ...userOpts }
 
  return {
    name: "RoamFlavoredMarkdown",
    markdownPlugins() {
      const plugins: PluggableList = []
 
      plugins.push(() => {
        return (tree: Root) => {
          const replacements: [RegExp, ReplaceFunction][] = []
 
          // Handle special embeds (audio, video, PDF)
          if (opts.audioComponent || opts.videoComponent || opts.pdfComponent) {
            visit(tree, "paragraph", ((node: Paragraph, index: number, parent: Parent | null) => {
              if (isSpecialEmbed(node)) {
                const transformedNode = transformSpecialEmbed(node, opts)
                if (transformedNode && parent) {
                  parent.children[index] = transformedNode
                }
              }
            }) as BuildVisitor<Root, "paragraph">)
          }
 
          // Roam italic syntax
          replacements.push([
            roamItalicRegex,
            (_value: string, match: string) => ({
              type: "emphasis",
              children: [{ type: "text", value: match }],
            }),
          ])
 
          // Roam highlight syntax
          replacements.push([
            roamHighlightRegex,
            (_value: string, inner: string) => ({
              type: "html",
              value: `<span class="text-highlight">${inner}</span>`,
            }),
          ])
 
          if (opts.orComponent) {
            replacements.push([
              orRegex,
              (match: string) => {
                const matchResult = match.match(/{{or:(.*?)}}/)
                if (matchResult === null) {
                  return { type: "html", value: "" }
                }
                const optionsString: string = matchResult[1]
                const options: string[] = optionsString.split("|")
                const selectHtml: string = `<select>${options.map((option: string) => `<option value="${option}">${option}</option>`).join("")}</select>`
                return { type: "html", value: selectHtml }
              },
            ])
          }
 
          if (opts.TODOComponent) {
            replacements.push([
              TODORegex,
              () => ({
                type: "html",
                value: `<input type="checkbox" disabled>`,
              }),
            ])
          }
 
          if (opts.DONEComponent) {
            replacements.push([
              DONERegex,
              () => ({
                type: "html",
                value: `<input type="checkbox" checked disabled>`,
              }),
            ])
          }
 
          if (opts.blockquoteComponent) {
            replacements.push([
              blockquoteRegex,
              (_match: string, _marker: string, content: string) => ({
                type: "html",
                value: `<blockquote>${content.trim()}</blockquote>`,
              }),
            ])
          }
 
          mdastFindReplace(tree, replacements)
        }
      })
 
      return plugins
    },
  }
}