Skip to content

feat(plugins): render markdown codehighlight #213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 6, 2024
Merged
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
18 changes: 18 additions & 0 deletions render-markdown-codehighlight/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
8 changes: 8 additions & 0 deletions render-markdown-codehighlight/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"trailingComma": "all",
"tabWidth": 2,
"singleQuote": true,
"jsxBracketSameLine": true,
"printWidth": 80,
"endOfLine": "auto"
}
11 changes: 11 additions & 0 deletions render-markdown-codehighlight/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# RenderMarkdownCodehighlight Plugin
The `RenderMarkdownCodehighlight` plugin improves the readability of code snippets within Markdown content by integrating highlight.js for syntax highlighting. It supports dynamic theme switching, allowing code blocks to adapt seamlessly to either light or dark themes based on your application's current theme. This makes code blocks more visually appealing and easier to read.

### Features
Dynamic Theme Switching: Automatically switches between light and dark modes for code highlighting based on the selected theme.
Theme Support: Supports various highlight.js themes, with some themes designed for both light and dark modes, while others are specifically tailored for one mode.

### Theme Types
theme-all: These themes support both light and dark modes, automatically adjusting based on the application's current theme.
theme-light: These themes are optimized for light mode and will use default dark mode.
theme-dark: These themes are designed specifically for dark mode and will use default light mode.
209 changes: 209 additions & 0 deletions render-markdown-codehighlight/generate-theme.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

const fs = require('fs');
const path = require('path');

const stylesDir = path.resolve(__dirname, 'node_modules/highlight.js/styles'); // Path to Highlight.js styles directory
const jsOutputFile = path.resolve(__dirname, 'themeStyles.js'); // Path to output JavaScript file
const goOutputFile = path.resolve(__dirname, 'theme_list.go'); // Path to output Go file
const colorInfoOutputFile = path.resolve(__dirname, 'themeColors.js'); // Path to output color information file

// Read all CSS files from the styles directory
let themes = fs.readdirSync(stylesDir).filter(file => file.endsWith('.css'));

// Prioritize .min.css files
const minifiedFiles = new Set(themes.filter(file => file.endsWith('.min.css')).map(file => file.replace('.min.css', '')));
themes = themes.filter(file => {
const baseName = file.replace('.css', '').replace('.min', '');
// Skip unminified versions if corresponding .min.css file exists
return !minifiedFiles.has(baseName) || file.endsWith('.min.css');
});

// Group themes and classify by naming conventions
const themeMap = {};
let themeList = [];
const themeColors = [];
let defaultDarkTheme = null;
let defaultLightTheme = null;

const cssColorNames = {
black: '#000000',
white: '#ffffff',
navy: '#000080',
// Add more color names as needed if the background color in css is not defined in a standard method
};

// Convert color names (e.g., 'black', 'white') to hex values
function convertColorNameToHex(colorName) {
return cssColorNames[colorName.toLowerCase()] || null;
}

// Normalize hex color code (e.g., convert shorthand hex to full length)
function normalizeHexColor(hexColor) {
hexColor = hexColor.startsWith('#') ? hexColor.slice(1) : hexColor;
if (hexColor.length === 3) {
hexColor = hexColor.split('').map(char => char + char).join('');
}
return hexColor;
}

