-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlink-renderer.ts
49 lines (40 loc) · 1.54 KB
/
link-renderer.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
import {IframeRenderer} from './iframe-renderer'
import {WikipediaRenderer} from './wikipedia-renderer'
import {findAsync, someAsync} from '../common/async'
import {ManifoldRenderer} from './manifold-renderer'
export interface LinkRenderer {
canRender(url: URL): Promise<boolean>
render(url: URL): Promise<HTMLElement>
}
export const siteSpecificRenderers: LinkRenderer[] = [
new ManifoldRenderer(),
new WikipediaRenderer()
]
/**
* Order is priority
*/
export const defaultRenderers: LinkRenderer[] = [
...siteSpecificRenderers,
new IframeRenderer(),
]
export const render = async (link: URL, renderers: LinkRenderer[] = defaultRenderers): Promise<HTMLElement | null> => {
// Do pre-check,so we can assume something is going to render and do that async
if (!await canRender(link, renderers)) return null
const renderContainer = defaultRenderContainer()
renderComponent(renderers, link)?.then(component => {
renderContainer.append(component)
})
return renderContainer
}
export const canRender = async (link: URL, renderers: LinkRenderer[] = defaultRenderers): Promise<boolean> =>
someAsync(renderers, renderer => renderer.canRender(link))
const renderComponent = async (renderers: LinkRenderer[], link: URL) => {
const renderer = await findAsync(renderers, r => r.canRender(link))
if (!renderer) throw new Error('No matching renderer found')
return renderer.render(link)
}
function defaultRenderContainer() {
const renderContainer = document.createElement('div')
renderContainer.className = 'link-preview-container'
return renderContainer
}