### Install monaco-themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Installation commands for common package managers.
```bash
npm install monaco-themes
# or
pnpm add monaco-themes
# or
yarn add monaco-themes
```
--------------------------------
### Install monaco-themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Install the monaco-themes package using npm, pnpm, or yarn.
```sh
npm install monaco-themes
# or
pnpm add monaco-themes
# or
yarn add monaco-themes
```
--------------------------------
### Start Development Server
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Launches the Vite development server for local testing.
```bash
pnpm dev
```
--------------------------------
### Install Dependencies for Development
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Install project dependencies using pnpm.
```sh
pnpm install
```
--------------------------------
### TextMate plist XML example
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/internal-interfaces.md
An example of a raw TextMate theme XML file before deserialization.
```xml
settingssettingsbackground#272822foreground#f8f8f2scopecommentsettingsforeground#75715efontStyleitalic
```
--------------------------------
### Complete Monaco Editor Setup
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Demonstrates registering pre-built themes, parsing custom TextMate themes, and initializing the editor with a selected theme.
```typescript
import { parseTmTheme, MonacoTheme } from 'monaco-themes';
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
import draculaTheme from 'monaco-themes/themes/Dracula.json';
// Register pre-built themes
monaco.editor.defineTheme('monokai', monakoiTheme as MonacoTheme);
monaco.editor.defineTheme('dracula', draculaTheme as MonacoTheme);
// Parse a custom TextMate theme
const customThemeContent = await fetch('/themes/custom.tmTheme').then(r => r.text());
const customTheme = parseTmTheme(customThemeContent);
monaco.editor.defineTheme('custom', customTheme);
// Create editor with a theme
const editor = monaco.editor.create(element, {
theme: 'monokai',
});
```
--------------------------------
### Development Server Script
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Start the development server using Vite with the 'pnpm dev' command.
```sh
pnpm dev
```
--------------------------------
### Complete HTML Page Integration
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Full implementation example using the Monaco Editor loader and fetching a theme JSON file directly in the browser.
```html
```
--------------------------------
### Example TextMate Scope Definition
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/internal-interfaces.md
An example of a TextMate theme settings entry containing multiple comma-separated scopes.
```xml
scopestring, constant.string, meta.stringsettingsforeground#e6db74
```
--------------------------------
### Theme Switcher Implementation
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Example of a UI-driven theme switcher that dynamically imports and registers themes.
```typescript
const themeNames = ['Monokai', 'Dracula', 'GitHub', 'Solarized-dark'];
const themeSelect = document.querySelector('select');
themeSelect.innerHTML = themeNames
.map(name => ``)
.join('');
themeSelect.addEventListener('change', async (event) => {
const themeName = event.target.value;
const theme = await import(`monaco-themes/themes/${themeName}.json`);
const themeData = theme.default || theme;
monaco.editor.setTheme(themeName.toLowerCase());
// Pre-register for future use (only once)
if (!monaco.editor._themes[themeName.toLowerCase()]) {
monaco.editor.defineTheme(themeName.toLowerCase(), themeData);
}
});
```
--------------------------------
### Usage examples for parseColor
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/color-parsing.md
Demonstrates how various input formats are normalized or handled by the function.
```typescript
parseColor('#272822') // → '#272822' (valid 6-digit hex)
parseColor('#f0f') // → '#ff00ff' (expanded short form)
parseColor('#ffffff80') // → 'rgba(255, 255, 255, 0.5)' (RGBA)
parseColor('') // → null (empty string)
parseColor('rgb(255,0,0)') // → null (invalid format, logged as error)
```
--------------------------------
### Usage of MonacoTheme
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/types.md
Example of parsing a theme string and the resulting object structure.
```typescript
import { parseTmTheme } from 'monaco-themes';
const monacoTheme: MonacoTheme = parseTmTheme(tmThemeString);
// Example output structure
const example: MonacoTheme = {
base: 'vs-dark',
inherit: true,
rules: [
{
token: '',
background: '272822',
},
{
token: 'comment',
foreground: '75715e',
fontStyle: 'italic',
},
{
token: 'string',
foreground: 'e6db74',
},
],
colors: {
'editor.background': '#272822',
'editor.foreground': '#f8f8f2',
'editor.selectionBackground': '#49483e',
'terminal.ansiRed': '#f92672',
'terminal.ansiGreen': '#a6e22e',
},
};
```
--------------------------------
### Parsing and Applying Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Usage example for converting theme content and applying it to the Monaco editor instance.
```typescript
import { parseTmTheme } from 'monaco-themes';
// Get theme content (from file, fetch, FileReader, etc.)
const content = await getThemeContent();
// Parse it
const monacoTheme = parseTmTheme(content);
// Use it
monaco.editor.defineTheme('mytheme', monacoTheme);
```
--------------------------------
### Node.js File Processing
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Example of reading a TextMate theme file from the filesystem and converting it to a Monaco-compatible JSON format.
```javascript
const fs = require('fs');
const { parseTmTheme } = require('monaco-themes');
// Process a TextMate theme file
const themeContent = fs.readFileSync('theme.tmTheme', 'utf8');
const monacoTheme = parseTmTheme(themeContent);
// Write as JSON
fs.writeFileSync('theme.json', JSON.stringify(monacoTheme, null, 2));
```
--------------------------------
### Parse TextMate Scope XML
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Example of a comma-separated scope string in TextMate XML format.
```xml
scopestring, constant.string, meta.string
```
--------------------------------
### Calculate relative luminance
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/color-parsing.md
Examples of calculating the relative luminance of various hex color strings.
```typescript
darkness('#000000') // → 0.0 (pure black)
darkness('#ffffff') // → 1.0 (pure white)
darkness('#272822') // → ~0.13 (very dark, Monokai background)
darkness('#f8f8f0') // → ~0.93 (very light)
```
--------------------------------
### Convert colors to RGB arrays
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/color-parsing.md
Examples of converting hex strings, functional RGB strings, and existing RGB arrays into a standardized number array.
```typescript
rgbColor('#272822') // → [39, 40, 34]
rgbColor('rgb(255, 0, 0)') // → [255, 0, 0]
rgbColor([128, 128, 128]) // → [128, 128, 128]
```
--------------------------------
### Define Global Color Object
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Example of the MonacoTheme.colors object containing mapped editor and terminal colors.
```typescript
colors: {
'editor.foreground': '#f8f8f2',
'editor.background': '#272822',
'terminal.ansiRed': '#f92672',
'terminal.ansiBrightGreen': '#a6e22e',
// ... (up to 41 colors)
}
```
--------------------------------
### Run Prepublish Tasks
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Executes the full build and theme generation pipeline, typically used before publishing.
```bash
pnpm prepublishOnly
# Runs: build && download && generate
```
--------------------------------
### Initialize and switch themes programmatically
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
Iterate through a list of themes to register them, then use setTheme to switch between them.
```typescript
const themes = [
'Monokai',
'Dracula',
'Solarized-dark',
'Solarized-light',
'GitHub',
];
async function initializeThemes() {
for (const themeName of themes) {
const themeModule = await import(
`monaco-themes/themes/${themeName}.json`
);
const theme = themeModule.default || themeModule;
monaco.editor.defineTheme(themeName.toLowerCase(), theme);
}
}
await initializeThemes();
// Later: switch themes
monaco.editor.setTheme('dracula');
```
--------------------------------
### Initialize Monaco Editor and Load Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/index.html
Sets up the Monaco editor environment, configures the editor worker, and initializes the editor with basic settings. It also includes event listeners for theme selection and loading local files.
```javascript
import * as MonacoThemes from 'monaco-themes';
var lang = document.getElementById('lang');
var loadedThemes = null;
var loadedThemesData = {};
var count = 0;
function loadTheme(theme) {
var path = './' + loadedThemes[theme] + '.json';
return fetch(path)
.then((r) => r.json())
.then((data) => {
loadedThemesData[theme] = data;
if (window.monaco) {
monaco.editor.defineTheme(theme, data);
}
return data;
});
}
function setEditorValue(jsn) {
if (!window.editor) {
return;
}
window.editor.setValue(
'const themeData = ' + JSON.stringify(jsn, null, 2),
);
}
function addFileListener() {
var fileNode = document.getElementById('file');
if (!window.FileReader) {
fileNode.disabled = true;
}
fileNode.addEventListener('change', function (ev) {
var file = ev.target.files[0];
var reader = new FileReader();
reader.onload = function (ev) {
var themeSlug = 'localtheme-' + count;
count++;
loadedThemes[themeSlug] = MonacoThemes.parseTmTheme(
ev.target.result,
);
monaco.editor.defineTheme(themeSlug, loadedThemes[themeSlug]);
monaco.editor.setTheme(themeSlug);
setEditorValue(loadedThemes[themeSlug]);
};
reader.readAsText(file);
});
}
lang.addEventListener('change', function (ev) {
var val = ev.target.value;
if (val === 'vs' || val === 'vs-dark' || val === 'hc-black') {
monaco.editor.setTheme(val);
return;
}
if (loadedThemesData[val]) {
monaco.editor.setTheme(val);
setEditorValue(loadedThemesData[val]);
} else {
loadTheme(val).then((data) => {
monaco.editor.setTheme(val);
setEditorValue(data);
});
}
});
function loadThemeList() {
return fetch('./themelist.json')
.then((r) => r.json())
.then((data) => {
loadedThemes = data;
var themes = Object.keys(data);
themes.forEach((theme) => {
var opt = document.createElement('option');
opt.value = theme;
opt.text = data[theme];
lang.add(opt);
});
});
}
loadThemeList();
require.config({
paths: {
vs: 'https://unpkg.com/monaco-editor@0.52.0/min/vs'
}
});
window.MonacoEnvironment = {
getWorkerUrl: function (workerId, label) {
return `data:text/javascript;charset=utf-8,${encodeURIComponent(`
self.MonacoEnvironment = { baseUrl: 'https://unpkg.com/monaco-editor@0.52.0/min' };
importScripts('https://unpkg.com/monaco-editor@0.52.0/min/vs/base/worker/workerMain.js');`)}
`;
},
};
require(['vs/editor/editor.main'], function () {
var editor = monaco.editor.create(document.getElementById('editor'), {
value: [
'{',
' "value": "Select a locally available tmtheme file or choose from the many pregenrated themes",',
'}',
].join('\n'),
language: 'javascript',
fontSize: 16,
fontFamily: 'monospace',
minimap: {
enabled: false,
},
scrollBeyondLastLine: false,
});
editor.focus();
window.editor = editor;
addFileListener();
});
```
--------------------------------
### Use Pre-built Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Import and define a pre-built theme directly from the library's theme directory.
```typescript
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
monaco.editor.defineTheme('monokai', monakoiTheme);
```
--------------------------------
### Import themes statically
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
Recommended approach for bundling themes directly into the application build.
```typescript
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
import draculaTheme from 'monaco-themes/themes/Dracula.json';
monaco.editor.defineTheme('monokai', monakoiTheme);
monaco.editor.defineTheme('dracula', draculaTheme);
```
--------------------------------
### Generate Pre-built Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Commands to fetch and parse TextMate theme files.
```bash
pnpm download # Fetch .tmTheme files from upstream
pnpm generate # Parse them with parseTmTheme()
```
--------------------------------
### Build Pipeline Commands
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Standard commands for managing dependencies, development, and production builds.
```bash
pnpm install # Install dependencies
pnpm dev # Start Vite dev server
pnpm build # Build ESM, CJS, IIFE outputs
pnpm download # Fetch source .tmTheme files from upstream
pnpm generate # Convert .tmTheme → Monaco JSON
```
--------------------------------
### Deserialized theme object structure
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/internal-interfaces.md
The resulting JavaScript object structure after the provided XML example is parsed.
```typescript
{
settings: [
{
settings: {
background: '#272822',
foreground: '#f8f8f2',
},
},
{
scope: 'comment',
settings: {
foreground: '#75715e',
fontStyle: 'italic',
},
},
],
}
```
--------------------------------
### Build Project
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Compiles the project into ESM, CommonJS, and IIFE formats with associated type declarations.
```bash
pnpm build
```
--------------------------------
### Build Library Script
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Build the library in ESM, CJS, and IIFE formats using the 'pnpm build' command.
```sh
pnpm build
```
--------------------------------
### Project File Structure
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/ARCHITECTURE.md
Visual representation of the source directory layout and module components.
```text
src/
└── index.ts (288 lines)
├── Type definitions (exported)
│ └── MonacoTheme interface
├── Type definitions (internal)
│ ├── RawThemeSettings
│ └── ColorMapping
├── Color utilities (private)
│ ├── rgbColor()
│ ├── darkness()
│ └── parseColor()
├── Mappings (module-level constants)
│ ├── COLOR_MAP (22 entries)
│ ├── ansiColorMap (16 entries)
│ └── GUTTER_COLOR_MAP (0 entries)
└── Main function (exported)
└── parseTmTheme()
```
--------------------------------
### Load Theme using Fetch API
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Fetch a theme JSON file from a local path and apply it to monaco-editor.
```js
/* load monaco */
fetch('/themes/Monokai.json')
.then((data) => data.json())
.then((data) => {
monaco.editor.defineTheme('monokai', data);
monaco.editor.setTheme('monokai');
});
```
--------------------------------
### Download Theme Files Script
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Download theme files from source repositories using the 'pnpm download' command.
```sh
pnpm download
```
--------------------------------
### Theme Data Flow Process
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/INDEX.md
Diagram illustrating the transformation pipeline from a TextMate XML plist file to a custom Monaco Editor theme.
```text
TextMate .tmTheme (XML plist)
↓ plist.parse()
RawThemeSettings
↓ parseTmTheme()
1. Extract global settings
2. Parse token rules
3. Normalize colors
4. Map color keys
5. Detect base theme
↓
MonacoTheme (JSON)
↓ monaco.editor.defineTheme()
Custom theme in editor
```
--------------------------------
### Define a pre-built theme in Monaco Editor
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/INDEX.md
Import a JSON theme file and register it with the Monaco editor instance using defineTheme.
```typescript
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
monaco.editor.defineTheme('monokai', monakoiTheme);
```
--------------------------------
### Load Themes via Bundled Import
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Recommended approach for built-in themes to ensure they are included in the application bundle.
```typescript
import monokai from 'monaco-themes/themes/Monokai.json';
monaco.editor.defineTheme('monokai', monokai);
```
--------------------------------
### Regenerate themes via CLI
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
Execute these commands to fetch the latest upstream themes and update the local Monaco JSON files.
```bash
# Download the latest .tmTheme files from upstream
pnpm download
# Convert them to Monaco JSON format
pnpm generate
# Verify and commit changes
git status
git add themes/
git commit -m "Update themes to latest upstream versions"
```
--------------------------------
### Generate Theme JSON Script
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Generate Monaco-compatible theme JSON files using the 'pnpm generate' command.
```sh
pnpm generate
```
--------------------------------
### Access themes via unpkg CDN
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Use these URLs to fetch theme JSON files directly from the unpkg CDN.
```javascript
// Latest version
https://unpkg.com/monaco-themes/themes/Monokai.json
// Specific version
https://unpkg.com/monaco-themes@0.4.8/themes/Monokai.json
```
--------------------------------
### Theme Generation Pipeline
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Commands to fetch upstream TextMate themes and convert them into the required Monaco JSON format.
```bash
# Download TextMate theme files from upstream sources
pnpm download
# Convert downloaded .tmTheme files to Monaco JSON format
pnpm generate
```
--------------------------------
### Implement basic file upload for themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Uses the FileReader API to read a file input and apply the parsed theme to the Monaco editor.
```typescript
function setupFileUpload() {
const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
fileInput.addEventListener('change', async (event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
// Read the file content
const content = await file.text();
// Parse the TextMate theme
const monacoTheme = parseTmTheme(content);
// Register and apply
const themeName = file.name.replace(/\..*$/, '');
monaco.editor.defineTheme(themeName, monacoTheme);
monaco.editor.setTheme(themeName);
});
}
setupFileUpload();
```
--------------------------------
### Fetch Theme List
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Asynchronous function to retrieve and parse the theme list from the package directory.
```typescript
async function getThemeList() {
const response = await fetch('node_modules/monaco-themes/themes/themelist.json');
const map = await response.json();
return Object.keys(map); // Array of normalized names
}
const themes = await getThemeList();
// ['monokai', 'dracula', 'solarized-dark', ...]
```
--------------------------------
### Fetch themes from the file system
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
Load theme JSON files via network requests, useful for environments where files are served statically.
```typescript
async function loadTheme(name) {
const response = await fetch(`/node_modules/monaco-themes/themes/${name}.json`);
const theme = await response.json();
return theme;
}
const monakoiTheme = await loadTheme('Monokai');
monaco.editor.defineTheme('monokai', monakoiTheme);
```
--------------------------------
### Token Rule Expansion
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Demonstrates how comma-separated TextMate token scopes are expanded into individual rules for the Monaco Editor.
```typescript
scope: "string, constant.string, meta.string"
// Results in 3 separate rules in the output
```
--------------------------------
### Parse TextMate theme with CommonJS
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/parse-tm-theme.md
Use this approach in Node.js environments to read a theme file from the filesystem and convert it.
```javascript
const { parseTmTheme } = require('monaco-themes');
const themeString = fs.readFileSync('path/to/theme.tmTheme', 'utf8');
const monacoTheme = parseTmTheme(themeString);
monaco.editor.defineTheme('my-theme', monacoTheme);
```
--------------------------------
### Project Documentation Structure
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/INDEX.md
Visual representation of the project's documentation file hierarchy.
```text
/output
├── INDEX.md ← You are here
├── OVERVIEW.md ← Project overview
├── FEATURE_GUIDE.md ← 10 key features explained
├── ARCHITECTURE.md ← Design & internals
├── IMPORT_PATTERNS.md ← 10 import/usage patterns
├── THEMES_MANIFEST.md ← 40 themes catalog
├── types.md ← MonacoTheme type definition
├── configuration.md ← Build & runtime setup
└── api-reference/
├── parse-tm-theme.md ← Main API function
├── color-parsing.md ← Color utilities
├── color-mapping.md ← Color key mappings
└── internal-interfaces.md ← Internal types
```
--------------------------------
### TextMate Theme XML Structure
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
The expected XML plist format for input theme files.
```xml
nameMonokaisettingssettingsbackground#272822foreground#f8f8f2caret#f8f8f0nameCommentscopecommentsettingsforeground#75715efontStyleitalic
```
--------------------------------
### Load User-Provided Themes via File Upload
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Allows users to upload TextMate theme files which are then parsed and applied at runtime.
```typescript
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
const content = await file.text();
const theme = parseTmTheme(content);
monaco.editor.defineTheme('uploaded', theme);
monaco.editor.setTheme('uploaded');
});
```
--------------------------------
### Register and Apply Monaco Editor Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Use parseTmTheme to convert content and define the theme globally or per editor instance.
```typescript
import { parseTmTheme } from 'monaco-themes';
const customTheme = parseTmTheme(themeContent);
// Register the theme
monaco.editor.defineTheme('custom-name', customTheme);
// Apply the theme to an editor
monaco.editor.create(domElement, {
theme: 'custom-name',
// other editor options...
});
// Or switch the global theme
monaco.editor.setTheme('custom-name');
```
--------------------------------
### Map theme names to filenames
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
The themelist.json file maps normalized theme names to their corresponding JSON filenames.
```json
{
"active-4d": "Active4D",
"all-hallows-eve": "All Hallows Eve",
"monokai": "Monokai",
...
}
```
--------------------------------
### Implement complete theme uploader class
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Encapsulates theme upload logic within a class, including file validation and error handling.
```typescript
import { parseTmTheme, MonacoTheme } from 'monaco-themes';
class ThemeUploader {
private editor: any; // Monaco editor instance
private uploadInput: HTMLInputElement;
constructor(editor: any) {
this.editor = editor;
this.uploadInput = document.createElement('input');
this.uploadInput.type = 'file';
this.uploadInput.accept = '.tmTheme, .tmTheme.xml';
this.setupListener();
}
private setupListener() {
this.uploadInput.addEventListener('change', this.handleFileUpload.bind(this));
}
private async handleFileUpload(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
try {
const content = await file.text();
const themeName = file.name
.replace(/\.(tmTheme|xml)$/, '')
.replace(/[^a-zA-Z0-9-_]/g, '-')
.toLowerCase();
const monacoTheme = parseTmTheme(content);
this.editor.defineTheme(themeName, monacoTheme);
this.editor.setTheme(themeName);
console.log(`Theme "${themeName}" loaded successfully`);
} catch (error) {
console.error('Failed to load theme:', error);
alert('Failed to load theme. Check the console for details.');
}
}
public openDialog() {
this.uploadInput.click();
}
}
// Usage
const uploader = new ThemeUploader(monaco.editor);
document.getElementById('upload-btn')?.addEventListener('click', () => {
uploader.openDialog();
});
```
--------------------------------
### Pre-register Built-in Themes in TypeScript
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Use this pattern for applications requiring a theme selection UI. It registers multiple themes asynchronously on startup for instant switching.
```typescript
const builtInThemes = [
'Monokai', 'Dracula', 'Solarized-dark', 'Solarized-light',
'GitHub', 'GitHub Dark', 'Nord', 'Oceanic Next', 'Tomorrow-Night',
];
async function registerAllThemes() {
const promises = builtInThemes.map(async (name) => {
const module = await import(`monaco-themes/themes/${name}.json`);
const theme = module.default || module;
monaco.editor.defineTheme(name.toLowerCase(), theme);
});
await Promise.all(promises);
}
// Register once on app startup
await registerAllThemes();
// Later: switching is instant
document.querySelector('#theme-select')?.addEventListener('change', (e) => {
const themeName = (e.target as HTMLSelectElement).value.toLowerCase();
monaco.editor.setTheme(themeName);
});
```
--------------------------------
### Package Export Configuration
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Defines the library's entry points for CommonJS and ESM, as well as direct access to theme JSON files.
```json
{
"exports": {
".": {
"require": "./dist/index.cjs", // CommonJS
"import": "./dist/index.js" // ESM (default)
},
"./themes/*": "./themes/*.json" // Direct theme files
}
}
```
--------------------------------
### Theme Directory Structure
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Representation of the pre-built theme files available in the library.
```text
themes/
├── Monokai.json
├── Dracula.json
├── Solarized-dark.json
├── Solarized-light.json
├── ... (38 more themes)
└── themelist.json (name→filename mapping)
```
--------------------------------
### Load Theme Directly using Modern Bundlers
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Import a theme JSON file directly using modern bundlers like Vite or Webpack and apply it.
```js
const monaco =
/* import monaco */
import('monaco-themes/themes/Monokai.json').then((data) => {
monaco.editor.defineTheme('monokai', data.default || data);
monaco.editor.setTheme('monokai');
});
```
--------------------------------
### Load Themes via Dynamic Import
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Use for lazy loading themes to reduce initial bundle size.
```typescript
const themeName = 'Dracula';
import(`monaco-themes/themes/${themeName}.json`).then(module => {
const theme = module.default || module;
monaco.editor.defineTheme(themeName.toLowerCase(), theme);
});
```
--------------------------------
### Access theme files
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Retrieve theme JSON files either through a module bundler or via network fetch.
```typescript
// Via bundler
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
// Via fetch
fetch('node_modules/monaco-themes/themes/Monokai.json')
.then(r => r.json())
```
--------------------------------
### Integrate Theme with Monaco Editor
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/types.md
Methods to register and apply the theme within the Monaco Editor instance.
```typescript
// Define the theme
monaco.editor.defineTheme('my-theme', monacoTheme);
// Set it as the active theme
monaco.editor.setTheme('my-theme');
// Create an editor with the theme
const editor = monaco.editor.create(domElement, {
theme: 'my-theme',
});
```
--------------------------------
### Load Themes via Fetch API
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/configuration.md
Useful for runtime theme selection from a remote server.
```typescript
async function loadTheme(themeName) {
const response = await fetch(`/themes/${themeName}.json`);
const theme = await response.json();
monaco.editor.defineTheme(themeName.toLowerCase(), theme);
}
loadTheme('Monokai');
```
--------------------------------
### Parse TextMate theme from browser file input
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/parse-tm-theme.md
Use this approach to allow users to upload and apply custom theme files directly in the browser.
```typescript
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
const content = await file.text();
const monacoTheme = parseTmTheme(content);
monaco.editor.defineTheme('uploaded-theme', monacoTheme);
monaco.editor.setTheme('uploaded-theme');
});
```
--------------------------------
### Parse and Apply Theme using ESM
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Use ESM to import the parseTmTheme function, parse a theme string, and apply it to monaco-editor.
```js
import { parseTmTheme } from 'monaco-themes';
const tmThemeString = /* read using FileReader */
const themeData = parseTmTheme(tmThemeString);
monaco.editor.defineTheme('mytheme', themeData);
monaco.editor.setTheme('mytheme');
```
--------------------------------
### Reference Tracking in Theme Processing
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/ARCHITECTURE.md
Demonstrates the lifecycle of temporary objects during the theme parsing process to ensure proper dereferencing.
```typescript
// Temporary objects dereferenced after use
const rawData = plist.parse(...) // Created by plist lib
const globalSettings = rawData.settings[0]?.settings || {} // Reference to nested object
// Processing loop creates temporary objects
rawData.settings.forEach((setting) => {
const rule: Partial<...> = {} // Created, populated, pushed
rules.push(rule) // Reference moved to output array
}) // rule object dereferenced at loop end
// Final object
const result = { base, inherit, rules, colors }
// Returned to caller; caller responsible for lifecycle
```
--------------------------------
### Define Gutter Settings Interface
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Infrastructure for gutter-specific color mappings in the theme settings.
```typescript
interface RawThemeSettings {
settings: Array<...>;
gutterSettings?: Record;
}
const GUTTER_COLOR_MAP: ColorMapping[] = [];
```
--------------------------------
### Use TypeScript Declarations
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Enables full type support for theme parsing.
```typescript
// Full type support
import type { MonacoTheme } from 'monaco-themes';
const theme: MonacoTheme = parseTmTheme(content);
```
--------------------------------
### Parse and Apply Theme using Script Tag (UMD)
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Include the UMD script and use the global MonacoThemes object to parse and apply a theme.
```html
```
--------------------------------
### Import Themes via CommonJS
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Usage for Node.js scripts and legacy bundlers.
```javascript
const { parseTmTheme } = require('monaco-themes');
const monakoiTheme = require('monaco-themes/themes/Monokai.json');
```
--------------------------------
### Access themes via jsDelivr CDN
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Use these URLs to fetch theme JSON files directly from the jsDelivr CDN.
```javascript
https://cdn.jsdelivr.net/npm/monaco-themes@latest/themes/Monokai.json
https://cdn.jsdelivr.net/npm/monaco-themes@0.4.8/themes/Monokai.json
```
--------------------------------
### Manage Themes with TypeScript
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Provides a type-safe registry for loading, parsing, and applying themes dynamically. Suitable for applications requiring runtime theme switching.
```typescript
import type { MonacoTheme } from 'monaco-themes';
import { parseTmTheme } from 'monaco-themes';
interface ThemeRegistry {
[themeName: string]: MonacoTheme;
}
class ThemeManager {
private registry: ThemeRegistry = {};
registerTheme(name: string, theme: MonacoTheme): void {
this.registry[name] = theme;
}
getTheme(name: string): MonacoTheme | undefined {
return this.registry[name];
}
async loadFromFile(name: string, filePath: string): Promise {
const response = await fetch(filePath);
const theme: MonacoTheme = await response.json();
this.registerTheme(name, theme);
}
async parseFromContent(name: string, content: string): Promise {
const theme = parseTmTheme(content);
this.registerTheme(name, theme);
}
applyTheme(name: string): void {
const theme = this.getTheme(name);
if (!theme) {
throw new Error(`Theme not found: ${name}`);
}
monaco.editor.defineTheme(name, theme);
monaco.editor.setTheme(name);
}
}
// Usage
const manager = new ThemeManager();
await manager.loadFromFile('monokai', '/themes/Monokai.json');
manager.applyTheme('monokai');
```
--------------------------------
### Access parsed theme data
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/internal-interfaces.md
Demonstrates how to access global settings and iterate through token rules after parsing a theme file.
```typescript
const rawData = plist.parse(rawTmThemeString) as RawThemeSettings;
// Access global settings
const globalSettings = rawData.settings[0]?.settings || {};
console.log(globalSettings.background); // e.g., "#272822"
// Process token rules
rawData.settings.forEach(setting => {
if (setting.scope && setting.settings) {
// Process individual token scope rule
}
});
```
--------------------------------
### Theme Catalog Loader
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Iteratively load and register multiple themes from a base URL.
```typescript
async function initializeThemeCatalog(themeNames: string[]) {
const baseUrl = 'https://unpkg.com/monaco-themes/themes';
for (const name of themeNames) {
try {
const response = await fetch(`${baseUrl}/${name}.json`);
const theme = await response.json();
monaco.editor.defineTheme(name.toLowerCase(), theme);
console.log(`✓ Loaded theme: ${name}`);
} catch (error) {
console.error(`✗ Failed to load theme: ${name}`, error);
}
}
}
await initializeThemeCatalog(['Monokai', 'Dracula', 'GitHub', 'Nord']);
```
--------------------------------
### Parse and Apply TextMate Themes
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/OVERVIEW.md
Convert a raw TextMate theme string into a Monaco-compatible theme object and register it with the editor.
```typescript
import { parseTmTheme } from 'monaco-themes';
// Read a TextMate theme file (from disk, FileReader, or fetch)
const tmThemeContent = await readThemeFile();
// Parse it to Monaco format
const monacoTheme = parseTmTheme(tmThemeContent);
// Register and apply with Monaco Editor
monaco.editor.defineTheme('my-theme', monacoTheme);
monaco.editor.setTheme('my-theme');
```
--------------------------------
### Process TextMate Files in Node.js
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Use this pattern for build scripts, CLI tools, or automated theme generation. It reads .tmTheme files from a directory and converts them to Monaco-compatible JSON.
```typescript
import fs from 'fs';
import path from 'path';
import { parseTmTheme, MonacoTheme } from 'monaco-themes';
function processThemeDirectory(inputDir: string, outputDir: string) {
const files = fs.readdirSync(inputDir).filter(f => f.endsWith('.tmTheme'));
const results: Record = {};
files.forEach((filename) => {
const themeName = filename.replace('.tmTheme', '');
const inputPath = path.join(inputDir, filename);
const outputPath = path.join(outputDir, `${themeName}.json`);
try {
const content = fs.readFileSync(inputPath, 'utf8');
const monacoTheme = parseTmTheme(content);
fs.writeFileSync(outputPath, JSON.stringify(monacoTheme, null, 2));
results[themeName] = 'success';
console.log(`✓ ${themeName}`);
} catch (error) {
results[themeName] = 'failed';
console.error(`✗ ${themeName}:`, error);
}
});
return results;
}
// Run the script
const results = processThemeDirectory('./input-themes', './output-themes');
console.log(`\nProcessed ${Object.keys(results).length} themes`);
```
--------------------------------
### Load Themes via Browser IIFE/UMD
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Usage for direct HTML script tags without a bundler.
```html
```
--------------------------------
### Import themes dynamically
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/THEMES_MANIFEST.md
Use dynamic imports to load theme files at runtime based on a variable name.
```typescript
const themeName = 'Dracula';
const themeModule = await import(
`monaco-themes/themes/${themeName}.json`
);
const theme = themeModule.default || themeModule;
monaco.editor.defineTheme(themeName.toLowerCase(), theme);
```
--------------------------------
### Performance Complexity Metrics
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/ARCHITECTURE.md
Time complexity analysis for the theme parsing pipeline, showing typical execution times for each stage.
```text
Operation Complexity Typical Time
─────────────────────────────────────────────────────
plist.parse() O(n) 1-2ms
Extract global settings O(1) < 0.1ms
Process token rules O(m) 1-2ms (m = rule count)
Color parsing per color O(1) 0.1ms each
Base theme detection O(1) 0.1ms
Output construction O(1) < 0.1ms
─────────────────────────────────────────────────────
TOTAL O(n + m) < 5ms typical
```
--------------------------------
### ESM Import Patterns
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/IMPORT_PATTERNS.md
Standard import syntax for the parsing function, pre-built themes, and type definitions in modern bundlers.
```typescript
// Import the parsing function
import { parseTmTheme } from 'monaco-themes';
// Import a pre-built theme
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
// Type definitions are automatically available
import type { MonacoTheme } from 'monaco-themes';
```
--------------------------------
### Parse and Apply Theme using CommonJS
Source: https://github.com/brijeshb42/monaco-themes/blob/master/README.md
Use CommonJS to require the parseTmTheme function, parse a theme string, and apply it to monaco-editor.
```js
const { parseTmTheme } = require('monaco-themes');
const tmThemeString = /* read using FileReader */
const themeData = parseTmTheme(tmThemeString);
monaco.editor.defineTheme('mytheme', themeData);
monaco.editor.setTheme('mytheme');
```
--------------------------------
### Execute Mapping Lookup
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Logic to iterate through the color map and apply valid colors from global settings to the theme colors object.
```typescript
COLOR_MAP.forEach(({ tm, mn }) => {
if (tm in globalSettings) {
const color = parseColor(globalSettings[tm]);
if (color) {
colors[mn] = color;
}
}
});
```
--------------------------------
### parseTmTheme(rawTmThemeString: string): MonacoTheme
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/parse-tm-theme.md
Parses a TextMate theme file string and returns a Monaco Editor compatible theme object.
```APIDOC
## function parseTmTheme(rawTmThemeString: string): MonacoTheme
### Description
Parses a TextMate theme file (in XML plist format) and converts it to a Monaco Editor compatible theme definition. It automatically detects the base theme (vs or vs-dark) and maps token scopes and colors.
### Parameters
- **rawTmThemeString** (string) - Required - The complete contents of a TextMate theme file in XML plist format.
### Return Type
Returns a `MonacoTheme` object that conforms to the Monaco Editor `IStandaloneThemeData` interface.
### Usage Example
```typescript
import { parseTmTheme } from 'monaco-themes';
const themeContent = `...`;
const monacoTheme = parseTmTheme(themeContent);
monaco.editor.defineTheme('my-theme', monacoTheme);
monaco.editor.setTheme('my-theme');
```
```
--------------------------------
### Parse TextMate theme with ESM
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/parse-tm-theme.md
Use this approach in modern JavaScript environments to parse a raw XML string and apply it to the Monaco editor.
```typescript
import { parseTmTheme } from 'monaco-themes';
const themeContent = `
settingssettingsbackground#272822foreground#f8f8f2scopecommentsettingsforeground#75715e`;
const monacoTheme = parseTmTheme(themeContent);
// monacoTheme.base === 'vs-dark'
// monacoTheme.colors['editor.background'] === '#272822'
// monacoTheme.rules includes { token: 'comment', foreground: '75715e' }
monaco.editor.defineTheme('my-theme', monacoTheme);
monaco.editor.setTheme('my-theme');
```
--------------------------------
### Implement Gutter Color Mapping
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Future extension logic for applying gutter colors when supported by the editor.
```typescript
// Not yet implemented
if (gutterSettings) {
GUTTER_COLOR_MAP.forEach(({ tm, mn }) => {
if (tm in gutterSettings) {
const color = parseColor(gutterSettings[tm]);
if (color) {
colors[mn] = color;
}
}
});
}
```
--------------------------------
### Import Themes via ESM
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/FEATURE_GUIDE.md
Usage for modern bundlers like Vite, Webpack 5+, esbuild, and Parcel 2.
```typescript
import { parseTmTheme } from 'monaco-themes';
import monakoiTheme from 'monaco-themes/themes/Monokai.json';
```
--------------------------------
### Define RawThemeSettings interface
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/api-reference/internal-interfaces.md
The interface representing the structure of parsed TextMate plist data after deserialization.
```typescript
interface RawThemeSettings {
settings: Array<{
scope?: string | string[];
settings?: {
foreground?: string;
background?: string;
fontStyle?: string;
};
}>;
gutterSettings?: Record;
}
```
--------------------------------
### Map Color Keys
Source: https://github.com/brijeshb42/monaco-themes/blob/master/_autodocs/ARCHITECTURE.md
Translates TextMate color keys to Monaco-compatible keys using a predefined mapping.
```typescript
const globalColors: Record = {};
COLOR_MAP.forEach((obj) => {
if (globalSettings[obj.tm as keyof typeof globalSettings]) {
const color = parseColor(globalSettings[obj.tm] as string);
if (color) {
globalColors[obj.mn] = color;
}
}
});
// Handle ANSI colors (already added to COLOR_MAP)
// Handle gutter colors (GUTTER_COLOR_MAP currently empty)
```
```json
{
'editor.foreground': '#f8f8f2',
'editor.background': '#272822',
'editorCursor.foreground': '#f8f8f0',
'terminal.ansiRed': '#f92672',
'terminal.ansiGreen': '#a6e22e',
...
}
```