Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -540,10 +540,33 @@ async function ensureDevCssPlaceholders(cssFiles) {
)
}

/** Remove unused font resources from a variant without math rendering. */
async function removeKatexResources(outputDir) {
const manifestPath = path.join(outputDir, 'manifest.json')
const manifest = await fs.readJson(manifestPath)
const keepResource = (resource) => resource !== 'katex-fonts/*.woff2'
if (manifest.manifest_version === 3) {
manifest.web_accessible_resources = manifest.web_accessible_resources
.map((entry) => ({ ...entry, resources: entry.resources.filter(keepResource) }))
.filter((entry) => entry.resources.length > 0)
} else {
manifest.web_accessible_resources = manifest.web_accessible_resources.filter(keepResource)
}
await fs.writeJson(manifestPath, manifest, { spaces: 2 })
}

/** Copy and package the shared assets for Chromium and Firefox variants. */
async function finishOutput(outputDirSuffix, sourceBuildDir = outdir) {
const includesKatex = !outputDirSuffix.includes('without-katex')
const commonFiles = [
{ src: 'src/logo.png', dst: 'logo.png' },
{ src: 'src/rules.json', dst: 'rules.json' },
...(includesKatex
? [
{ src: 'src/components/MarkdownRender/katex-fonts.css', dst: 'katex-fonts.css' },
{ src: 'node_modules/katex/dist/fonts', dst: 'katex-fonts' },
]
: []),

{ src: `${sourceBuildDir}/shared.js`, dst: 'shared.js' },
{ src: `${sourceBuildDir}/content-script.css`, dst: 'content-script.css' }, // shared
Expand Down Expand Up @@ -585,6 +608,7 @@ async function finishOutput(outputDirSuffix, sourceBuildDir = outdir) {
),
),
)
if (!includesKatex) await removeKatexResources(chromiumOutputDir)
if (isProduction) await zipFolder(chromiumOutputDir)

// firefox
Expand All @@ -602,6 +626,7 @@ async function finishOutput(outputDirSuffix, sourceBuildDir = outdir) {
),
),
)
if (!includesKatex) await removeKatexResources(firefoxOutputDir)
if (isProduction) await zipFolder(firefoxOutputDir)
}

