main
ts 55 lines 2.1 KB
Raw
1 import { CFG, prefix } from './misc'
2 import { watchLoad } from './watchLoad'
3 import { defineConfig } from './config'
4 import Dict = NodeJS.Dict
5 import { writeFile } from 'fs/promises'
6 import { mapPlugins } from './plugins'
7 import _ from 'lodash'
8
9 const FILE = 'custom.html'
10
11 export const customHtmlSections: ReadonlyArray<string> = ['style', 'script', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
12 'footer', 'top', 'bottom', 'afterEntryName', 'beforeLogin', 'unauthorized', 'htmlHead', 'userPanelAfterInfo']
13
14 export const customHtml = watchLoadCustomHtml()
15 export const disableCustomHtml = defineConfig(CFG.disable_custom_html, false)
16
17 export function watchLoadCustomHtml(folder='') {
18 const sections = new Map<string, string>()
19 const res = watchLoad(prefix('', folder, '/') + FILE, data => {
20 const re = /^\[([^\]]+)] *$/gm
21 sections.clear()
22 if (!data) return
23 let name: string | undefined = 'top'
24 do {
25 let last = re.lastIndex
26 const match = re.exec(data)
27 const content = data.slice(last, !match ? undefined : re.lastIndex - (match?.[0]?.length || 0)).trim()
28 if (content)
29 sections.set(name, content)
30 name = match?.[1]
31 } while (name)
32 })
33 return Object.assign(res, { sections })
34 }
35
36 export function getSection(name: string) {
37 return (!disableCustomHtml.get() && customHtml.sections.get(name) || '')
38 + mapPlugins(pl => pl.getData().getCustomHtml()[name]).join('\n')
39 }
40
41 export function getAllSections() {
42 const keys = mapPlugins(pl => Object.keys(pl.getData().getCustomHtml()))
43 keys.push(Array.from(customHtml.sections.keys()))
44 const all = _.uniq(keys.flat())
45 return Object.fromEntries(all.map(x => [x, getSection(x)]))
46 }
47
48 export async function saveCustomHtml(sections: Dict<string>) {
49 const text = Object.entries(sections).filter(([k,v]) => v?.trim()).map(([k,v]) => `[${k}]\n${v}\n\n`).join('')
50 await writeFile(FILE, text)
51 customHtml.sections.clear()
52 for (const [k,v] of Object.entries(sections))
53 if (v)
54 customHtml.sections.set(k, v)
55 }