mirror of
https://github.com/d0zingcat/BroadcastChannel.git
synced 2026-05-22 23:16:46 +00:00
parse code snippets ie ``js const a = 1;`` in Telegram and perform syntax highlighting in the post using Prism
This commit is contained in:
@@ -1,8 +1,12 @@
|
||||
import { $fetch } from 'ofetch'
|
||||
import * as cheerio from 'cheerio'
|
||||
import { LRUCache } from 'lru-cache'
|
||||
import Prism from 'prismjs'
|
||||
import loadLanguages from 'prismjs/components/'
|
||||
import { getEnv } from '../env'
|
||||
|
||||
loadLanguages(['javascript', 'python', 'css', 'html'])
|
||||
|
||||
const cache = new LRUCache({
|
||||
ttl: 1000 * 60 * 5, // 5 minutes
|
||||
maxSize: 50 * 1024 * 1024, // 50MB
|
||||
@@ -108,9 +112,33 @@ function modifyHTMLContent($, content, { index } = {}) {
|
||||
?.wrap('<label class="spoiler-button"></label>')
|
||||
?.before(`<input type="checkbox" />`)
|
||||
})
|
||||
$(content).find('pre').each((_index, pre) => {
|
||||
const code = $(pre).text()
|
||||
const language = detectLanguage(code) // You'll need to implement this function
|
||||
const highlightedCode = Prism.highlight(code, Prism.languages[language], language)
|
||||
$(pre).html(`<code class="language-${language}">${highlightedCode}</code>`)
|
||||
})
|
||||
return content
|
||||
}
|
||||
|
||||
function detectLanguage(code) {
|
||||
// Implement a simple language detection logic
|
||||
// This is a basic example and might need refinement
|
||||
if (code.includes('function') || code.includes('const') || code.includes('let')) {
|
||||
return 'javascript'
|
||||
}
|
||||
else if (code.includes('def ') || code.includes('import ')) {
|
||||
return 'python'
|
||||
}
|
||||
else if (code.includes('<html>') || code.includes('<!DOCTYPE html>')) {
|
||||
return 'html'
|
||||
}
|
||||
else if (code.includes('{') && code.includes('}') && code.includes(':')) {
|
||||
return 'css'
|
||||
}
|
||||
return 'clike' // default to C-like syntax
|
||||
}
|
||||
|
||||
function getPost($, item, { channel, staticProxy, index = 0 }) {
|
||||
item = item ? $(item).find('.tgme_widget_message') : $('.tgme_widget_message')
|
||||
const content = $(item).find('.js-message_reply_text')?.length > 0
|
||||
|
||||
Reference in New Issue
Block a user