Expand Down
181 changes: 181 additions & 0 deletions src/components/MarkdownRender/katex-fonts.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/* Loaded only when ChatGPTBox renders math. */
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
@font-face {
font-display: swap;
font-family: KaTeX_AMS;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_AMS-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_AMS-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_AMS-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Caligraphic;
font-style: normal;
font-weight: 700;
src: url('katex-fonts/KaTeX_Caligraphic-Bold.woff2') format('woff2'),
url('katex-fonts/KaTeX_Caligraphic-Bold.woff') format('woff'),
url('katex-fonts/KaTeX_Caligraphic-Bold.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Caligraphic;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Caligraphic-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Caligraphic-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Caligraphic-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Fraktur;
font-style: normal;
font-weight: 700;
src: url('katex-fonts/KaTeX_Fraktur-Bold.woff2') format('woff2'),
url('katex-fonts/KaTeX_Fraktur-Bold.woff') format('woff'),
url('katex-fonts/KaTeX_Fraktur-Bold.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Fraktur;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Fraktur-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Fraktur-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Fraktur-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Main;
font-style: normal;
font-weight: 700;
src: url('katex-fonts/KaTeX_Main-Bold.woff2') format('woff2'),
url('katex-fonts/KaTeX_Main-Bold.woff') format('woff'),
url('katex-fonts/KaTeX_Main-Bold.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Main;
font-style: italic;
font-weight: 700;
src: url('katex-fonts/KaTeX_Main-BoldItalic.woff2') format('woff2'),
url('katex-fonts/KaTeX_Main-BoldItalic.woff') format('woff'),
url('katex-fonts/KaTeX_Main-BoldItalic.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Main;
font-style: italic;
font-weight: 400;
src: url('katex-fonts/KaTeX_Main-Italic.woff2') format('woff2'),
url('katex-fonts/KaTeX_Main-Italic.woff') format('woff'),
url('katex-fonts/KaTeX_Main-Italic.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Main;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Main-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Main-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Main-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Math;
font-style: italic;
font-weight: 700;
src: url('katex-fonts/KaTeX_Math-BoldItalic.woff2') format('woff2'),
url('katex-fonts/KaTeX_Math-BoldItalic.woff') format('woff'),
url('katex-fonts/KaTeX_Math-BoldItalic.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Math;
font-style: italic;
font-weight: 400;
src: url('katex-fonts/KaTeX_Math-Italic.woff2') format('woff2'),
url('katex-fonts/KaTeX_Math-Italic.woff') format('woff'),
url('katex-fonts/KaTeX_Math-Italic.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_SansSerif;
font-style: normal;
font-weight: 700;
src: url('katex-fonts/KaTeX_SansSerif-Bold.woff2') format('woff2'),
url('katex-fonts/KaTeX_SansSerif-Bold.woff') format('woff'),
url('katex-fonts/KaTeX_SansSerif-Bold.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_SansSerif;
font-style: italic;
font-weight: 400;
src: url('katex-fonts/KaTeX_SansSerif-Italic.woff2') format('woff2'),
url('katex-fonts/KaTeX_SansSerif-Italic.woff') format('woff'),
url('katex-fonts/KaTeX_SansSerif-Italic.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_SansSerif;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_SansSerif-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_SansSerif-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_SansSerif-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Script;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Script-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Script-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Script-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Size1;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Size1-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Size1-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Size1-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Size2;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Size2-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Size2-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Size2-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Size3;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Size3-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Size3-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Size3-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Size4;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Size4-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Size4-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Size4-Regular.ttf') format('truetype');
}
@font-face {
font-display: swap;
font-family: KaTeX_Typewriter;
font-style: normal;
font-weight: 400;
src: url('katex-fonts/KaTeX_Typewriter-Regular.woff2') format('woff2'),
url('katex-fonts/KaTeX_Typewriter-Regular.woff') format('woff'),
url('katex-fonts/KaTeX_Typewriter-Regular.ttf') format('truetype');
}
135 changes: 135 additions & 0 deletions src/components/MarkdownRender/katex-fonts.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import Browser from 'webextension-polyfill'

const fontFiles = [
'KaTeX_AMS-Regular',
'KaTeX_Caligraphic-Bold',
'KaTeX_Caligraphic-Regular',
'KaTeX_Fraktur-Bold',
'KaTeX_Fraktur-Regular',
'KaTeX_Main-Bold',
'KaTeX_Main-BoldItalic',
'KaTeX_Main-Italic',
'KaTeX_Main-Regular',
'KaTeX_Math-BoldItalic',
'KaTeX_Math-Italic',
'KaTeX_SansSerif-Bold',
'KaTeX_SansSerif-Italic',
'KaTeX_SansSerif-Regular',
'KaTeX_Script-Regular',
'KaTeX_Size1-Regular',
'KaTeX_Size2-Regular',
'KaTeX_Size3-Regular',
'KaTeX_Size4-Regular',
'KaTeX_Typewriter-Regular',
].map((filename) => {
const [family, variant] = filename.split('-')
return {
filename,
family,
style: variant.includes('Italic') ? 'italic' : 'normal',
weight: variant.includes('Bold') ? '700' : '400',
}
})
const fontLoads = new WeakMap()

/** Watch actual formula changes instead of rebuilt React child identities. */
export function observeKatexFonts(root) {
let content
const update = () => {
const nextContent = root.outerHTML
if (nextContent === content) return
content = nextContent
loadKatexFonts(root)
}
const observer = new root.ownerDocument.defaultView.MutationObserver(update)
observer.observe(root, {
childList: true,
characterData: true,
attributes: true,
attributeFilter: ['class', 'style'],
subtree: true,
})
update()
return () => observer.disconnect()
}

function usedFonts(root) {
const document = root.ownerDocument
const html = root.querySelector('.katex-html')
const fonts = new Set()
if (!html) return fonts

// Inspect rendered glyphs, not the hidden MathML accessibility copy.
const walker = document.createTreeWalker(html, 4 /* NodeFilter.SHOW_TEXT */)
while (walker.nextNode()) {
const text = walker.currentNode
if (!text.data.trim()) continue
const style = document.defaultView.getComputedStyle(text.parentElement)
const families = style.fontFamily.split(',').map((family) => family.trim().replace(/['"]/g, ''))
const family = families.find((name) => fontFiles.some((font) => font.family === name))
const faces = fontFiles.filter((font) => font.family === family)
if (!faces.length) continue

const requestedStyle = /italic|oblique/.test(style.fontStyle) ? 'italic' : 'normal'
const styledFaces = faces.filter((font) => font.style === requestedStyle)
const candidates = styledFaces.length ? styledFaces : faces
const weight = Number(style.fontWeight) > 500 || style.fontWeight === 'bold' ? '700' : '400'
fonts.add(candidates.find((font) => font.weight === weight) || candidates[0])
}
return fonts
}

async function loadFont(font, document) {
// Retry a transient failure once, even if the mounted formula does not change.
for (let attempt = 0; attempt < 2; attempt++) {
try {
const response = await fetch(Browser.runtime.getURL(`katex-fonts/${font.filename}.woff2`))
if (!response.ok) throw new Error(`Failed to fetch ${font.filename}: ${response.status}`)
// Binary sources avoid the host page's font-src restriction.
const face = new FontFace(font.family, await response.arrayBuffer(), {
style: font.style,
weight: font.weight,
})
await face.load()
document.fonts.add(face)
return
} catch (error) {
if (attempt === 1) throw error
await new Promise((resolve) => setTimeout(resolve, 250))
}
}
}

/** Load only faces used by a rendered KaTeX subtree; cache each face independently. */
export function loadKatexFonts(root) {
if (!root) return Promise.resolve()
const document = root.ownerDocument
if (document.location.origin === new URL(Browser.runtime.getURL('/')).origin) {
if (!document.getElementById('chatgptbox-katex-fonts')) {
const stylesheet = document.createElement('link')
stylesheet.id = 'chatgptbox-katex-fonts'
stylesheet.rel = 'stylesheet'
stylesheet.href = Browser.runtime.getURL('katex-fonts.css')
document.head.appendChild(stylesheet)
}
return Promise.resolve()
}

let cache = fontLoads.get(document)
if (!cache) {
cache = new Map()
fontLoads.set(document, cache)
}
return Promise.all(
[...usedFonts(root)].map((font) => {
if (!cache.has(font.filename)) {
const loading = loadFont(font, document).catch((error) => {
cache.delete(font.filename)
console.warn('[markdown] Failed to load KaTeX font', error)
})
cache.set(font.filename, loading)
}
return cache.get(font.filename)
}),
)
}
Loading
Loading