Skip to content

feat(*): Using shiki for highlighting #1788

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

Closed
Closed
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
2,643 changes: 1,270 additions & 1,373 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,9 @@
"peerDependencies": {
"@google/genai": "^1.3.0",
"@supabase/supabase-js": "^2.49.4",
"dompurify": "^3.2.6",
"marked": "^12.0.0"
"marked": "^12.0.2",
"marked-highlight": "^2.2.2",
"shiki": "^3.8.0"
},
"browserslist": [
"defaults"
Expand Down
43 changes: 24 additions & 19 deletions src/components/chat/chat-message.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { consume } from '@lit/context';
import DOMPurify from 'dompurify';
import { html, LitElement, nothing } from 'lit';
import { property } from 'lit/decorators.js';
import { html, LitElement, nothing, type TemplateResult } from 'lit';
import { property, state } from 'lit/decorators.js';
import IgcAvatarComponent from '../avatar/avatar.js';
import { chatContext } from '../common/context.js';
import { watch } from '../common/decorators/watch.js';
import { registerComponent } from '../common/definitions/register.js';
import type { ChatState } from './chat-state.js';
import { renderMarkdown } from './markdown-util.js';
import IgcMessageAttachmentsComponent from './message-attachments.js';
import { styles } from './themes/message.base.css.js';
import { styles as shared } from './themes/shared/chat-message.common.css.js';
Expand Down Expand Up @@ -61,14 +60,25 @@ export default class IgcChatMessageComponent extends LitElement {
@property({ attribute: false })
public message: IgcMessage | undefined;

/**
* Sanitizes message text to prevent XSS or invalid HTML.
* @param text The raw message text
* @returns Sanitized text safe for HTML rendering
* @private
*/
private sanitizeMessageText(text: string): string {
return DOMPurify.sanitize(text);
@state()
private _renderedMarkdown: TemplateResult | null = null;

@watch('message')
async processMarkdown() {
const text = this.message?.text.trim() || '';

if (this._chatState?.options?.supportsMarkdown !== true) {
this._renderedMarkdown = html`${text}`;
return;
}

const renderer = this._chatState?.options?.markdownRenderer;
if (renderer) {
this._renderedMarkdown = renderer(text);
} else {
const { renderMarkdown } = await import('./markdown-util.js');
this._renderedMarkdown = await renderMarkdown(text);
}
}

/**
Expand All @@ -79,19 +89,14 @@ export default class IgcChatMessageComponent extends LitElement {
*/
protected override render() {
const containerPart = `message-container ${this.message?.sender === this._chatState?.currentUserId ? 'sent' : ''}`;
const sanitizedMessageText = this.sanitizeMessageText(
this.message?.text.trim() || ''
);
const renderer =
this._chatState?.options?.markdownRenderer || renderMarkdown;

return html`
<div part=${containerPart}>
<div part="bubble">
${this._chatState?.options?.templates?.messageTemplate && this.message
? this._chatState.options.templates.messageTemplate(this.message)
: html` ${sanitizedMessageText
? html`<div>${renderer(sanitizedMessageText)}</div>`
: html` ${this._renderedMarkdown
? html`<div>${this._renderedMarkdown}</div>`
: nothing}
${this.message?.attachments &&
this.message?.attachments.length > 0
Expand Down
7 changes: 6 additions & 1 deletion src/components/chat/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,13 @@ export default class IgcChatComponent extends EventEmitterMixin<
</div>`;
}

protected override firstUpdated() {
protected override async firstUpdated() {
this._context.setValue(this._chatState, true);
if (!this._chatState.options?.highlighter) return;

const { configureMarkdownHighlighter } = await import('./markdown-util.js');
await configureMarkdownHighlighter(this._chatState.options.highlighter);
this.requestUpdate();
}

protected override render() {
Expand Down
57 changes: 57 additions & 0 deletions src/components/chat/highlighter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
type CodeToHastOptions,
createHighlighterCore,
type HighlighterCore,
} from '@shikijs/core';
import { createJavaScriptRegexEngine } from '@shikijs/engine-javascript';

export class CodeHighlighter {
private highlighterPromise: Promise<HighlighterCore>;

constructor(
public langs: Promise<any>[],
public themes: Promise<any>[],
engine = createJavaScriptRegexEngine()
) {
this.highlighterPromise = createHighlighterCore({
langs,
themes,
engine,
});
}

async highlight(code: string, lang: string): Promise<string> {
const highlighter = await this.highlighterPromise;
const resolvedLang = highlighter.getLoadedLanguages().includes(lang)
? lang
: 'text';
const loadedThemes = highlighter.getLoadedThemes();

if (!loadedThemes?.length) return code;

let options: CodeToHastOptions<string, string>;
if (loadedThemes.length === 1) {
options = {
lang: resolvedLang,
theme: loadedThemes[0],
};
} else {
const [lightTheme, darkTheme] = loadedThemes;
options = {
lang: resolvedLang,
themes: {
light: lightTheme,
dark: darkTheme,
},
};
}

return highlighter.codeToHtml(code, options);
}
}

export function createMarkdownHighlighter(highlighter: CodeHighlighter) {
return async function highlight(code: string, lang: string) {
return await highlighter.highlight(code, lang);
};
}
80 changes: 69 additions & 11 deletions src/components/chat/markdown-util.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,85 @@
import { html, type TemplateResult } from 'lit';
import { marked } from 'marked';
import { markedHighlight } from 'marked-highlight';
import { CodeHighlighter, createMarkdownHighlighter } from './highlighter.js';
import type { ICodeHighlighter } from './types.js';

const renderer = new marked.Renderer();

// Customize link rendering
renderer.link = (href, title, text) => {
return `<a href="${href}" target="_blank" rel="noopener noreferrer" ${title ? `title="${title}"` : ''}>${text}</a>`;
};

marked.setOptions({
gfm: true,
breaks: true,
renderer,
});

const renderer = new marked.Renderer();

// Customize code rendering
renderer.code = (code, language) => {
return `<pre><code class="language-${language}">${code}</code></pre>`;
const languageModules: Record<string, () => Promise<any>> = {
javascript: () => import('@shikijs/langs/javascript'),
typescript: () => import('@shikijs/langs/typescript'),
json: () => import('@shikijs/langs/json'),
scss: () => import('@shikijs/langs/scss'),
html: () => import('@shikijs/langs/html'),
markdown: () => import('@shikijs/langs/markdown'),
// etc.
};

// Customize link rendering
renderer.link = (href, title, text) => {
return `<a href="${href}" target="_blank" rel="noopener noreferrer" ${title ? `title="${title}"` : ''}>${text}</a>`;
function loadLanguage(name: string): Promise<any> {
const loader = languageModules[name];
if (!loader) {
return Promise.resolve(undefined); // fallback to text
}
return loader();
}

const themeModules: Record<string, () => Promise<any>> = {
'github-light': () => import('@shikijs/themes/github-light'),
'github-dark': () => import('@shikijs/themes/github-dark'),
'min-light': () => import('@shikijs/themes/min-light'),
'min-dark': () => import('@shikijs/themes/min-dark'),
// etc.
};

export function renderMarkdown(text: string): TemplateResult {
if (!text) return html``;
function loadTheme(name: string): Promise<any> {
const loader = themeModules[name];
if (!loader) {
return Promise.resolve(undefined);
}
return loader();
}

// This will be our local marked instance — one per configuration
// let localMarked: Marked | null = null;

export async function configureMarkdownHighlighter(
highlighterConfig?: ICodeHighlighter
) {
if (highlighterConfig) {
const languageImports = highlighterConfig.languages.map(loadLanguage);
const themeImports = highlighterConfig.themes.map(loadTheme);

const rendered = marked(text, { renderer }).toString();
const [langs, themes] = await Promise.all([
Promise.all(languageImports),
Promise.all(themeImports),
]);

const highlighter = new CodeHighlighter(langs, themes);

marked.use(
markedHighlight({
async: true,
highlight: createMarkdownHighlighter(highlighter),
})
);
}
}

export async function renderMarkdown(text: string): Promise<TemplateResult> {
if (!text) return html``;
const rendered = await marked.parse(text);
const template = document.createElement('template');
template.innerHTML = rendered;

Expand Down
6 changes: 6 additions & 0 deletions src/components/chat/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ export interface IgcMessageAttachment {
*/
thumbnail?: string;
}
export interface ICodeHighlighter {
languages: string[];
themes: string[];
}

/**
* A function type used to render a group of attachments in a chat message.
Expand Down Expand Up @@ -138,6 +142,8 @@ export type IgcChatOptions = {
* A set of template override functions used to customize rendering of messages, attachments, etc.
*/
templates?: IgcChatTemplates;
supportsMarkdown: boolean;
highlighter?: ICodeHighlighter;
markdownRenderer?: (text: string) => TemplateResult; //TODO: Remove when highlighter is implemented
};

Expand Down
21 changes: 16 additions & 5 deletions stories/chat.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/web-components-vite';
import { html } from 'lit';

import { GoogleGenAI, Modality } from '@google/genai';
import { createClient } from '@supabase/supabase-js';
// import { createClient } from '@supabase/supabase-js';
import {
IgcChatComponent,
defineComponents,
Expand All @@ -13,9 +13,9 @@ import type {
IgcMessageAttachment,
} from '../src/components/chat/types.js';

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);
// const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
// const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
const supabase = ''; //createClient(supabaseUrl, supabaseKey);

const ai = new GoogleGenAI({
apiKey: googleGenAIKey,
Expand Down Expand Up @@ -141,12 +141,23 @@ const ai_chat_options = {
// textAreaActionsTemplate: _textAreaActionsTemplate,
// textAreaAttachmentsTemplate: _textAreaAttachmentsTemplate,
},
// markdownRenderer: _customRenderer
supportsMarkdown: true,
// markdownRenderer: _customRenderer,
highlighter: {
languages: ['javascript', 'html', 'typescript', 'scss'],
themes: ['github-light'],
},
};

const chat_options = {
disableAutoScroll: false,
disableAttachments: true,
supportsMarkdown: true,
// markdownRenderer: _customRenderer,
highlighter: {
languages: ['javascript', 'html', 'typescript', 'scss'],
themes: ['github-light'],
},
};

function handleCustomSendClick() {
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitOverride": true,
"moduleResolution": "node",
"moduleResolution": "node16",
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"forceConsistentCasingInFileNames": true,
Expand Down