返回 oh-my-ppt
master-link.ts
根目录 / src / main / presentation / html / master-link.ts
1 import * as cheerio from 'cheerio'
2 import { MASTER_CSS_HREF, MASTER_LINK_SELECTOR } from '@shared/master'
3
4 export const buildMasterStyleLink = (): string =>
5 `<link rel="stylesheet" href="${MASTER_CSS_HREF}" data-ppt-master="1">`
6
7 const isMasterHref = (href: string | undefined): boolean => {
8 if (!href) return false
9 const normalized = href.trim().split(/[?#]/, 1)[0]?.replace(/\\/g, '/')
10 return (
11 normalized === MASTER_CSS_HREF ||
12 normalized === MASTER_CSS_HREF.slice(2)
13 )
14 }
15
16 export function ensureMasterStyleLink(html: string): string {
17 const $ = cheerio.load(html, { scriptingEnabled: false })
18 if ($('head').length === 0) $('html').prepend('<head></head>')
19 $('link').each((_, element) => {
20 const link = $(element)
21 if (link.is(MASTER_LINK_SELECTOR) || isMasterHref(link.attr('href'))) link.remove()
22 })
23 $('head').append(`\n ${buildMasterStyleLink()}\n`)
24 return $.html()
25 }
26
27 export function hasUniqueMasterStyleLink(html: string): boolean {
28 const $ = cheerio.load(html, { scriptingEnabled: false })
29 const masterLinks = $('link').filter((_, element) => isMasterHref($(element).attr('href')))
30 if (masterLinks.length !== 1) return false
31 const link = masterLinks.first()
32 return link.is(MASTER_LINK_SELECTOR) && link.attr('href') === MASTER_CSS_HREF
33 }
34
35 export function setMasterPageNumber(html: string, pageNumber: number): string {
36 const normalizedPageNumber = Math.max(1, Math.floor(pageNumber))
37 if (!Number.isFinite(normalizedPageNumber)) return html
38 const $ = cheerio.load(html, { scriptingEnabled: false })
39 const value = String(normalizedPageNumber)
40 $('body').first().attr('data-ppt-page-number', value)
41 $('.ppt-page-root[data-ppt-guard-root="1"]').first().attr('data-ppt-page-number', value)
42 return $.html()
43 }
44
45 export function isMasterElementsDisabled(html: string): boolean {
46 const $ = cheerio.load(html, { scriptingEnabled: false })
47 return (
48 $('body').first().attr('data-ppt-master-off') === '1' ||
49 $('.ppt-page-root[data-ppt-guard-root="1"]').first().attr('data-ppt-master-off') === '1'
50 )
51 }
52
53 export function setMasterElementsDisabled(html: string, disabled: boolean): string {
54 const $ = cheerio.load(html, { scriptingEnabled: false })
55 const body = $('body').first()
56 const root = $('.ppt-page-root[data-ppt-guard-root="1"]').first()
57 if (disabled) {
58 body.attr('data-ppt-master-off', '1')
59 root.attr('data-ppt-master-off', '1')
60 } else {
61 body.removeAttr('data-ppt-master-off')
62 root.removeAttr('data-ppt-master-off')
63 }
64 return $.html()
65 }
66
66 lines TYPESCRIPT