// Determine if a theme is dark based on its background color
function isDarkTheme(color) {
if (!color.startsWith('#') && !color.startsWith('rgb')) {
const hexColor = convertColorNameToHex(color);
if (hexColor) {
color = hexColor;
} else {
return false;
}
}
const hexColor = normalizeHexColor(color);
const rgb = parseInt(hexColor, 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = (rgb >> 0) & 0xff;
const brightness = (r * 299 + g * 587 + b * 114) / 1000; // Calculate brightness based on RGB values
return brightness < 128; // Dark theme if brightness is below the threshold
}

// Process each theme file
themes.forEach(file => {
const themeName = file.replace('.css', '').replace('.min', '');
const [base, ...variantParts] = themeName.split('-');
const variant = variantParts.join('-');

if (!themeMap[base]) {
themeMap[base] = {};
}

let isDark = false;
let backgroundColor = null;

// Identify light or dark themes based on the variant name
if (variant.includes('light')) {
if (!themeMap[base].light || themeMap[base].light.length > file.length) {
themeMap[base].light = `() => import('highlight.js/styles/${file}?inline')`;
if (!defaultLightTheme) {
defaultLightTheme = themeMap[base].light;
}
}
} else if (variant.includes('dark')) {
if (!themeMap[base].dark || themeMap[base].dark.length > file.length) {
themeMap[base].dark = `() => import('highlight.js/styles/${file}?inline')`;
if (!defaultDarkTheme) {
defaultDarkTheme = themeMap[base].dark;
}
}
} else {
// Extract background color from CSS content and determine if it's a dark theme
const cssContent = fs.readFileSync(path.resolve(stylesDir, file), 'utf-8');
const backgroundMatch = cssContent.match(/\.hljs\s*{[^}]*?\s*background(?:-color)?:\s*(#[0-9a-fA-F]{3,6}|rgb\([^)]+\)|[a-zA-Z]+|url\([^)]+\))/i);
backgroundColor = backgroundMatch ? backgroundMatch[1].trim() : null;

if (backgroundColor) {
if (backgroundColor.startsWith('url')) {
backgroundColor = null;
} else if (backgroundColor.startsWith('#')) {
isDark = isDarkTheme(backgroundColor);
} else if (backgroundColor.startsWith('rgb')) {
const rgbValues = backgroundColor.match(/\d+/g).map(Number);
const brightness = (rgbValues[0] * 299 + rgbValues[1] * 587 + rgbValues[2] * 114) / 1000;
isDark = brightness < 128;
} else {
isDark = isDarkTheme(backgroundColor);
}
}

// Assign the theme to light or dark based on the background color
if (isDark) {
if (!themeMap[base].dark || themeMap[base].dark.length > file.length) {
themeMap[base].dark = `() => import('highlight.js/styles/${file}?inline')`;
if (!defaultDarkTheme) {
defaultDarkTheme = themeMap[base].dark;
}
}
} else {
if (!themeMap[base].light || themeMap[base].light.length > file.length) {
themeMap[base].light = `() => import('highlight.js/styles/${file}?inline')`;
if (!defaultLightTheme) {
defaultLightTheme = themeMap[base].light;
}
}
}
}

// Add theme to the theme list
if (!themeList.includes(base)) {
themeList.push(base);
}

// Store theme color information
if (backgroundColor) {
themeColors.push({
theme: base,
variant: isDark ? 'dark' : 'light',
color: backgroundColor
});
}
});

// Classify themes based on the presence of light and dark variants
themeList = themeList.map(base => {
if (themeMap[base].light && !themeMap[base].dark) {
return `${base}-light`;
} else if (!themeMap[base].light && themeMap[base].dark) {
return `${base}-dark`;
} else if (themeMap[base].light && themeMap[base].dark) {
return `${base}-all`;
} else {
return base;
}
});

// Assign default light and dark themes if missing
Object.keys(themeMap).forEach(base => {
if (!themeMap[base].dark && defaultDarkTheme) {
themeMap[base].dark = defaultDarkTheme;
}
if (!themeMap[base].light && defaultLightTheme) {
themeMap[base].light = defaultLightTheme;
}
});

// Generate the JavaScript output for theme styles
const jsOutput = `export const themeStyles = {\n${Object.entries(themeMap)
.map(([theme, variants]) =>
` ${JSON.stringify(theme)}: {\n light: ${variants.light},\n dark: ${variants.dark}\n }`
).join(',\n')}\n};`;

fs.writeFileSync(jsOutputFile, jsOutput); // Write the theme styles to JavaScript file

// Generate the Go output for theme list
const goOutput = `
package render_markdown_codehighlight

var ThemeList = []string{
${themeList.map(theme => `"${theme}"`).join(",\n ")},
}
`;

fs.writeFileSync(goOutputFile, goOutput); // Write the theme list to Go file

console.log('Theme styles, Go theme list, and color information generated successfully!');
46 changes: 46 additions & 0 deletions render-markdown-codehighlight/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
module github.com/apache/incubator-answer-plugins/render-markdown-codehighlight

go 1.22.6

require (
github.com/apache/incubator-answer v1.3.6
github.com/apache/incubator-answer-plugins/util v1.0.2
)

require (
github.com/LinkinStars/go-i18n/v2 v2.2.2 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.9.1 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.14.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/wire v0.5.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/microcosm-cc/bluemonday v1.0.21 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/segmentfault/pacman v1.0.5-0.20230822083413-c0075a2d401f // indirect
github.com/segmentfault/pacman/contrib/i18n v0.0.0-20230516093754-b76aef1c1150 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
Loading