repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/spellchecker/index.js | src/main/spellchecker/index.js | import { ipcMain, BrowserWindow } from 'electron'
import log from 'electron-log'
import { isOsx } from '../config'
/**
* Add the given word to the spellchecker dictionary.
*
* @param {BrowserWindow} win The browser window.
* @param {string} word The word to add.
* @returns {boolean} Whether the word was added.
*/
export const addToDictionary = (win, word) => {
return win.webContents.session.addWordToSpellCheckerDictionary(word)
}
/**
* Remove the given word from the spellchecker dictionary.
*
* @param {BrowserWindow} win The browser window.
* @param {string} word The word to remove.
* @returns {boolean} Whether the word was removed.
*/
export const removeFromDictionary = (win, word) => {
return win.webContents.session.removeWordFromSpellCheckerDictionary(word)
}
/**
* Returns a list of all words in the custom dictionary.
*
* @param {BrowserWindow} win The browser window.
* @returns {Promise<string[]>} List of custom dictionary words.
*/
export const getCustomDictionaryWords = async win => {
return win.webContents.session.listWordsInSpellCheckerDictionary()
}
/**
* Sets whether to enable the builtin spell checker.
*
* @param {BrowserWindow} win The browser window.
* @param {boolean} enabled Whether to enable the builtin spell checker.
*/
export const setSpellCheckerEnabled = (win, enabled) => {
win.webContents.session.setSpellCheckerEnabled(enabled)
return win.webContents.session.isSpellCheckerEnabled() === enabled
}
/**
* Switch the spellchecker to the given language and enable the builtin spell checker.
*
* @param {BrowserWindow} win The browser window.
* @param {string} word The word to remove.
* @throws Throws an exception if the language cannot be set.
*/
export const switchLanguage = (win, lang) => {
win.webContents.session.setSpellCheckerLanguages([lang])
}
/**
*
* @param {BrowserWindow} win The browser window.
* @returns {string[]} List of available spellchecker languages or an empty array on macOS.
*/
export const getAvailableDictionaries = win => {
if (!win.webContents.session.isSpellCheckerEnabled) {
console.warn('Spell Checker not available but dictionaries requested.')
return []
} else if (isOsx) {
// NB: On macOS the OS spellchecker is used and will detect the language automatically.
return []
}
return win.webContents.session.availableSpellCheckerLanguages
}
export default () => {
ipcMain.handle('mt::spellchecker-remove-word', async (e, word) => {
const win = BrowserWindow.fromWebContents(e.sender)
return removeFromDictionary(win, word)
})
ipcMain.handle('mt::spellchecker-switch-language', async (e, lang) => {
const win = BrowserWindow.fromWebContents(e.sender)
switchLanguage(win, lang)
return null
})
ipcMain.handle('mt::spellchecker-get-available-dictionaries', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
return getAvailableDictionaries(win)
})
// NOTE: We have to set a language or call `switchLanguage` on Linux and Windows.
ipcMain.handle('mt::spellchecker-set-enabled', async (e, enabled) => {
const win = BrowserWindow.fromWebContents(e.sender)
if (!setSpellCheckerEnabled(win, enabled)) {
log.warn(`Failed to (de-)activate spell checking on editor (id=${win.id}).`)
return false
}
return true
})
ipcMain.handle('mt::spellchecker-get-custom-dictionary-words', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
return getCustomDictionaryWords(win)
})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/windows/editor.js | src/main/windows/editor.js | import path from 'path'
import { BrowserWindow, dialog, ipcMain } from 'electron'
import { enable as remoteEnable } from '@electron/remote/main'
import log from 'electron-log'
import windowStateKeeper from 'electron-window-state'
import { isChildOfDirectory, isSamePathSync } from 'common/filesystem/paths'
import BaseWindow, { WindowLifecycle, WindowType } from './base'
import { ensureWindowPosition, zoomIn, zoomOut } from './utils'
import { TITLE_BAR_HEIGHT, editorWinOptions, isLinux, isOsx } from '../config'
import { showEditorContextMenu } from '../contextMenu/editor'
import { loadMarkdownFile } from '../filesystem/markdown'
import { switchLanguage } from '../spellchecker'
class EditorWindow extends BaseWindow {
/**
* @param {Accessor} accessor The application accessor for application instances.
*/
constructor (accessor) {
super(accessor)
this.type = WindowType.EDITOR
// Root directory and file list to open when the window is ready.
this._directoryToOpen = null
this._filesToOpen = [] // {doc: IMarkdownDocumentRaw, options: any, selected: boolean}
this._markdownToOpen = [] // List of markdown strings or an empty string will open a new untitled tab
// Root directory and file list that are currently opened. These lists are
// used to find the best window to open new files in.
this._openedRootDirectory = ''
this._openedFiles = []
}
/**
* Creates a new editor window.
*
* @param {string} [rootDirectory] The root directory to open.
* @param {string[]} [fileList] A list of markdown files to open.
* @param {string[]} [markdownList] Array of markdown data to open.
* @param {*} [options] The BrowserWindow options.
*/
createWindow (rootDirectory = null, fileList = [], markdownList = [], options = {}) {
const { menu: appMenu, env, preferences } = this._accessor
const addBlankTab = !rootDirectory && fileList.length === 0 && markdownList.length === 0
const mainWindowState = windowStateKeeper({
defaultWidth: 1200,
defaultHeight: 800
})
const { x, y, width, height } = ensureWindowPosition(mainWindowState)
const winOptions = Object.assign({ x, y, width, height }, editorWinOptions, options)
if (isLinux) {
winOptions.icon = path.join(__static, 'logo-96px.png')
}
const {
titleBarStyle,
theme,
sideBarVisibility,
tabBarVisibility,
sourceCodeModeEnabled,
spellcheckerEnabled,
spellcheckerLanguage
} = preferences.getAll()
// Enable native or custom/frameless window and titlebar
if (!isOsx) {
winOptions.titleBarStyle = 'default'
if (titleBarStyle === 'native') {
winOptions.frame = true
}
}
winOptions.backgroundColor = this._getPreferredBackgroundColor(theme)
if (env.disableSpellcheck) {
winOptions.webPreferences.spellcheck = false
}
let win = this.browserWindow = new BrowserWindow(winOptions)
remoteEnable(win.webContents)
this.id = win.id
if (spellcheckerEnabled && !isOsx) {
try {
switchLanguage(win, spellcheckerLanguage)
} catch (error) {
log.error('Unable to set spell checker language on startup:', error)
}
}
// Create a menu for the current window
appMenu.addEditorMenu(win, { sourceCodeModeEnabled })
win.webContents.on('context-menu', (event, params) => {
showEditorContextMenu(win, event, params, preferences.getItem('spellcheckerEnabled'))
})
win.webContents.once('did-finish-load', () => {
this.lifecycle = WindowLifecycle.READY
this.emit('window-ready')
// Restore and focus window
this.bringToFront()
const lineEnding = preferences.getPreferredEol()
appMenu.updateLineEndingMenu(this.id, lineEnding)
win.webContents.send('mt::bootstrap-editor', {
addBlankTab,
markdownList: this._markdownToOpen,
lineEnding,
sideBarVisibility,
tabBarVisibility,
sourceCodeModeEnabled
})
this._doOpenFilesToOpen()
this._markdownToOpen.length = 0
// Listen on default system mouse zoom event (e.g. Ctrl+MouseWheel on Linux/Windows).
win.webContents.on('zoom-changed', (event, zoomDirection) => {
if (zoomDirection === 'in') {
zoomIn(win)
} else if (zoomDirection === 'out') {
zoomOut(win)
}
})
})
win.webContents.once('did-fail-load', (event, errorCode, errorDescription) => {
log.error(`The window failed to load or was cancelled: ${errorCode}; ${errorDescription}`)
})
win.webContents.once('render-process-gone', async (event, { reason }) => {
if (reason === 'clean-exit') {
return
}
const msg = `The renderer process has crashed unexpected or is killed (${reason}).`
log.error(msg)
if (reason === 'abnormal-exit') {
return
}
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Close', 'Reload', 'Keep It Open'],
message: 'MarkText has crashed',
detail: msg
})
if (win.id) {
switch (response) {
case 0:
return this.destroy()
case 1:
return this.reload()
}
}
})
win.on('focus', () => {
this.emit('window-focus')
win.webContents.send('mt::window-active-status', { status: true })
})
// Lost focus
win.on('blur', () => {
this.emit('window-blur')
win.webContents.send('mt::window-active-status', { status: false })
})
;['maximize', 'unmaximize', 'enter-full-screen', 'leave-full-screen'].forEach(channel => {
win.on(channel, () => {
win.webContents.send(`mt::window-${channel}`)
})
})
// Before closed. We cancel the action and ask the editor further instructions.
win.on('close', event => {
this.emit('window-close')
event.preventDefault()
win.webContents.send('mt::ask-for-close')
// TODO: Close all watchers etc. Should we do this manually or listen to 'quit' event?
})
// The window is now destroyed.
win.on('closed', () => {
this.lifecycle = WindowLifecycle.QUITTED
this.emit('window-closed')
// Free window reference
win = null
})
this.lifecycle = WindowLifecycle.LOADING
win.loadURL(this._buildUrlString(this.id, env, preferences))
win.setSheetOffset(TITLE_BAR_HEIGHT)
mainWindowState.manage(win)
// Disable application menu shortcuts because we want to handle key bindings ourself.
win.webContents.setIgnoreMenuShortcuts(true)
// Delay load files and directories after the current control flow.
setTimeout(() => {
if (rootDirectory) {
this.openFolder(rootDirectory)
}
if (fileList.length) {
this.openTabsFromPaths(fileList)
}
}, 0)
return win
}
/**
* Open a new tab from a markdown file.
*
* @param {string} filePath The markdown file path.
* @param {string} [options] The tab option for the editor window.
* @param {boolean} [selected] Whether the tab should become the selected tab (true if not set).
*/
openTab (filePath, options = {}, selected = true) {
// TODO: Don't allow new files if quitting.
if (this.lifecycle === WindowLifecycle.QUITTED) return
this.openTabs([{ filePath, options, selected }])
}
/**
* Open new tabs from the given file paths.
*
* @param {string[]} filePaths The file paths to open.
*/
openTabsFromPaths (filePaths) {
if (!filePaths || filePaths.length === 0) return
const fileList = filePaths.map(p => ({ filePath: p, options: {}, selected: false }))
fileList[0].selected = true
this.openTabs(fileList)
}
/**
* Open new tabs from markdown files with options for editor window.
*
* @param {{filePath: string, selected: boolean, options: any}[]} filePath A list of markdown file paths and options to open.
*/
openTabs (fileList) {
// TODO: Don't allow new files if quitting.
if (this.lifecycle === WindowLifecycle.QUITTED) return
const { browserWindow } = this
const { preferences } = this._accessor
const eol = preferences.getPreferredEol()
const { autoGuessEncoding, trimTrailingNewline } = preferences.getAll()
for (const { filePath, options, selected } of fileList) {
loadMarkdownFile(filePath, eol, autoGuessEncoding, trimTrailingNewline).then(rawDocument => {
if (this.lifecycle === WindowLifecycle.READY) {
this._doOpenTab(rawDocument, options, selected)
} else {
this._filesToOpen.push({ doc: rawDocument, options, selected })
}
}).catch(err => {
const { message, stack } = err
log.error(`[ERROR] Cannot open file or directory: ${message}\n\n${stack}`)
browserWindow.webContents.send('mt::show-notification', {
title: 'Cannot open tab',
type: 'error',
message: err.message
})
})
}
}
/**
* Open a new untitled tab optional with a markdown string.
*
* @param {[boolean]} selected Whether the tab should become the selected tab (true if not set).
* @param {[string]} markdown The markdown string.
*/
openUntitledTab (selected = true, markdown = '') {
// TODO: Don't allow new files if quitting.
if (this.lifecycle === WindowLifecycle.QUITTED) return
if (this.lifecycle === WindowLifecycle.READY) {
const { browserWindow } = this
browserWindow.webContents.send('mt::new-untitled-tab', selected, markdown)
} else {
this._markdownToOpen.push(markdown)
}
}
/**
* Open a (new) directory and replaces the old one.
*
* @param {string} pathname The directory path.
*/
openFolder (pathname) {
// TODO: Don't allow new files if quitting.
if (!pathname || this.lifecycle === WindowLifecycle.QUITTED ||
isSamePathSync(pathname, this._openedRootDirectory)) {
return
}
if (this.lifecycle === WindowLifecycle.READY) {
const { _accessor, browserWindow } = this
const { menu: appMenu } = _accessor
if (this._openedRootDirectory) {
ipcMain.emit('watcher-unwatch-directory', browserWindow, this._openedRootDirectory)
}
appMenu.addRecentlyUsedDocument(pathname)
this._openedRootDirectory = pathname
ipcMain.emit('watcher-watch-directory', browserWindow, pathname)
browserWindow.webContents.send('mt::open-directory', pathname)
} else {
this._directoryToOpen = pathname
}
}
/**
* Add a new path to the file list and watch the given path.
*
* @param {string} filePath The file path.
*/
addToOpenedFiles (filePath) {
const { _openedFiles, browserWindow } = this
_openedFiles.push(filePath)
ipcMain.emit('watcher-watch-file', browserWindow, filePath)
}
/**
* Change a path in the opened file list and update the watcher.
*
* @param {string} pathname
* @param {string} oldPathname
*/
changeOpenedFilePath (pathname, oldPathname) {
const { _openedFiles, browserWindow } = this
const index = _openedFiles.findIndex(p => p === oldPathname)
if (index === -1) {
// The old path was not found but add the new one.
_openedFiles.push(pathname)
} else {
_openedFiles[index] = pathname
}
ipcMain.emit('watcher-unwatch-file', browserWindow, oldPathname)
ipcMain.emit('watcher-watch-file', browserWindow, pathname)
}
/**
* Remove a path from the opened file list and stop watching the path.
*
* @param {string} pathname The full path.
*/
removeFromOpenedFiles (pathname) {
const { _openedFiles, browserWindow } = this
const index = _openedFiles.findIndex(p => p === pathname)
if (index !== -1) {
_openedFiles.splice(index, 1)
}
ipcMain.emit('watcher-unwatch-file', browserWindow, pathname)
}
/**
* Returns a score list for a given file list.
*
* @param {string[]} fileList The file list.
* @returns {number[]}
*/
getCandidateScores (fileList) {
const { _openedFiles, _openedRootDirectory, id } = this
const buf = []
for (const pathname of fileList) {
let score = 0
if (_openedFiles.some(p => p === pathname)) {
score = -1
} else {
if (isChildOfDirectory(_openedRootDirectory, pathname)) {
score += 5
}
for (const item of _openedFiles) {
if (isChildOfDirectory(path.dirname(item), pathname)) {
score += 1
}
}
}
buf.push({ id, score })
}
return buf
}
reload () {
const { id, browserWindow } = this
// Close watchers
ipcMain.emit('watcher-unwatch-all-by-id', id)
// Reset saved state
this._directoryToOpen = ''
this._filesToOpen = []
this._markdownToOpen = []
this._openedRootDirectory = ''
this._openedFiles = []
browserWindow.webContents.once('did-finish-load', () => {
this.lifecycle = WindowLifecycle.READY
const { preferences } = this._accessor
const { sideBarVisibility, tabBarVisibility, sourceCodeModeEnabled } = preferences.getAll()
const lineEnding = preferences.getPreferredEol()
browserWindow.webContents.send('mt::bootstrap-editor', {
addBlankTab: true,
markdownList: [],
lineEnding,
sideBarVisibility,
tabBarVisibility,
sourceCodeModeEnabled
})
})
this.lifecycle = WindowLifecycle.LOADING
super.reload()
}
destroy () {
super.destroy()
// Watchers are freed from WindowManager.
this._directoryToOpen = null
this._filesToOpen = null
this._markdownToOpen = null
this._openedRootDirectory = null
this._openedFiles = null
}
get openedRootDirectory () {
return this._openedRootDirectory
}
// --- private ---------------------------------
/**
* Open a new new tab from the markdown document.
*
* @param {IMarkdownDocumentRaw} rawDocument The markdown document.
* @param {any} options The tab option for the editor window.
* @param {boolean} selected Whether the tab should become the selected tab (true if not set).
*/
_doOpenTab (rawDocument, options, selected) {
const { _accessor, _openedFiles, browserWindow } = this
const { menu: appMenu } = _accessor
const { pathname } = rawDocument
// Listen for file changed.
ipcMain.emit('watcher-watch-file', browserWindow, pathname)
appMenu.addRecentlyUsedDocument(pathname)
_openedFiles.push(pathname)
browserWindow.webContents.send('mt::open-new-tab', rawDocument, options, selected)
}
_doOpenFilesToOpen () {
if (this.lifecycle !== WindowLifecycle.READY) {
throw new Error('Invalid state.')
}
if (this._directoryToOpen) {
this.openFolder(this._directoryToOpen)
}
this._directoryToOpen = null
for (const { doc, options, selected } of this._filesToOpen) {
this._doOpenTab(doc, options, selected)
}
this._filesToOpen.length = 0
}
}
export default EditorWindow
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/windows/base.js | src/main/windows/base.js | import EventEmitter from 'events'
import { isLinux } from '../config'
/**
* A MarkText window.
* @typedef {BaseWindow} IApplicationWindow
* @property {number | null} id Identifier (= browserWindow.id) or null during initialization.
* @property {Electron.BrowserWindow} browserWindow The browse window.
* @property {WindowLifecycle} lifecycle The window lifecycle state.
* @property {WindowType} type The window type.
*/
// Window type marktext support.
export const WindowType = {
BASE: 'base', // You shold never create a `BASE` window.
EDITOR: 'editor',
SETTINGS: 'settings'
}
export const WindowLifecycle = {
NONE: 0,
LOADING: 1,
READY: 2,
QUITTED: 3
}
class BaseWindow extends EventEmitter {
/**
* @param {Accessor} accessor The application accessor for application instances.
*/
constructor (accessor) {
super()
this._accessor = accessor
this.id = null
this.browserWindow = null
this.lifecycle = WindowLifecycle.NONE
this.type = WindowType.BASE
}
bringToFront () {
const { browserWindow: win } = this
if (win.isMinimized()) win.restore()
if (!win.isVisible()) win.show()
if (isLinux) {
win.focus()
} else {
win.moveTop()
}
}
reload () {
this.browserWindow.reload()
}
destroy () {
this.lifecycle = WindowLifecycle.QUITTED
this.emit('window-closed')
this.removeAllListeners()
if (this.browserWindow) {
this.browserWindow.destroy()
this.browserWindow = null
}
this.id = null
}
// --- private ---------------------------------
_buildUrlWithSettings (windowId, env, userPreference) {
// NOTE: Only send absolutely necessary values. Full settings are delay loaded.
const { type } = this
const { debug, paths } = env
const {
codeFontFamily,
codeFontSize,
hideScrollbar,
theme,
titleBarStyle
} = userPreference.getAll()
/* eslint-disable */
const baseUrl = process.env.NODE_ENV === 'development'
? 'http://localhost:9091'
: `file://${__dirname}/index.html`
/* eslint-enable */
const url = new URL(baseUrl)
url.searchParams.set('udp', paths.userDataPath)
url.searchParams.set('debug', debug ? '1' : '0')
url.searchParams.set('wid', windowId)
url.searchParams.set('type', type)
// Settings
url.searchParams.set('cff', codeFontFamily)
url.searchParams.set('cfs', codeFontSize)
url.searchParams.set('hsb', hideScrollbar ? '1' : '0')
url.searchParams.set('theme', theme)
url.searchParams.set('tbs', titleBarStyle)
return url
}
_buildUrlString (windowId, env, userPreference) {
return this._buildUrlWithSettings(windowId, env, userPreference).toString()
}
_getPreferredBackgroundColor (theme) {
// Hardcode the theme background color and show the window direct for the fastet window ready time.
// Later with custom themes we need the background color (e.g. from meta information) and wait
// that the window is loaded and then pass theme data to the renderer.
switch (theme) {
case 'dark':
return '#282828'
case 'material-dark':
return '#34393f'
case 'ulysses':
return '#f3f3f3'
case 'graphite':
return '#f7f7f7'
case 'one-dark':
return '#282c34'
case 'light':
default:
return '#ffffff'
}
}
}
export default BaseWindow
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/windows/setting.js | src/main/windows/setting.js | import path from 'path'
import { BrowserWindow, ipcMain } from 'electron'
import { enable as remoteEnable } from '@electron/remote/main'
import { electronLocalshortcut } from '@hfelix/electron-localshortcut'
import BaseWindow, { WindowLifecycle, WindowType } from './base'
import { centerWindowOptions } from './utils'
import { TITLE_BAR_HEIGHT, preferencesWinOptions, isLinux, isOsx } from '../config'
class SettingWindow extends BaseWindow {
/**
* @param {Accessor} accessor The application accessor for application instances.
*/
constructor (accessor) {
super(accessor)
this.type = WindowType.SETTINGS
}
/**
* Creates a new setting window.
*
* @param {*} [category] The settings category tab name.
*/
createWindow (category = null) {
const { menu: appMenu, env, keybindings, preferences } = this._accessor
const winOptions = Object.assign({}, preferencesWinOptions)
centerWindowOptions(winOptions)
if (isLinux) {
winOptions.icon = path.join(__static, 'logo-96px.png')
}
// WORKAROUND: Electron has issues with different DPI per monitor when
// setting a fixed window size.
winOptions.resizable = true
// Enable native or custom/frameless window and titlebar
const { titleBarStyle, theme } = preferences.getAll()
if (!isOsx) {
winOptions.titleBarStyle = 'default'
if (titleBarStyle === 'native') {
winOptions.frame = true
}
}
winOptions.backgroundColor = this._getPreferredBackgroundColor(theme)
let win = this.browserWindow = new BrowserWindow(winOptions)
remoteEnable(win.webContents)
this.id = win.id
// Create a menu for the current window
appMenu.addSettingMenu(win)
win.once('ready-to-show', () => {
this.lifecycle = WindowLifecycle.READY
this.emit('window-ready')
})
win.on('focus', () => {
this.emit('window-focus')
win.webContents.send('mt::window-active-status', { status: true })
})
// Lost focus
win.on('blur', () => {
this.emit('window-blur')
win.webContents.send('mt::window-active-status', { status: false })
})
win.on('close', event => {
this.emit('window-close')
event.preventDefault()
ipcMain.emit('window-close-by-id', win.id)
})
// The window is now destroyed.
win.on('closed', () => {
this.emit('window-closed')
// Free window reference
win = null
})
this.lifecycle = WindowLifecycle.LOADING
win.loadURL(this._buildUrlString(this.id, env, preferences, category))
win.setSheetOffset(TITLE_BAR_HEIGHT)
const devToolsAccelerator = keybindings.getAccelerator('view.toggle-dev-tools')
if (env.debug && devToolsAccelerator) {
electronLocalshortcut.register(win, devToolsAccelerator, () => {
win.webContents.toggleDevTools()
})
}
return win
}
_buildUrlString (windowId, env, userPreference, category) {
const url = this._buildUrlWithSettings(windowId, env, userPreference)
if (category) {
// Overwrite type to add category name
url.searchParams.set('type', `${WindowType.SETTINGS}/${category}`)
}
return url.toString()
}
}
export default SettingWindow
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/windows/utils.js | src/main/windows/utils.js | import { screen } from 'electron'
import { isLinux } from '../config'
export const zoomIn = win => {
const { webContents } = win
const zoom = webContents.getZoomFactor()
// WORKAROUND: We need to set zoom on the browser window due to Electron#16018.
webContents.send('mt::window-zoom', Math.min(2.0, zoom + 0.125))
}
export const zoomOut = win => {
const { webContents } = win
const zoom = webContents.getZoomFactor()
// WORKAROUND: We need to set zoom on the browser window due to Electron#16018.
webContents.send('mt::window-zoom', Math.max(0.5, zoom - 0.125))
}
export const centerWindowOptions = options => {
// "workArea" doesn't work on Linux
const { bounds, workArea } = screen.getDisplayNearestPoint(screen.getCursorScreenPoint())
const screenArea = isLinux ? bounds : workArea
const { width, height } = options
options.x = Math.ceil(screenArea.x + (screenArea.width - width) / 2)
options.y = Math.ceil(screenArea.y + (screenArea.height - height) / 2)
}
export const ensureWindowPosition = windowState => {
// "workArea" doesn't work on Linux
const { bounds, workArea } = screen.getPrimaryDisplay()
const screenArea = isLinux ? bounds : workArea
let { x, y, width, height } = windowState
let center = false
if (x === undefined || y === undefined) {
center = true
// First app start; check whether window size is larger than screen size
if (screenArea.width < width) width = screenArea.width
if (screenArea.height < height) height = screenArea.height
} else {
center = !screen.getAllDisplays().map(display =>
x >= display.bounds.x && x <= display.bounds.x + display.bounds.width &&
y >= display.bounds.y && y <= display.bounds.y + display.bounds.height)
.some(display => display)
}
if (center) {
x = Math.ceil(screenArea.x + (screenArea.width - width) / 2)
y = Math.ceil(screenArea.y + (screenArea.height - height) / 2)
}
return {
x,
y,
width,
height
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/preferences/index.js | src/main/preferences/index.js | import fs from 'fs'
import path from 'path'
import EventEmitter from 'events'
import Store from 'electron-store'
import { BrowserWindow, ipcMain, nativeTheme } from 'electron'
import log from 'electron-log'
import { isWindows } from '../config'
import { hasSameKeys } from '../utils'
import schema from './schema'
const PREFERENCES_FILE_NAME = 'preferences'
class Preference extends EventEmitter {
/**
* @param {AppPaths} userDataPath The path instance.
*
* NOTE: This throws an exception when validation fails.
*
*/
constructor (paths) {
// TODO: Preferences should not loaded if global.MARKTEXT_SAFE_MODE is set.
super()
const { preferencesPath } = paths
this.preferencesPath = preferencesPath
this.hasPreferencesFile = fs.existsSync(path.join(this.preferencesPath, `./${PREFERENCES_FILE_NAME}.json`))
this.store = new Store({
schema,
name: PREFERENCES_FILE_NAME
})
this.staticPath = path.join(__static, 'preference.json')
this.init()
}
init = () => {
let defaultSettings = null
try {
defaultSettings = JSON.parse(fs.readFileSync(this.staticPath, { encoding: 'utf8' }) || '{}')
// Set best theme on first application start.
if (nativeTheme.shouldUseDarkColors) {
defaultSettings.theme = 'dark'
}
} catch (err) {
log.error(err)
}
if (!defaultSettings) {
throw new Error('Can not load static preference.json file')
}
// I don't know why `this.store.size` is 3 when first load, so I just check file existed.
if (!this.hasPreferencesFile) {
this.store.set(defaultSettings)
} else {
// Because `this.getAll()` will return a plainObject, so we can not use `hasOwnProperty` method
// const plainObject = () => Object.create(null)
const userSetting = this.getAll()
// Update outdated settings
const requiresUpdate = !hasSameKeys(defaultSettings, userSetting)
const userSettingKeys = Object.keys(userSetting)
const defaultSettingKeys = Object.keys(defaultSettings)
if (requiresUpdate) {
// TODO(fxha): For performance reasons, we should try to replace 'electron-store' because
// it does multiple blocking I/O calls when changing entries. There is no transaction or
// async I/O available. The core reason we changed to it was JSON scheme validation.
// Remove outdated settings
for (const key of userSettingKeys) {
if (!defaultSettingKeys.includes(key)) {
delete userSetting[key]
this.store.delete(key)
}
}
// Add new setting options
let addedNewEntries = false
for (const key in defaultSettings) {
if (!userSettingKeys.includes(key)) {
addedNewEntries = true
userSetting[key] = defaultSettings[key]
}
}
if (addedNewEntries) {
this.store.set(userSetting)
}
}
}
this._listenForIpcMain()
}
getAll () {
return this.store.store
}
setItem (key, value) {
ipcMain.emit('broadcast-preferences-changed', { [key]: value })
return this.store.set(key, value)
}
getItem (key) {
return this.store.get(key)
}
/**
* Change multiple setting entries.
*
* @param {Object.<string, *>} settings A settings object or subset object with key/value entries.
*/
setItems (settings) {
if (!settings) {
log.error('Cannot change settings without entires: object is undefined or null.')
return
}
Object.keys(settings).forEach(key => {
this.setItem(key, settings[key])
})
}
getPreferredEol () {
const endOfLine = this.getItem('endOfLine')
if (endOfLine === 'lf') {
return 'lf'
}
return endOfLine === 'crlf' || isWindows ? 'crlf' : 'lf'
}
exportJSON () {
// todo
}
importJSON () {
// todo
}
_listenForIpcMain () {
ipcMain.on('mt::ask-for-user-preference', e => {
const win = BrowserWindow.fromWebContents(e.sender)
win.webContents.send('mt::user-preference', this.getAll())
})
ipcMain.on('mt::set-user-preference', (e, settings) => {
this.setItems(settings)
})
ipcMain.on('mt::cmd-toggle-autosave', e => {
this.setItem('autoSave', !!this.getItem('autoSave'))
})
ipcMain.on('set-user-preference', settings => {
this.setItems(settings)
})
}
}
export default Preference
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/cli/index.js | src/main/cli/index.js | import path from 'path'
import { app } from 'electron'
import os from 'os'
import { isDirectory } from 'common/filesystem'
import parseArgs from './parser'
import { getPath } from '../utils'
const write = s => process.stdout.write(s)
const writeLine = s => write(s + '\n')
const cli = () => {
let argv = process.argv.slice(1)
if (process.env.NODE_ENV === 'development') {
// Don't pass electron development arguments to MarkText and change user data path.
argv = ['--user-data-dir', path.join(getPath('appData'), 'marktext-dev')]
}
const args = parseArgs(argv, true)
if (args['--help']) {
write(`Usage: marktext [commands] [path ...]
Available commands:
--debug Enable debug mode
--safe Disable plugins and other user configuration
-n, --new-window Open a new window on second-instance
--user-data-dir Change the user data directory
--disable-gpu Disable GPU hardware acceleration
--disable-spellcheck Disable built-in spellchecker
-v, --verbose Be verbose
--version Print version information
-h, --help Print this help message
`)
process.exit(0)
}
if (args['--version']) {
writeLine(`MarkText: ${global.MARKTEXT_VERSION_STRING}`)
writeLine(`Node.js: ${process.versions.node}`)
writeLine(`Electron: ${process.versions.electron}`)
writeLine(`Chromium: ${process.versions.chrome}`)
writeLine(`OS: ${os.type()} ${os.arch()} ${os.release()}`)
process.exit(0)
}
// Check for portable mode and ensure the user data path is absolute. We assume
// that the path is writable if not this lead to an application crash.
if (!args['--user-data-dir']) {
const portablePath = path.join(app.getAppPath(), '..', '..', 'marktext-user-data')
if (isDirectory(portablePath)) {
args['--user-data-dir'] = portablePath
}
} else {
args['--user-data-dir'] = path.resolve(args['--user-data-dir'])
}
return args
}
export default cli
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/cli/parser.js | src/main/cli/parser.js | import arg from 'arg'
/**
* Parse the given arguments or the default program arguments.
*
* @param {string[]} argv Arguments if null the default program arguments are used.
* @param {boolean} permissive If set to false an exception is throw about unknown flags.
* @returns {arg.Result} Parsed arguments
*/
const parseArgs = (argv = null, permissive = true) => {
if (argv === null) {
argv = process.argv.slice(1)
}
const spec = {
'--debug': Boolean,
'--safe': Boolean,
'--new-window': Boolean,
'-n': '--new-window',
'--disable-gpu': Boolean,
'--disable-spellcheck': Boolean,
'--user-data-dir': String,
// Misc
'--help': Boolean,
'-h': '--help',
'--verbose': arg.COUNT,
'-v': '--verbose',
'--version': Boolean
}
return arg(spec, { argv, permissive })
}
export default parseArgs
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/index.js | src/main/menu/index.js | import fs from 'fs'
import path from 'path'
import { app, ipcMain, Menu } from 'electron'
import log from 'electron-log'
import { ensureDirSync, isDirectory2, isFile2 } from 'common/filesystem'
import { isLinux, isOsx, isWindows } from '../config'
import { updateSidebarMenu } from '../menu/actions/edit'
import { updateFormatMenu } from '../menu/actions/format'
import { updateSelectionMenus } from '../menu/actions/paragraph'
import { viewLayoutChanged } from '../menu/actions/view'
import configureMenu, { configSettingMenu } from '../menu/templates'
const RECENTLY_USED_DOCUMENTS_FILE_NAME = 'recently-used-documents.json'
const MAX_RECENTLY_USED_DOCUMENTS = 12
export const MenuType = {
DEFAULT: 0,
EDITOR: 1,
SETTINGS: 2
}
class AppMenu {
/**
* @param {Preference} preferences The preferences instances.
* @param {Keybindings} keybindings The keybindings instances.
* @param {string} userDataPath The user data path.
*/
constructor (preferences, keybindings, userDataPath) {
this._preferences = preferences
this._keybindings = keybindings
this._userDataPath = userDataPath
this.RECENTS_PATH = path.join(userDataPath, RECENTLY_USED_DOCUMENTS_FILE_NAME)
this.isOsxOrWindows = isOsx || isWindows
this.activeWindowId = -1
this.windowMenus = new Map()
this._listenForIpcMain()
}
/**
* Add the file or directory path to the recently used documents.
*
* @param {string} filePath The file or directory full path.
*/
addRecentlyUsedDocument (filePath) {
const { isOsxOrWindows, RECENTS_PATH } = this
if (isOsxOrWindows) app.addRecentDocument(filePath)
if (isOsx) return
const recentDocuments = this.getRecentlyUsedDocuments()
const index = recentDocuments.indexOf(filePath)
let needSave = index !== 0
if (index > 0) {
recentDocuments.splice(index, 1)
}
if (index !== 0) {
recentDocuments.unshift(filePath)
}
if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {
needSave = true
recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)
}
this.updateAppMenu(recentDocuments)
if (needSave) {
ensureDirSync(this._userDataPath)
const json = JSON.stringify(recentDocuments, null, 2)
fs.writeFileSync(RECENTS_PATH, json, 'utf-8')
}
}
/**
* Returns a list of all recently used documents and folders.
*
* @returns {string[]}
*/
getRecentlyUsedDocuments () {
const { RECENTS_PATH } = this
if (!isFile2(RECENTS_PATH)) {
return []
}
try {
const recentDocuments = JSON.parse(fs.readFileSync(RECENTS_PATH, 'utf-8'))
.filter(f => f && (isFile2(f) || isDirectory2(f)))
if (recentDocuments.length > MAX_RECENTLY_USED_DOCUMENTS) {
recentDocuments.splice(MAX_RECENTLY_USED_DOCUMENTS, recentDocuments.length - MAX_RECENTLY_USED_DOCUMENTS)
}
return recentDocuments
} catch (err) {
log.error('Error while read recently used documents:', err)
return []
}
}
/**
* Clear recently used documents.
*/
clearRecentlyUsedDocuments () {
const { isOsxOrWindows, RECENTS_PATH } = this
if (isOsxOrWindows) app.clearRecentDocuments()
if (isOsx) return
const recentDocuments = []
this.updateAppMenu(recentDocuments)
const json = JSON.stringify(recentDocuments, null, 2)
ensureDirSync(this._userDataPath)
fs.writeFileSync(RECENTS_PATH, json, 'utf-8')
}
/**
* Add a default menu to the given window.
*
* @param {number} windowId The window id.
*/
addDefaultMenu (windowId) {
const { windowMenus } = this
const menu = this._buildSettingMenu() // Setting menu is also the fallback menu.
windowMenus.set(windowId, menu)
}
/**
* Add the settings menu to the given window.
*
* @param {BrowserWindow} window The settings browser window.
*/
addSettingMenu (window) {
const { windowMenus } = this
const menu = this._buildSettingMenu()
windowMenus.set(window.id, menu)
}
/**
* Add the editor menu to the given window.
*
* @param {BrowserWindow} window The editor browser window.
* @param {[*]} options The menu options.
*/
addEditorMenu (window, options = {}) {
const isSourceMode = !!options.sourceCodeModeEnabled
const { windowMenus } = this
windowMenus.set(window.id, this._buildEditorMenu())
const { menu } = windowMenus.get(window.id)
// Set source-code editor if preferred.
const sourceCodeModeMenuItem = menu.getMenuItemById('sourceCodeModeMenuItem')
sourceCodeModeMenuItem.checked = isSourceMode
if (isSourceMode) {
const typewriterModeMenuItem = menu.getMenuItemById('typewriterModeMenuItem')
const focusModeMenuItem = menu.getMenuItemById('focusModeMenuItem')
typewriterModeMenuItem.enabled = false
focusModeMenuItem.enabled = false
}
const { _keybindings } = this
_keybindings.registerEditorKeyHandlers(window)
if (isWindows) {
// WORKAROUND: Window close event isn't triggered on Windows if `setIgnoreMenuShortcuts(true)` is used (Electron#32674).
// NB: Remove this immediately if upstream is fixed because the event may be emitted twice.
_keybindings.registerAccelerator(window, 'Alt+F4', win => {
if (win && !win.isDestroyed()) {
win.close()
}
})
}
}
/**
* Remove menu from the given window.
*
* @param {number} windowId The window id.
*/
removeWindowMenu (windowId) {
// NOTE: Shortcut handler is automatically unregistered when window is closed.
const { activeWindowId } = this
this.windowMenus.delete(windowId)
if (activeWindowId === windowId) {
this.activeWindowId = -1
}
}
/**
* Returns the window menu.
*
* @param {number} windowId The window id.
* @returns {Electron.Menu} The menu.
*/
getWindowMenuById (windowId) {
const menu = this.windowMenus.get(windowId)
if (!menu) {
log.error(`getWindowMenuById: Cannot find window menu for window id ${windowId}.`)
throw new Error(`Cannot find window menu for id ${windowId}.`)
}
return menu.menu
}
/**
* Check whether the given window has a menu.
*
* @param {number} windowId The window id.
*/
has (windowId) {
return this.windowMenus.has(windowId)
}
/**
* Set the given window as last active.
*
* @param {number} windowId The window id.
*/
setActiveWindow (windowId) {
if (this.activeWindowId !== windowId) {
// Change application menu to the current window menu.
this._setApplicationMenu(this.getWindowMenuById(windowId))
this.activeWindowId = windowId
}
}
/**
* Updates all window menus.
*
* NOTE: We need this method to add or remove menu items at runtime.
*
* @param {[string[]]} recentUsedDocuments
*/
updateAppMenu (recentUsedDocuments) {
if (!recentUsedDocuments) {
recentUsedDocuments = this.getRecentlyUsedDocuments()
}
// "we don't support changing menu object after calling setMenu, the behavior
// is undefined if user does that." That mean we have to recreate the editor
// application menu each time.
// rebuild all window menus
this.windowMenus.forEach((value, key) => {
const { menu: oldMenu, type } = value
if (type !== MenuType.EDITOR) return
const { menu: newMenu } = this._buildEditorMenu(recentUsedDocuments)
// all other menu items are set automatically
updateMenuItem(oldMenu, newMenu, 'sourceCodeModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'typewriterModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'focusModeMenuItem')
updateMenuItem(oldMenu, newMenu, 'sideBarMenuItem')
updateMenuItem(oldMenu, newMenu, 'tabBarMenuItem')
// update window menu
value.menu = newMenu
// update application menu if necessary
const { activeWindowId } = this
if (activeWindowId === key) {
this._setApplicationMenu(newMenu)
}
})
}
/**
* Update line ending menu items.
*
* @param {number} windowId The window id.
* @param {string} lineEnding Either >lf< or >crlf<.
*/
updateLineEndingMenu (windowId, lineEnding) {
const menus = this.getWindowMenuById(windowId)
const crlfMenu = menus.getMenuItemById('crlfLineEndingMenuEntry')
const lfMenu = menus.getMenuItemById('lfLineEndingMenuEntry')
if (lineEnding === 'crlf') {
crlfMenu.checked = true
} else {
lfMenu.checked = true
}
}
/**
* Update always on top menu item.
*
* @param {number} windowId The window id.
* @param {boolean} lineEnding Always on top.
*/
updateAlwaysOnTopMenu (windowId, flag) {
const menus = this.getWindowMenuById(windowId)
const menu = menus.getMenuItemById('alwaysOnTopMenuItem')
menu.checked = flag
}
/**
* Update all theme entries from editor menus to the selected one.
*/
updateThemeMenu = theme => {
this.windowMenus.forEach(value => {
const { menu, type } = value
if (type !== MenuType.EDITOR) {
return
}
const themeMenus = menu.getMenuItemById('themeMenu')
if (!themeMenus) {
return
}
themeMenus.submenu.items.forEach(item => (item.checked = false))
themeMenus.submenu.items
.forEach(item => {
if (item.id && item.id === theme) {
item.checked = true
}
})
})
}
/**
* Update all auto save entries from editor menus to the given state.
*/
updateAutoSaveMenu = autoSave => {
this.windowMenus.forEach(value => {
const { menu, type } = value
if (type !== MenuType.EDITOR) {
return
}
const autoSaveMenu = menu.getMenuItemById('autoSaveMenuItem')
if (!autoSaveMenu) {
return
}
autoSaveMenu.checked = autoSave
})
}
_buildEditorMenu (recentUsedDocuments = null) {
if (!recentUsedDocuments) {
recentUsedDocuments = this.getRecentlyUsedDocuments()
}
const menuTemplate = configureMenu(this._keybindings, this._preferences, recentUsedDocuments)
const menu = Menu.buildFromTemplate(menuTemplate)
return { menu, type: MenuType.EDITOR }
}
_buildSettingMenu () {
if (isOsx) {
const menuTemplate = configSettingMenu(this._keybindings)
const menu = Menu.buildFromTemplate(menuTemplate)
return { menu, type: MenuType.SETTINGS }
}
return { menu: null, type: MenuType.SETTINGS }
}
_setApplicationMenu (menu) {
if (isLinux && !menu) {
// WORKAROUND for Electron#16521: We cannot hide the (application) menu on Linux.
const dummyMenu = Menu.buildFromTemplate([])
Menu.setApplicationMenu(dummyMenu)
} else {
Menu.setApplicationMenu(menu)
}
}
_listenForIpcMain () {
ipcMain.on('mt::add-recently-used-document', (e, pathname) => {
this.addRecentlyUsedDocument(pathname)
})
ipcMain.on('mt::update-line-ending-menu', (e, windowId, lineEnding) => {
this.updateLineEndingMenu(windowId, lineEnding)
})
ipcMain.on('mt::update-format-menu', (e, windowId, formats) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateFormatMenu(this.getWindowMenuById(windowId), formats)
})
ipcMain.on('mt::update-sidebar-menu', (e, windowId, value) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateSidebarMenu(this.getWindowMenuById(windowId), value)
})
ipcMain.on('mt::view-layout-changed', (e, windowId, viewSettings) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
viewLayoutChanged(this.getWindowMenuById(windowId), viewSettings)
})
ipcMain.on('mt::editor-selection-changed', (e, windowId, changes) => {
if (!this.has(windowId)) {
log.error(`UpdateApplicationMenu: Cannot find window menu for window id ${windowId}.`)
return
}
updateSelectionMenus(this.getWindowMenuById(windowId), changes)
})
ipcMain.on('menu-add-recently-used', pathname => {
this.addRecentlyUsedDocument(pathname)
})
ipcMain.on('menu-clear-recently-used', () => {
this.clearRecentlyUsedDocuments()
})
ipcMain.on('broadcast-preferences-changed', prefs => {
if (prefs.theme !== undefined) {
this.updateThemeMenu(prefs.theme)
}
if (prefs.autoSave !== undefined) {
this.updateAutoSaveMenu(prefs.autoSave)
}
})
}
}
const updateMenuItem = (oldMenus, newMenus, id) => {
const oldItem = oldMenus.getMenuItemById(id)
const newItem = newMenus.getMenuItemById(id)
newItem.checked = oldItem.checked
}
// ----------------------------------------------
// HACKY: We have one application menu per window and switch the menu when
// switching windows, so we can access and change the menu items via Electron.
/**
* Return the menu from the application menu.
*
* @param {string} menuId Menu ID
* @returns {Electron.Menu} Returns the menu or null.
*/
export const getMenuItemById = menuId => {
const menus = Menu.getApplicationMenu()
return menus.getMenuItemById(menuId)
}
export default AppMenu
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/edit.js | src/main/menu/actions/edit.js | import path from 'path'
import { ipcMain, BrowserWindow } from 'electron'
import log from 'electron-log'
import { COMMANDS } from '../../commands'
import { searchFilesAndDir } from '../../utils/imagePathAutoComplement'
// TODO(Refactor): Move to filesystem and provide generic API to search files in directories.
ipcMain.on('mt::ask-for-image-auto-path', (e, { pathname, src, id }) => {
const win = BrowserWindow.fromWebContents(e.sender)
if (!src || typeof src !== 'string') {
win.webContents.send(`mt::response-of-image-path-${id}`, [])
return
}
if (src.endsWith('/') || src.endsWith('\\') || src.endsWith('.')) {
return win.webContents.send(`mt::response-of-image-path-${id}`, [])
}
const fullPath = path.isAbsolute(src) ? src : path.join(path.dirname(pathname), src)
const dir = path.dirname(fullPath)
const searchKey = path.basename(fullPath)
searchFilesAndDir(dir, searchKey)
.then(files => {
return win.webContents.send(`mt::response-of-image-path-${id}`, files)
})
.catch(err => {
log.error(err)
return win.webContents.send(`mt::response-of-image-path-${id}`, [])
})
})
// --- Menu actions -------------------------------------------------------------
export const editorUndo = win => {
edit(win, 'undo')
}
export const editorRedo = win => {
edit(win, 'redo')
}
export const editorCopyAsMarkdown = win => {
edit(win, 'copyAsMarkdown')
}
export const editorCopyAsHtml = win => {
edit(win, 'copyAsHtml')
}
export const editorPasteAsPlainText = win => {
edit(win, 'pasteAsPlainText')
}
export const editorSelectAll = win => {
edit(win, 'selectAll')
}
export const editorDuplicate = win => {
edit(win, 'duplicate')
}
export const editorCreateParagraph = win => {
edit(win, 'createParagraph')
}
export const editorDeleteParagraph = win => {
edit(win, 'deleteParagraph')
}
export const editorFind = win => {
edit(win, 'find')
}
export const editorFindNext = win => {
edit(win, 'findNext')
}
export const editorFindPrevious = win => {
edit(win, 'findPrev')
}
export const editorReplace = win => {
edit(win, 'undo')
}
export const findInFolder = win => {
edit(win, 'findInFolder')
}
export const edit = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::editor-edit-action', type)
}
}
export const nativeCut = win => {
if (win) {
win.webContents.cut()
}
}
export const nativeCopy = win => {
if (win) {
win.webContents.copy()
}
}
export const nativePaste = win => {
if (win) {
win.webContents.paste()
}
}
export const screenshot = win => {
ipcMain.emit('screen-capture', win)
}
export const lineEnding = (win, lineEnding) => {
if (win && win.webContents) {
win.webContents.send('mt::set-line-ending', lineEnding)
}
}
// --- Commands -------------------------------------------------------------
export const loadEditCommands = commandManager => {
commandManager.add(COMMANDS.EDIT_COPY, nativeCopy)
commandManager.add(COMMANDS.EDIT_COPY_AS_HTML, editorCopyAsHtml)
commandManager.add(COMMANDS.EDIT_COPY_AS_MARKDOWN, editorCopyAsMarkdown)
commandManager.add(COMMANDS.EDIT_CREATE_PARAGRAPH, editorCreateParagraph)
commandManager.add(COMMANDS.EDIT_CUT, nativeCut)
commandManager.add(COMMANDS.EDIT_DELETE_PARAGRAPH, editorDeleteParagraph)
commandManager.add(COMMANDS.EDIT_DUPLICATE, editorDuplicate)
commandManager.add(COMMANDS.EDIT_FIND, editorFind)
commandManager.add(COMMANDS.EDIT_FIND_IN_FOLDER, findInFolder)
commandManager.add(COMMANDS.EDIT_FIND_NEXT, editorFindNext)
commandManager.add(COMMANDS.EDIT_FIND_PREVIOUS, editorFindPrevious)
commandManager.add(COMMANDS.EDIT_PASTE, nativePaste)
commandManager.add(COMMANDS.EDIT_PASTE_AS_PLAINTEXT, editorPasteAsPlainText)
commandManager.add(COMMANDS.EDIT_REDO, editorRedo)
commandManager.add(COMMANDS.EDIT_REPLACE, editorReplace)
commandManager.add(COMMANDS.EDIT_SCREENSHOT, screenshot)
commandManager.add(COMMANDS.EDIT_SELECT_ALL, editorSelectAll)
commandManager.add(COMMANDS.EDIT_UNDO, editorUndo)
}
// --- IPC events -------------------------------------------------------------
// NOTE: Don't use static `getMenuItemById` here, instead request the menu by
// window id from `AppMenu` manager.
export const updateSidebarMenu = (applicationMenu, value) => {
const sideBarMenuItem = applicationMenu.getMenuItemById('sideBarMenuItem')
sideBarMenuItem.checked = !!value
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/help.js | src/main/menu/actions/help.js | export const showAboutDialog = win => {
if (win && win.webContents) {
win.webContents.send('mt::about-dialog')
}
}
export const showTweetDialog = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::tweet', type)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/index.js | src/main/menu/actions/index.js | import { loadEditCommands } from './edit'
import { loadFileCommands } from './file'
import { loadFormatCommands } from './format'
import { loadMarktextCommands } from './marktext'
import { loadParagraphCommands } from './paragraph'
import { loadViewCommands } from './view'
import { loadWindowCommands } from './window'
export const loadMenuCommands = commandManager => {
loadEditCommands(commandManager)
loadFileCommands(commandManager)
loadFormatCommands(commandManager)
loadMarktextCommands(commandManager)
loadParagraphCommands(commandManager)
loadViewCommands(commandManager)
loadWindowCommands(commandManager)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/view.js | src/main/menu/actions/view.js | import { ipcMain } from 'electron'
import { COMMANDS } from '../../commands'
const typewriterModeMenuItemId = 'typewriterModeMenuItem'
const focusModeMenuItemId = 'focusModeMenuItem'
const toggleTypeMode = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::toggle-view-mode-entry', type)
}
}
const setLayout = (win, type, value) => {
if (win && win.webContents) {
win.webContents.send('mt::set-view-layout', { [type]: value })
}
}
const toggleLayout = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::toggle-view-layout-entry', type)
}
}
export const debugToggleDevTools = win => {
if (win && global.MARKTEXT_DEBUG) {
win.webContents.toggleDevTools()
}
}
export const debugReloadWindow = win => {
if (win && global.MARKTEXT_DEBUG) {
ipcMain.emit('window-reload-by-id', win.id)
}
}
export const showCommandPalette = win => {
if (win && win.webContents) {
win.webContents.send('mt::show-command-palette')
}
}
export const toggleFocusMode = win => {
toggleTypeMode(win, 'focus')
}
export const toggleSourceCodeMode = win => {
toggleTypeMode(win, 'sourceCode')
}
export const toggleSidebar = win => {
toggleLayout(win, 'showSideBar')
}
export const toggleTabBar = win => {
toggleLayout(win, 'showTabBar')
}
export const showTabBar = win => {
setLayout(win, 'showTabBar', true)
}
export const showTableOfContents = win => {
setLayout(win, 'rightColumn', 'toc')
}
export const toggleTypewriterMode = win => {
toggleTypeMode(win, 'typewriter')
}
export const reloadImageCache = win => {
if (win && win.webContents) {
win.webContents.send('mt::invalidate-image-cache')
}
}
// --- Commands -------------------------------------------------------------
export const loadViewCommands = commandManager => {
commandManager.add(COMMANDS.VIEW_COMMAND_PALETTE, showCommandPalette)
commandManager.add(COMMANDS.VIEW_FOCUS_MODE, toggleFocusMode)
commandManager.add(COMMANDS.VIEW_FORCE_RELOAD_IMAGES, reloadImageCache)
commandManager.add(COMMANDS.VIEW_SOURCE_CODE_MODE, toggleSourceCodeMode)
commandManager.add(COMMANDS.VIEW_TOGGLE_SIDEBAR, toggleSidebar)
commandManager.add(COMMANDS.VIEW_TOGGLE_TABBAR, toggleTabBar)
commandManager.add(COMMANDS.VIEW_TOGGLE_TOC, showTableOfContents)
commandManager.add(COMMANDS.VIEW_TYPEWRITER_MODE, toggleTypewriterMode)
commandManager.add(COMMANDS.VIEW_DEV_RELOAD, debugReloadWindow)
commandManager.add(COMMANDS.VIEW_TOGGLE_DEV_TOOLS, debugToggleDevTools)
}
// --- IPC events -------------------------------------------------------------
// NOTE: Don't use static `getMenuItemById` here, instead request the menu by
// window id from `AppMenu` manager.
/**
*
* @param {*} applicationMenu The application menu instance.
* @param {*} changes Array of changed view settings (e.g. [ {showSideBar: true} ]).
*/
export const viewLayoutChanged = (applicationMenu, changes) => {
const disableMenuByName = (id, value) => {
const menuItem = applicationMenu.getMenuItemById(id)
menuItem.enabled = value
}
const changeMenuByName = (id, value) => {
const menuItem = applicationMenu.getMenuItemById(id)
menuItem.checked = value
}
for (const key in changes) {
const value = changes[key]
switch (key) {
case 'showSideBar':
changeMenuByName('sideBarMenuItem', value)
break
case 'showTabBar':
changeMenuByName('tabBarMenuItem', value)
break
case 'sourceCode':
changeMenuByName('sourceCodeModeMenuItem', value)
disableMenuByName(focusModeMenuItemId, !value)
disableMenuByName(typewriterModeMenuItemId, !value)
break
case 'typewriter':
changeMenuByName(typewriterModeMenuItemId, value)
break
case 'focus':
changeMenuByName(focusModeMenuItemId, value)
break
}
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/theme.js | src/main/menu/actions/theme.js | import { ipcMain } from 'electron'
export const selectTheme = theme => {
ipcMain.emit('set-user-preference', { theme })
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/window.js | src/main/menu/actions/window.js | import { ipcMain, Menu } from 'electron'
import { isOsx } from '../../config'
import { COMMANDS } from '../../commands'
import { zoomIn, zoomOut } from '../../windows/utils'
export const minimizeWindow = win => {
if (win) {
if (isOsx) {
Menu.sendActionToFirstResponder('performMiniaturize:')
} else {
win.minimize()
}
}
}
export const toggleAlwaysOnTop = win => {
if (win) {
ipcMain.emit('window-toggle-always-on-top', win)
}
}
export const toggleFullScreen = win => {
if (win) {
win.setFullScreen(!win.isFullScreen())
}
}
// --- Commands -------------------------------------------------------------
export const loadWindowCommands = commandManager => {
commandManager.add(COMMANDS.WINDOW_MINIMIZE, minimizeWindow)
commandManager.add(COMMANDS.WINDOW_TOGGLE_ALWAYS_ON_TOP, toggleAlwaysOnTop)
commandManager.add(COMMANDS.WINDOW_TOGGLE_FULL_SCREEN, toggleFullScreen)
commandManager.add(COMMANDS.WINDOW_ZOOM_IN, zoomIn)
commandManager.add(COMMANDS.WINDOW_ZOOM_OUT, zoomOut)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/paragraph.js | src/main/menu/actions/paragraph.js | import { COMMANDS } from '../../commands'
const DISABLE_LABELS = [
// paragraph menu items
'heading1MenuItem', 'heading2MenuItem', 'heading3MenuItem', 'heading4MenuItem',
'heading5MenuItem', 'heading6MenuItem',
'upgradeHeadingMenuItem', 'degradeHeadingMenuItem',
'tableMenuItem',
// formats menu items
'hyperlinkMenuItem', 'imageMenuItem'
]
const MENU_ID_MAP = Object.freeze({
heading1MenuItem: 'h1',
heading2MenuItem: 'h2',
heading3MenuItem: 'h3',
heading4MenuItem: 'h4',
heading5MenuItem: 'h5',
heading6MenuItem: 'h6',
tableMenuItem: 'figure',
codeFencesMenuItem: 'pre',
htmlBlockMenuItem: 'html',
mathBlockMenuItem: 'multiplemath',
quoteBlockMenuItem: 'blockquote',
orderListMenuItem: 'ol',
bulletListMenuItem: 'ul',
// taskListMenuItem: 'ul',
paragraphMenuItem: 'p',
horizontalLineMenuItem: 'hr',
frontMatterMenuItem: 'frontmatter' // 'pre'
})
const transformEditorElement = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::editor-paragraph-action', { type })
}
}
export const bulletList = win => {
transformEditorElement(win, 'ul-bullet')
}
export const codeFence = win => {
transformEditorElement(win, 'pre')
}
export const degradeHeading = win => {
transformEditorElement(win, 'degrade heading')
}
export const frontMatter = win => {
transformEditorElement(win, 'front-matter')
}
export const heading1 = win => {
transformEditorElement(win, 'heading 1')
}
export const heading2 = win => {
transformEditorElement(win, 'heading 2')
}
export const heading3 = win => {
transformEditorElement(win, 'heading 3')
}
export const heading4 = win => {
transformEditorElement(win, 'heading 4')
}
export const heading5 = win => {
transformEditorElement(win, 'heading 5')
}
export const heading6 = win => {
transformEditorElement(win, 'heading 6')
}
export const horizontalLine = win => {
transformEditorElement(win, 'hr')
}
export const htmlBlock = win => {
transformEditorElement(win, 'html')
}
export const looseListItem = win => {
transformEditorElement(win, 'loose-list-item')
}
export const mathFormula = win => {
transformEditorElement(win, 'mathblock')
}
export const orderedList = win => {
transformEditorElement(win, 'ol-order')
}
export const paragraph = win => {
transformEditorElement(win, 'paragraph')
}
export const quoteBlock = win => {
transformEditorElement(win, 'blockquote')
}
export const table = win => {
transformEditorElement(win, 'table')
}
export const taskList = win => {
transformEditorElement(win, 'ul-task')
}
export const increaseHeading = win => {
transformEditorElement(win, 'upgrade heading')
}
// --- Commands -------------------------------------------------------------
export const loadParagraphCommands = commandManager => {
commandManager.add(COMMANDS.PARAGRAPH_BULLET_LIST, bulletList)
commandManager.add(COMMANDS.PARAGRAPH_CODE_FENCE, codeFence)
commandManager.add(COMMANDS.PARAGRAPH_DEGRADE_HEADING, degradeHeading)
commandManager.add(COMMANDS.PARAGRAPH_FRONT_MATTER, frontMatter)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_1, heading1)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_2, heading2)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_3, heading3)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_4, heading4)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_5, heading5)
commandManager.add(COMMANDS.PARAGRAPH_HEADING_6, heading6)
commandManager.add(COMMANDS.PARAGRAPH_HORIZONTAL_LINE, horizontalLine)
commandManager.add(COMMANDS.PARAGRAPH_HTML_BLOCK, htmlBlock)
commandManager.add(COMMANDS.PARAGRAPH_LOOSE_LIST_ITEM, looseListItem)
commandManager.add(COMMANDS.PARAGRAPH_MATH_FORMULA, mathFormula)
commandManager.add(COMMANDS.PARAGRAPH_ORDERED_LIST, orderedList)
commandManager.add(COMMANDS.PARAGRAPH_PARAGRAPH, paragraph)
commandManager.add(COMMANDS.PARAGRAPH_QUOTE_BLOCK, quoteBlock)
commandManager.add(COMMANDS.PARAGRAPH_TABLE, table)
commandManager.add(COMMANDS.PARAGRAPH_TASK_LIST, taskList)
commandManager.add(COMMANDS.PARAGRAPH_INCREASE_HEADING, increaseHeading)
}
// --- IPC events -------------------------------------------------------------
// NOTE: Don't use static `getMenuItemById` here, instead request the menu by
// window id from `AppMenu` manager.
const setParagraphMenuItemStatus = (applicationMenu, bool) => {
const paragraphMenuItem = applicationMenu.getMenuItemById('paragraphMenuEntry')
paragraphMenuItem.submenu.items
.forEach(item => (item.enabled = bool))
}
const setMultipleStatus = (applicationMenu, list, status) => {
const paragraphMenuItem = applicationMenu.getMenuItemById('paragraphMenuEntry')
paragraphMenuItem.submenu.items
.filter(item => item.id && list.includes(item.id))
.forEach(item => (item.enabled = status))
}
const setCheckedMenuItem = (applicationMenu, { affiliation, isTable, isLooseListItem, isTaskList }) => {
const paragraphMenuItem = applicationMenu.getMenuItemById('paragraphMenuEntry')
paragraphMenuItem.submenu.items.forEach(item => (item.checked = false))
paragraphMenuItem.submenu.items.forEach(item => {
if (!item.id) {
return false
} else if (item.id === 'looseListItemMenuItem') {
item.checked = !!isLooseListItem
} else if (Object.keys(affiliation).some(b => {
if (b === 'ul' && isTaskList) {
if (item.id === 'taskListMenuItem') {
return true
}
return false
} else if (isTable && item.id === 'tableMenuItem') {
return true
} else if (item.id === 'codeFencesMenuItem' && /code$/.test(b)) {
return true
}
return b === MENU_ID_MAP[item.id]
})) {
item.checked = true
}
})
}
/**
* Update paragraph menu entires from given state.
*
* @param {Electron.MenuItem} applicationMenu The application menu instance.
* @param {*} state The selection information.
*/
export const updateSelectionMenus = (applicationMenu, state) => {
const {
// Key/boolean object like "ul: true" of block elements that are selected.
// This may be an empty object when multiple block elements are selected.
affiliation,
isDisabled,
isMultiline,
isCodeFences,
isCodeContent
} = state
// Reset format menu.
const formatMenuItem = applicationMenu.getMenuItemById('formatMenuItem')
formatMenuItem.submenu.items.forEach(item => (item.enabled = true))
// Handle menu checked.
setCheckedMenuItem(applicationMenu, state)
// Reset paragraph menu.
setParagraphMenuItemStatus(applicationMenu, !isDisabled)
if (isDisabled) {
return
}
if (isCodeFences) {
setParagraphMenuItemStatus(applicationMenu, false)
// A code line is selected.
if (isCodeContent) {
formatMenuItem.submenu.items.forEach(item => (item.enabled = false))
// TODO: Allow to transform to paragraph for other code blocks too but
// currently not supported by Muya.
// // Allow to transform to paragraph.
// if (affiliation.frontmatter) {
// setMultipleStatus(applicationMenu, ['frontMatterMenuItem'], true)
// } else if (affiliation.html) {
// setMultipleStatus(applicationMenu, ['htmlBlockMenuItem'], true)
// } else if (affiliation.multiplemath) {
// setMultipleStatus(applicationMenu, ['mathBlockMenuItem'], true)
// } else {
// setMultipleStatus(applicationMenu, ['codeFencesMenuItem'], true)
// }
if (Object.keys(affiliation).some(b => /code$/.test(b))) {
setMultipleStatus(applicationMenu, ['codeFencesMenuItem'], true)
}
}
} else if (isMultiline) {
formatMenuItem.submenu.items
.filter(item => item.id && DISABLE_LABELS.includes(item.id))
.forEach(item => (item.enabled = false))
setMultipleStatus(applicationMenu, DISABLE_LABELS, false)
}
// Disable loose list item.
if (!affiliation.ul && !affiliation.ol) {
setMultipleStatus(applicationMenu, ['looseListItemMenuItem'], false)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/marktext.js | src/main/menu/actions/marktext.js | import { autoUpdater } from 'electron-updater'
import { ipcMain, BrowserWindow, Menu } from 'electron'
import { COMMANDS } from '../../commands'
import { isOsx } from '../../config'
let runningUpdate = false
let win = null
autoUpdater.autoDownload = false
autoUpdater.on('error', error => {
if (win) {
win.webContents.send('mt::UPDATE_ERROR', error === null ? 'Error: unknown' : (error.message || error).toString())
}
})
autoUpdater.on('update-available', () => {
if (win) {
win.webContents.send('mt::UPDATE_AVAILABLE', 'Found an update, do you want download and install now?')
}
runningUpdate = false
})
autoUpdater.on('update-not-available', () => {
if (win) {
win.webContents.send('mt::UPDATE_NOT_AVAILABLE', 'Current version is up-to-date.')
}
runningUpdate = false
})
autoUpdater.on('update-downloaded', () => {
// TODO: We should ask the user, so that the user can save all documents and
// not just force close the application.
if (win) {
win.webContents.send('mt::UPDATE_DOWNLOADED', 'Update downloaded, application will be quit for update...')
}
setImmediate(() => autoUpdater.quitAndInstall())
})
ipcMain.on('mt::NEED_UPDATE', (e, { needUpdate }) => {
if (needUpdate) {
autoUpdater.downloadUpdate()
} else {
runningUpdate = false
}
})
ipcMain.on('mt::check-for-update', e => {
const win = BrowserWindow.fromWebContents(e.sender)
checkUpdates(win)
})
// --------------------------------------------------------
export const userSetting = () => {
ipcMain.emit('app-create-settings-window')
}
export const checkUpdates = browserWindow => {
if (!runningUpdate) {
runningUpdate = true
win = browserWindow
autoUpdater.checkForUpdates()
}
}
export const osxHide = () => {
if (isOsx) {
Menu.sendActionToFirstResponder('hide:')
}
}
export const osxHideAll = () => {
if (isOsx) {
Menu.sendActionToFirstResponder('hideOtherApplications:')
}
}
export const osxShowAll = () => {
if (isOsx) {
Menu.sendActionToFirstResponder('unhideAllApplications:')
}
}
// --- Commands -------------------------------------------------------------
export const loadMarktextCommands = commandManager => {
commandManager.add(COMMANDS.MT_HIDE, osxHide)
commandManager.add(COMMANDS.MT_HIDE_OTHERS, osxHideAll)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/file.js | src/main/menu/actions/file.js | import fs from 'fs-extra'
import path from 'path'
import { BrowserWindow, app, dialog, ipcMain, shell } from 'electron'
import log from 'electron-log'
import { isDirectory, isFile, exists } from 'common/filesystem'
import { MARKDOWN_EXTENSIONS, isMarkdownFile } from 'common/filesystem/paths'
import { checkUpdates, userSetting } from './marktext'
import { showTabBar } from './view'
import { COMMANDS } from '../../commands'
import { EXTENSION_HASN, PANDOC_EXTENSIONS, URL_REG } from '../../config'
import { normalizeAndResolvePath, writeFile } from '../../filesystem'
import { writeMarkdownFile } from '../../filesystem/markdown'
import { getPath, getRecommendTitleFromMarkdownString } from '../../utils'
import pandoc from '../../utils/pandoc'
// TODO(refactor): "save" and "save as" should be moved to the editor window (editor.js) and
// the renderer should communicate only with the editor window for file relevant stuff.
// E.g. "mt::save-tabs" --> "mt::window-save-tabs$wid:<windowId>"
const getExportExtensionFilter = type => {
if (type === 'pdf') {
return [{
name: 'Portable Document Format',
extensions: ['pdf']
}]
} else if (type === 'styledHtml') {
return [{
name: 'Hypertext Markup Language',
extensions: ['html']
}]
}
// Allow all extensions.
return undefined
}
const getPdfPageOptions = options => {
if (!options) {
return {}
}
const { pageSize, pageSizeWidth, pageSizeHeight, isLandscape } = options
if (pageSize === 'custom' && pageSizeWidth && pageSizeHeight) {
return {
// Note: mm to microns
pageSize: { height: pageSizeHeight * 1000, width: pageSizeWidth * 1000 },
landscape: !!isLandscape
}
} else {
return { pageSize, landscape: !!isLandscape }
}
}
// Handle the export response from renderer process.
const handleResponseForExport = async (e, { type, content, pathname, title, pageOptions }) => {
const win = BrowserWindow.fromWebContents(e.sender)
const extension = EXTENSION_HASN[type]
const dirname = pathname ? path.dirname(pathname) : getPath('documents')
let nakedFilename = pathname ? path.basename(pathname, '.md') : title
if (!nakedFilename) {
nakedFilename = 'Untitled'
}
const defaultPath = path.join(dirname, `${nakedFilename}${extension}`)
const { filePath, canceled } = await dialog.showSaveDialog(win, {
defaultPath,
filters: getExportExtensionFilter(type)
})
if (filePath && !canceled) {
try {
if (type === 'pdf') {
const options = { printBackground: true }
Object.assign(options, getPdfPageOptions(pageOptions))
const data = await win.webContents.printToPDF(options)
removePrintServiceFromWindow(win)
await writeFile(filePath, data, extension, 'binary')
} else {
if (!content) {
throw new Error('No HTML content found.')
}
await writeFile(filePath, content, extension, 'utf8')
}
win.webContents.send('mt::export-success', { type, filePath })
} catch (err) {
log.error('Error while exporting:', err)
const ERROR_MSG = err.message || `Error happened when export ${filePath}`
win.webContents.send('mt::show-notification', {
title: 'Export failure',
type: 'error',
message: ERROR_MSG
})
}
} else {
// User canceled save dialog
if (type === 'pdf') {
removePrintServiceFromWindow(win)
}
}
}
const handleResponseForPrint = e => {
const win = BrowserWindow.fromWebContents(e.sender)
win.webContents.print({ printBackground: true }, () => {
removePrintServiceFromWindow(win)
})
}
const handleResponseForSave = async (e, { id, filename, markdown, pathname, options, defaultPath }) => {
const win = BrowserWindow.fromWebContents(e.sender)
let recommendFilename = getRecommendTitleFromMarkdownString(markdown)
if (!recommendFilename) {
recommendFilename = filename || 'Untitled'
}
// If the file doesn't exist on disk add it to the recently used documents later
// and execute file from filesystem watcher for a short time. The file may exists
// on disk nevertheless but is already tracked by MarkText.
const alreadyExistOnDisk = !!pathname
let filePath = pathname
if (!filePath) {
const { filePath: dialogPath, canceled } = await dialog.showSaveDialog(win, {
defaultPath: path.join(defaultPath || getPath('documents'), `${recommendFilename}.md`)
})
if (dialogPath && !canceled) {
filePath = dialogPath
}
}
// Save dialog canceled by user - no error.
if (!filePath) {
return Promise.resolve()
}
filePath = path.resolve(filePath)
const extension = path.extname(filePath) || '.md'
filePath = !filePath.endsWith(extension) ? filePath += extension : filePath
return writeMarkdownFile(filePath, markdown, options, win)
.then(() => {
if (!alreadyExistOnDisk) {
ipcMain.emit('window-add-file-path', win.id, filePath)
ipcMain.emit('menu-add-recently-used', filePath)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else {
ipcMain.emit('window-file-saved', win.id, filePath)
win.webContents.send('mt::tab-saved', id)
}
return id
})
.catch(err => {
log.error('Error while saving:', err)
win.webContents.send('mt::tab-save-failure', id, err.message)
})
}
const showUnsavedFilesMessage = async (win, files) => {
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Save', 'Cancel', 'Don\'t save'],
defaultId: 0,
message: `Do you want to save the changes you made to ${files.length} ${files.length === 1 ? 'file' : 'files'}?\n\n${files.map(f => f.filename).join('\n')}`,
detail: 'Your changes will be lost if you don\'t save them.',
cancelId: 1,
noLink: true
})
switch (response) {
case 2:
return { needSave: false }
case 0:
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ needSave: true })
})
})
default:
return null
}
}
const noticePandocNotFound = win => {
return win.webContents.send('mt::pandoc-not-exists', {
title: 'Import Warning',
type: 'warning',
message: 'Install pandoc before you want to import files.',
time: 10000
})
}
const openPandocFile = async (windowId, pathname) => {
try {
const converter = pandoc(pathname, 'markdown')
const data = await converter()
ipcMain.emit('app-open-markdown-by-id', windowId, data)
} catch (err) {
log.error('Error while converting file:', err)
}
}
const removePrintServiceFromWindow = win => {
// remove print service content and restore GUI
win.webContents.send('mt::print-service-clearup')
}
// --- events -----------------------------------
ipcMain.on('mt::save-tabs', (e, unsavedFiles) => {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.catch(log.error)
})
ipcMain.on('mt::save-and-close-tabs', async (e, unsavedFiles) => {
const win = BrowserWindow.fromWebContents(e.sender)
const userResult = await showUnsavedFilesMessage(win, unsavedFiles)
if (!userResult) {
return
}
const { needSave } = userResult
if (needSave) {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.then(arr => {
const tabIds = arr.filter(id => id != null)
win.webContents.send('mt::force-close-tabs-by-id', tabIds)
})
.catch(err => {
log.error('Error while save all:', err)
})
} else {
const tabIds = unsavedFiles.map(f => f.id)
win.webContents.send('mt::force-close-tabs-by-id', tabIds)
}
})
ipcMain.on('mt::response-file-save-as', async (e, { id, filename, markdown, pathname, options, defaultPath }) => {
const win = BrowserWindow.fromWebContents(e.sender)
let recommendFilename = getRecommendTitleFromMarkdownString(markdown)
if (!recommendFilename) {
recommendFilename = filename || 'Untitled'
}
// If the file doesn't exist on disk add it to the recently used documents later
// and execute file from filesystem watcher for a short time. The file may exists
// on disk nevertheless but is already tracked by MarkText.
const alreadyExistOnDisk = !!pathname
let { filePath, canceled } = await dialog.showSaveDialog(win, {
defaultPath: pathname || path.join(defaultPath || getPath('documents'), `${recommendFilename}.md`)
})
if (filePath && !canceled) {
filePath = path.resolve(filePath)
writeMarkdownFile(filePath, markdown, options, win)
.then(() => {
if (!alreadyExistOnDisk) {
ipcMain.emit('window-add-file-path', win.id, filePath)
ipcMain.emit('menu-add-recently-used', filePath)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else if (pathname !== filePath) {
// Update window file list and watcher.
ipcMain.emit('window-change-file-path', win.id, filePath, pathname)
const filename = path.basename(filePath)
win.webContents.send('mt::set-pathname', { id, pathname: filePath, filename })
} else {
ipcMain.emit('window-file-saved', win.id, filePath)
win.webContents.send('mt::tab-saved', id)
}
})
.catch(err => {
log.error('Error while save as:', err)
win.webContents.send('mt::tab-save-failure', id, err.message)
})
}
})
ipcMain.on('mt::close-window-confirm', async (e, unsavedFiles) => {
const win = BrowserWindow.fromWebContents(e.sender)
const userResult = await showUnsavedFilesMessage(win, unsavedFiles)
if (!userResult) {
return
}
const { needSave } = userResult
if (needSave) {
Promise.all(unsavedFiles.map(file => handleResponseForSave(e, file)))
.then(() => {
ipcMain.emit('window-close-by-id', win.id)
})
.catch(err => {
log.error('Error while saving before quit:', err)
// Notify user about the problem.
dialog.showMessageBox(win, {
type: 'error',
buttons: ['Close', 'Keep It Open'],
message: 'Failure while saving files',
detail: err.message
})
.then(({ response }) => {
if (win.id && response === 0) {
ipcMain.emit('window-close-by-id', win.id)
}
})
})
} else {
ipcMain.emit('window-close-by-id', win.id)
}
})
ipcMain.on('mt::response-file-save', handleResponseForSave)
ipcMain.on('mt::response-export', handleResponseForExport)
ipcMain.on('mt::response-print', handleResponseForPrint)
ipcMain.on('mt::window::drop', async (e, fileList) => {
const win = BrowserWindow.fromWebContents(e.sender)
for (const file of fileList) {
if (isMarkdownFile(file)) {
openFileOrFolder(win, file)
continue
}
// Try to import the file
if (PANDOC_EXTENSIONS.some(ext => file.endsWith(ext))) {
const existsPandoc = pandoc.exists()
if (!existsPandoc) {
noticePandocNotFound(win)
} else {
openPandocFile(win.id, file)
}
break
}
}
})
ipcMain.on('mt::rename', async (e, { id, pathname, newPathname }) => {
if (pathname === newPathname) return
const win = BrowserWindow.fromWebContents(e.sender)
const doRename = () => {
fs.rename(pathname, newPathname, err => {
if (err) {
log.error(`mt::rename: Cannot rename "${pathname}" to "${newPathname}".\n${err.stack}`)
return
}
ipcMain.emit('window-change-file-path', win.id, newPathname, pathname)
e.sender.send('mt::set-pathname', {
id,
pathname: newPathname,
filename: path.basename(newPathname)
})
})
}
if (!await exists(newPathname)) {
doRename()
} else {
const { response } = await dialog.showMessageBox(win, {
type: 'warning',
buttons: ['Replace', 'Cancel'],
defaultId: 1,
message: `The file "${path.basename(newPathname)}" already exists. Do you want to replace it?`,
cancelId: 1,
noLink: true
})
if (response === 0) {
doRename()
}
}
})
ipcMain.on('mt::response-file-move-to', async (e, { id, pathname }) => {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePath, canceled } = await dialog.showSaveDialog(win, {
buttonLabel: 'Move to',
nameFieldLabel: 'Filename:',
defaultPath: pathname
})
if (filePath && !canceled) {
fs.rename(pathname, filePath, err => {
if (err) {
log.error(`mt::rename: Cannot rename "${pathname}" to "${filePath}".\n${err.stack}`)
return
}
ipcMain.emit('window-change-file-path', win.id, filePath, pathname)
e.sender.send('mt::set-pathname', { id, pathname: filePath, filename: path.basename(filePath) })
})
}
})
ipcMain.on('mt::ask-for-open-project-in-sidebar', async e => {
const win = BrowserWindow.fromWebContents(e.sender)
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
const resolvedPath = normalizeAndResolvePath(filePaths[0])
ipcMain.emit('app-open-directory-by-id', win.id, resolvedPath, true)
}
})
ipcMain.on('mt::format-link-click', (e, { data, dirname }) => {
if (!data || (!data.href && !data.text)) {
return
}
const urlCandidate = data.href || data.text
if (URL_REG.test(urlCandidate)) {
shell.openExternal(urlCandidate)
return
} else if (/^[a-z0-9]+:\/\//i.test(urlCandidate)) {
// Prevent other URLs.
return
}
const href = data.href
if (!href) {
return
}
let pathname = null
if (path.isAbsolute(href)) {
pathname = href
} else if (dirname && !path.isAbsolute(href)) {
pathname = path.join(dirname, href)
}
if (pathname) {
pathname = path.normalize(pathname)
if (isMarkdownFile(pathname)) {
const win = BrowserWindow.fromWebContents(e.sender)
openFileOrFolder(win, pathname)
} else {
shell.openPath(pathname)
}
}
})
// --- commands -------------------------------------
ipcMain.on('mt::cmd-open-file', e => {
const win = BrowserWindow.fromWebContents(e.sender)
openFile(win)
})
ipcMain.on('mt::cmd-new-editor-window', () => {
newEditorWindow()
})
ipcMain.on('mt::cmd-open-folder', e => {
const win = BrowserWindow.fromWebContents(e.sender)
openFolder(win)
})
ipcMain.on('mt::cmd-close-window', e => {
const win = BrowserWindow.fromWebContents(e.sender)
win.close()
})
ipcMain.on('mt::cmd-import-file', e => {
const win = BrowserWindow.fromWebContents(e.sender)
importFile(win)
})
// --- menu -------------------------------------
export const exportFile = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::show-export-dialog', type)
}
}
export const importFile = async win => {
const existsPandoc = pandoc.exists()
if (!existsPandoc) {
return noticePandocNotFound(win)
}
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile'],
filters: [{
name: 'All Files',
extensions: PANDOC_EXTENSIONS
}]
})
if (filePaths && filePaths[0]) {
openPandocFile(win.id, filePaths[0])
}
}
export const printDocument = win => {
if (win) {
win.webContents.send('mt::show-export-dialog', 'print')
}
}
export const openFile = async win => {
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openFile', 'multiSelections'],
filters: [{
name: 'Markdown document',
extensions: MARKDOWN_EXTENSIONS
}]
})
if (Array.isArray(filePaths) && filePaths.length > 0) {
ipcMain.emit('app-open-files-by-id', win.id, filePaths)
}
}
export const openFolder = async win => {
const { filePaths } = await dialog.showOpenDialog(win, {
properties: ['openDirectory', 'createDirectory']
})
if (filePaths && filePaths[0]) {
openFileOrFolder(win, filePaths[0])
}
}
export const openFileOrFolder = (win, pathname) => {
const resolvedPath = normalizeAndResolvePath(pathname)
if (isFile(resolvedPath)) {
ipcMain.emit('app-open-file-by-id', win.id, resolvedPath)
} else if (isDirectory(resolvedPath)) {
ipcMain.emit('app-open-directory-by-id', win.id, resolvedPath)
} else {
console.error(`[ERROR] Cannot open unknown file: "${resolvedPath}"`)
}
}
export const newBlankTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::new-untitled-tab')
showTabBar(win)
}
}
export const newEditorWindow = () => {
ipcMain.emit('app-create-editor-window')
}
export const closeTab = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-close-tab')
}
}
export const closeWindow = win => {
if (win) {
win.close()
}
}
export const save = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-ask-file-save')
}
}
export const saveAs = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-ask-file-save-as')
}
}
export const autoSave = (menuItem, browserWindow) => {
const { checked } = menuItem
ipcMain.emit('set-user-preference', { autoSave: checked })
}
export const moveTo = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-move-file')
}
}
export const rename = win => {
if (win && win.webContents) {
win.webContents.send('mt::editor-rename-file')
}
}
export const clearRecentlyUsed = () => {
ipcMain.emit('menu-clear-recently-used')
}
// --- Commands -------------------------------------------------------------
export const loadFileCommands = commandManager => {
commandManager.add(COMMANDS.FILE_CHECK_UPDATE, checkUpdates)
commandManager.add(COMMANDS.FILE_CLOSE_TAB, closeTab)
commandManager.add(COMMANDS.FILE_CLOSE_WINDOW, closeWindow)
commandManager.add(COMMANDS.FILE_EXPORT_FILE, exportFile)
commandManager.add(COMMANDS.FILE_IMPORT_FILE, importFile)
commandManager.add(COMMANDS.FILE_MOVE_FILE, moveTo)
commandManager.add(COMMANDS.FILE_NEW_FILE, newEditorWindow)
commandManager.add(COMMANDS.FILE_NEW_TAB, newBlankTab)
commandManager.add(COMMANDS.FILE_OPEN_FILE, openFile)
commandManager.add(COMMANDS.FILE_OPEN_FOLDER, openFolder)
commandManager.add(COMMANDS.FILE_PREFERENCES, userSetting)
commandManager.add(COMMANDS.FILE_PRINT, printDocument)
commandManager.add(COMMANDS.FILE_QUIT, app.quit)
commandManager.add(COMMANDS.FILE_RENAME_FILE, rename)
commandManager.add(COMMANDS.FILE_SAVE, save)
commandManager.add(COMMANDS.FILE_SAVE_AS, saveAs)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/actions/format.js | src/main/menu/actions/format.js | import { COMMANDS } from '../../commands'
const MENU_ID_FORMAT_MAP = Object.freeze({
strongMenuItem: 'strong',
emphasisMenuItem: 'em',
inlineCodeMenuItem: 'inline_code',
strikeMenuItem: 'del',
hyperlinkMenuItem: 'link',
imageMenuItem: 'image',
inlineMathMenuItem: 'inline_math'
})
const format = (win, type) => {
if (win && win.webContents) {
win.webContents.send('mt::editor-format-action', { type })
}
}
export const clearFormat = win => {
format(win, 'clear')
}
export const emphasis = win => {
format(win, 'em')
}
export const highlight = win => {
format(win, 'mark')
}
export const hyperlink = win => {
format(win, 'link')
}
export const image = win => {
format(win, 'image')
}
export const inlineCode = win => {
format(win, 'inline_code')
}
export const inlineMath = win => {
format(win, 'inline_math')
}
export const strikethrough = win => {
format(win, 'del')
}
export const strong = win => {
format(win, 'strong')
}
export const subscript = win => {
format(win, 'sub')
}
export const superscript = win => {
format(win, 'sup')
}
export const underline = win => {
format(win, 'u')
}
// --- Commands -------------------------------------------------------------
export const loadFormatCommands = commandManager => {
commandManager.add(COMMANDS.FORMAT_CLEAR_FORMAT, clearFormat)
commandManager.add(COMMANDS.FORMAT_EMPHASIS, emphasis)
commandManager.add(COMMANDS.FORMAT_HIGHLIGHT, highlight)
commandManager.add(COMMANDS.FORMAT_HYPERLINK, hyperlink)
commandManager.add(COMMANDS.FORMAT_IMAGE, image)
commandManager.add(COMMANDS.FORMAT_INLINE_CODE, inlineCode)
commandManager.add(COMMANDS.FORMAT_INLINE_MATH, inlineMath)
commandManager.add(COMMANDS.FORMAT_STRIKE, strikethrough)
commandManager.add(COMMANDS.FORMAT_STRONG, strong)
commandManager.add(COMMANDS.FORMAT_SUBSCRIPT, subscript)
commandManager.add(COMMANDS.FORMAT_SUPERSCRIPT, superscript)
commandManager.add(COMMANDS.FORMAT_UNDERLINE, underline)
}
// --- IPC events -------------------------------------------------------------
// NOTE: Don't use static `getMenuItemById` here, instead request the menu by
// window id from `AppMenu` manager.
/**
* Update format menu entires from given state.
*
* @param {Electron.MenuItem} applicationMenu The application menu instance.
* @param {Object.<string, boolean>} formats A object map with selected formats.
*/
export const updateFormatMenu = (applicationMenu, formats) => {
const formatMenuItem = applicationMenu.getMenuItemById('formatMenuItem')
formatMenuItem.submenu.items.forEach(item => (item.checked = false))
formatMenuItem.submenu.items
.forEach(item => {
if (item.id && formats[MENU_ID_FORMAT_MAP[item.id]]) {
item.checked = true
}
})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/edit.js | src/main/menu/templates/edit.js | import * as actions from '../actions/edit'
import { isOsx } from '../../config'
import { COMMANDS } from '../../commands'
export default function (keybindings) {
return {
label: '&Edit',
submenu: [{
label: 'Undo',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_UNDO),
click: (menuItem, browserWindow) => {
actions.editorUndo(browserWindow)
}
}, {
label: 'Redo',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_REDO),
click: (menuItem, browserWindow) => {
actions.editorRedo(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_CUT),
click (menuItem, browserWindow) {
actions.nativeCut(browserWindow)
}
}, {
label: 'Copy',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_COPY),
click (menuItem, browserWindow) {
actions.nativeCopy(browserWindow)
}
}, {
label: 'Paste',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_PASTE),
click (menuItem, browserWindow) {
actions.nativePaste(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Copy as Markdown',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_COPY_AS_MARKDOWN),
click (menuItem, browserWindow) {
actions.editorCopyAsMarkdown(browserWindow)
}
}, {
label: 'Copy as HTML',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_COPY_AS_HTML),
click (menuItem, browserWindow) {
actions.editorCopyAsHtml(browserWindow)
}
}, {
label: 'Paste as Plain Text',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_PASTE_AS_PLAINTEXT),
click (menuItem, browserWindow) {
actions.editorPasteAsPlainText(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Select All',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_SELECT_ALL),
click (menuItem, browserWindow) {
actions.editorSelectAll(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Duplicate',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_DUPLICATE),
click (menuItem, browserWindow) {
actions.editorDuplicate(browserWindow)
}
}, {
label: 'Create Paragraph',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_CREATE_PARAGRAPH),
click (menuItem, browserWindow) {
actions.editorCreateParagraph(browserWindow)
}
}, {
label: 'Delete Paragraph',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_DELETE_PARAGRAPH),
click (menuItem, browserWindow) {
actions.editorDeleteParagraph(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Find',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_FIND),
click (menuItem, browserWindow) {
actions.editorFind(browserWindow)
}
}, {
label: 'Find Next',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_FIND_NEXT),
click (menuItem, browserWindow) {
actions.editorFindNext(browserWindow)
}
}, {
label: 'Find Previous',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_FIND_PREVIOUS),
click (menuItem, browserWindow) {
actions.editorFindPrevious(browserWindow)
}
}, {
label: 'Replace',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_REPLACE),
click (menuItem, browserWindow) {
actions.editorReplace(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Find in Folder',
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_FIND_IN_FOLDER),
click (menuItem, browserWindow) {
actions.findInFolder(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Screenshot',
id: 'screenshot',
visible: isOsx,
accelerator: keybindings.getAccelerator(COMMANDS.EDIT_SCREENSHOT),
click (menuItem, browserWindow) {
actions.screenshot(browserWindow)
}
}, {
type: 'separator'
}, {
// TODO: Remove this menu entry and add it to the command palette (#1408).
label: 'Line Ending',
submenu: [{
id: 'crlfLineEndingMenuEntry',
label: 'Carriage return and line feed (CRLF)',
type: 'radio',
click (menuItem, browserWindow) {
actions.lineEnding(browserWindow, 'crlf')
}
}, {
id: 'lfLineEndingMenuEntry',
label: 'Line feed (LF)',
type: 'radio',
click (menuItem, browserWindow) {
actions.lineEnding(browserWindow, 'lf')
}
}]
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/dock.js | src/main/menu/templates/dock.js | import { app, Menu } from 'electron'
import * as actions from '../actions/file'
const dockMenu = Menu.buildFromTemplate([{
label: 'Open...',
click (menuItem, browserWindow) {
if (browserWindow) {
actions.openFile(browserWindow)
} else {
actions.newEditorWindow()
}
}
}, {
label: 'Clear Recent',
click () {
app.clearRecentDocuments()
}
}])
export default dockMenu
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/help.js | src/main/menu/templates/help.js | import path from 'path'
import { shell } from 'electron'
import { isFile } from 'common/filesystem'
import * as actions from '../actions/help'
import { checkUpdates } from '../actions/marktext'
/// Check whether the package is updatable at runtime.
const isUpdatable = () => {
// TODO: If not updatable, allow to check whether there is a new version available.
const resFile = isFile(path.join(process.resourcesPath, 'app-update.yml'))
if (!resFile) {
// No update resource file available.
return false
} else if (process.env.APPIMAGE) {
// We are running as AppImage.
return true
} else if (process.platform === 'win32' && isFile(path.join(process.resourcesPath, 'md.ico'))) {
// Windows is a little but tricky. The update resource file is always available and
// there is no way to check the target type at runtime (electron-builder#4119).
// As workaround we check whether "md.ico" exists that is only included in the setup.
return true
}
// Otherwise assume that we cannot perform an auto update (standalone binary, archives,
// packed for package manager).
return false
}
export default function () {
const helpMenu = {
label: '&Help',
role: 'help',
submenu: [{
label: 'Quick Start...',
click () {
shell.openExternal('https://github.com/marktext/marktext/blob/master/docs/README.md')
}
}, {
label: 'Markdown Reference...',
click () {
shell.openExternal('https://github.com/marktext/marktext/blob/master/docs/MARKDOWN_SYNTAX.md')
}
}, {
label: 'Changelog...',
click () {
shell.openExternal('https://github.com/marktext/marktext/blob/master/.github/CHANGELOG.md')
}
}, {
type: 'separator'
}, {
label: 'Donate via Open Collective...',
click (item, win) {
shell.openExternal('https://opencollective.com/marktext')
}
}, {
label: 'Feedback via Twitter...',
click (item, win) {
actions.showTweetDialog(win, 'twitter')
}
}, {
label: 'Report Issue or Request Feature...',
click () {
shell.openExternal('https://github.com/marktext/marktext/issues')
}
}, {
type: 'separator'
}, {
label: 'Website...',
click () {
shell.openExternal('https://github.com/marktext/marktext')
}
}, {
label: 'Watch on GitHub...',
click () {
shell.openExternal('https://github.com/marktext/marktext')
}
}, {
label: 'Follow us on Github...',
click () {
shell.openExternal('https://github.com/Jocs')
}
}, {
label: 'Follow us on Twitter...',
click () {
shell.openExternal('https://twitter.com/marktextapp')
}
}, {
type: 'separator'
}, {
label: 'License...',
click () {
shell.openExternal('https://github.com/marktext/marktext/blob/master/LICENSE')
}
}]
}
if (isUpdatable()) {
helpMenu.submenu.push({
type: 'separator'
}, {
label: 'Check for updates...',
click (menuItem, browserWindow) {
checkUpdates(browserWindow)
}
})
}
if (process.platform !== 'darwin') {
helpMenu.submenu.push({
type: 'separator'
}, {
label: 'About MarkText...',
click (menuItem, browserWindow) {
actions.showAboutDialog(browserWindow)
}
})
}
return helpMenu
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/index.js | src/main/menu/templates/index.js | import edit from './edit'
import prefEdit from './prefEdit'
import file from './file'
import help from './help'
import marktext from './marktext'
import view from './view'
import window from './window'
import paragraph from './paragraph'
import format from './format'
import theme from './theme'
export dockMenu from './dock'
/**
* Create the setting window menu.
*
* @param {Keybindings} keybindings The keybindings instance
*/
export const configSettingMenu = (keybindings) => {
return [
...(process.platform === 'darwin' ? [marktext(keybindings)] : []),
prefEdit(keybindings),
help()
]
}
/**
* Create the application menu for the editor window.
*
* @param {Keybindings} keybindings The keybindings instance.
* @param {Preference} preferences The preference instance.
* @param {string[]} recentlyUsedFiles The recently used files.
*/
export default function (keybindings, preferences, recentlyUsedFiles) {
return [
...(process.platform === 'darwin' ? [marktext(keybindings)] : []),
file(keybindings, preferences, recentlyUsedFiles),
edit(keybindings),
paragraph(keybindings),
format(keybindings),
window(keybindings),
theme(preferences),
view(keybindings),
help()
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/view.js | src/main/menu/templates/view.js | import * as actions from '../actions/view'
export default function (keybindings) {
const viewMenu = {
label: '&View',
submenu: [{
label: 'Command Palette...',
accelerator: keybindings.getAccelerator('view.command-palette'),
click (menuItem, focusedWindow) {
actions.showCommandPalette(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'sourceCodeModeMenuItem',
label: 'Source Code Mode',
accelerator: keybindings.getAccelerator('view.source-code-mode'),
type: 'checkbox',
checked: false,
click (item, focusedWindow) {
actions.toggleSourceCodeMode(focusedWindow)
}
}, {
id: 'typewriterModeMenuItem',
label: 'Typewriter Mode',
accelerator: keybindings.getAccelerator('view.typewriter-mode'),
type: 'checkbox',
checked: false,
click (item, focusedWindow) {
actions.toggleTypewriterMode(focusedWindow)
}
}, {
id: 'focusModeMenuItem',
label: 'Focus Mode',
accelerator: keybindings.getAccelerator('view.focus-mode'),
type: 'checkbox',
checked: false,
click (item, focusedWindow) {
actions.toggleFocusMode(focusedWindow)
}
}, {
type: 'separator'
}, {
label: 'Show Sidebar',
id: 'sideBarMenuItem',
accelerator: keybindings.getAccelerator('view.toggle-sidebar'),
type: 'checkbox',
checked: false,
click (item, focusedWindow) {
actions.toggleSidebar(focusedWindow)
}
}, {
label: 'Show Tab Bar',
id: 'tabBarMenuItem',
accelerator: keybindings.getAccelerator('view.toggle-tabbar'),
type: 'checkbox',
checked: false,
click (item, focusedWindow) {
actions.toggleTabBar(focusedWindow)
}
}, {
label: 'Toggle Table of Contents',
id: 'tocMenuItem',
accelerator: keybindings.getAccelerator('view.toggle-toc'),
click (_, focusedWindow) {
actions.showTableOfContents(focusedWindow)
}
}, {
label: 'Reload Images',
accelerator: keybindings.getAccelerator('view.reload-images'),
click (item, focusedWindow) {
actions.reloadImageCache(focusedWindow)
}
}]
}
if (global.MARKTEXT_DEBUG) {
viewMenu.submenu.push({
type: 'separator'
})
viewMenu.submenu.push({
label: 'Show Developer Tools',
accelerator: keybindings.getAccelerator('view.toggle-dev-tools'),
click (item, win) {
actions.debugToggleDevTools(win)
}
})
viewMenu.submenu.push({
label: 'Reload window',
accelerator: keybindings.getAccelerator('view.dev-reload'),
click (item, focusedWindow) {
actions.debugReloadWindow(focusedWindow)
}
})
}
return viewMenu
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/prefEdit.js | src/main/menu/templates/prefEdit.js | export default function (keybindings) {
return {
label: 'Edit',
submenu: [{
label: 'Cut',
accelerator: keybindings.getAccelerator('edit.cut'),
role: 'cut'
}, {
label: 'Copy',
accelerator: keybindings.getAccelerator('edit.copy'),
role: 'copy'
}, {
label: 'Paste',
accelerator: keybindings.getAccelerator('edit.paste'),
role: 'paste'
}, {
type: 'separator'
}, {
label: 'Select All',
accelerator: keybindings.getAccelerator('edit.select-all'),
role: 'selectAll'
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/theme.js | src/main/menu/templates/theme.js | import * as actions from '../actions/theme'
export default function (userPreference) {
const { theme } = userPreference.getAll()
return {
label: '&Theme',
id: 'themeMenu',
submenu: [{
label: 'Cadmium Light',
type: 'radio',
id: 'light',
checked: theme === 'light',
click (menuItem, browserWindow) {
actions.selectTheme('light')
}
}, {
label: 'Dark',
type: 'radio',
id: 'dark',
checked: theme === 'dark',
click (menuItem, browserWindow) {
actions.selectTheme('dark')
}
}, {
label: 'Graphite Light',
type: 'radio',
id: 'graphite',
checked: theme === 'graphite',
click (menuItem, browserWindow) {
actions.selectTheme('graphite')
}
}, {
label: 'Material Dark',
type: 'radio',
id: 'material-dark',
checked: theme === 'material-dark',
click (menuItem, browserWindow) {
actions.selectTheme('material-dark')
}
}, {
label: 'One Dark',
type: 'radio',
id: 'one-dark',
checked: theme === 'one-dark',
click (menuItem, browserWindow) {
actions.selectTheme('one-dark')
}
}, {
label: 'Ulysses Light',
type: 'radio',
id: 'ulysses',
checked: theme === 'ulysses',
click (menuItem, browserWindow) {
actions.selectTheme('ulysses')
}
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/window.js | src/main/menu/templates/window.js | import { Menu } from 'electron'
import { minimizeWindow, toggleAlwaysOnTop, toggleFullScreen } from '../actions/window'
import { zoomIn, zoomOut } from '../../windows/utils'
import { isOsx } from '../../config'
export default function (keybindings) {
const menu = {
label: '&Window',
role: 'window',
submenu: [{
label: 'Minimize',
accelerator: keybindings.getAccelerator('window.minimize'),
click (menuItem, browserWindow) {
minimizeWindow(browserWindow)
}
}, {
id: 'alwaysOnTopMenuItem',
label: 'Always on Top',
type: 'checkbox',
accelerator: keybindings.getAccelerator('window.toggle-always-on-top'),
click (menuItem, browserWindow) {
toggleAlwaysOnTop(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Zoom In',
accelerator: keybindings.getAccelerator('window.zoom-in'),
click (menuItem, browserWindow) {
zoomIn(browserWindow)
}
}, {
label: 'Zoom Out',
accelerator: keybindings.getAccelerator('window.zoom-out'),
click (menuItem, browserWindow) {
zoomOut(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Show in Full Screen',
accelerator: keybindings.getAccelerator('window.toggle-full-screen'),
click (item, browserWindow) {
if (browserWindow) {
toggleFullScreen(browserWindow)
}
}
}]
}
if (isOsx) {
menu.submenu.push({
label: 'Bring All to Front',
click () {
Menu.sendActionToFirstResponder('arrangeInFront:')
}
})
}
return menu
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/paragraph.js | src/main/menu/templates/paragraph.js | import * as actions from '../actions/paragraph'
export default function (keybindings) {
return {
id: 'paragraphMenuEntry',
label: '&Paragraph',
submenu: [{
id: 'heading1MenuItem',
label: 'Heading 1',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-1'),
click (menuItem, focusedWindow) {
actions.heading1(focusedWindow)
}
}, {
id: 'heading2MenuItem',
label: 'Heading 2',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-2'),
click (menuItem, focusedWindow) {
actions.heading2(focusedWindow)
}
}, {
id: 'heading3MenuItem',
label: 'Heading 3',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-3'),
click (menuItem, focusedWindow) {
actions.heading3(focusedWindow)
}
}, {
id: 'heading4MenuItem',
label: 'Heading 4',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-4'),
click (menuItem, focusedWindow) {
actions.heading4(focusedWindow)
}
}, {
id: 'heading5MenuItem',
label: 'Heading 5',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-5'),
click (menuItem, focusedWindow) {
actions.heading5(focusedWindow)
}
}, {
id: 'heading6MenuItem',
label: 'Heading 6',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.heading-6'),
click (menuItem, focusedWindow) {
actions.heading6(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'upgradeHeadingMenuItem',
label: 'Promote Heading',
accelerator: keybindings.getAccelerator('paragraph.upgrade-heading'),
click (menuItem, focusedWindow) {
actions.increaseHeading(focusedWindow)
}
}, {
id: 'degradeHeadingMenuItem',
label: 'Demote Heading',
accelerator: keybindings.getAccelerator('paragraph.degrade-heading'),
click (menuItem, focusedWindow) {
actions.degradeHeading(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'tableMenuItem',
label: 'Table',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.table'),
click (menuItem, focusedWindow) {
actions.table(focusedWindow)
}
}, {
id: 'codeFencesMenuItem',
label: 'Code Fences',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.code-fence'),
click (menuItem, focusedWindow) {
actions.codeFence(focusedWindow)
}
}, {
id: 'quoteBlockMenuItem',
label: 'Quote Block',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.quote-block'),
click (menuItem, focusedWindow) {
actions.quoteBlock(focusedWindow)
}
}, {
id: 'mathBlockMenuItem',
label: 'Math Block',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.math-formula'),
click (menuItem, focusedWindow) {
actions.mathFormula(focusedWindow)
}
}, {
id: 'htmlBlockMenuItem',
label: 'Html Block',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.html-block'),
click (menuItem, focusedWindow) {
actions.htmlBlock(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'orderListMenuItem',
label: 'Ordered List',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.order-list'),
click (menuItem, focusedWindow) {
actions.orderedList(focusedWindow)
}
}, {
id: 'bulletListMenuItem',
label: 'Bullet List',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.bullet-list'),
click (menuItem, focusedWindow) {
actions.bulletList(focusedWindow)
}
}, {
id: 'taskListMenuItem',
label: 'Task List',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.task-list'),
click (menuItem, focusedWindow) {
actions.taskList(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'looseListItemMenuItem',
label: 'Loose List Item',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.loose-list-item'),
click (menuItem, focusedWindow) {
actions.looseListItem(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'paragraphMenuItem',
label: 'Paragraph',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.paragraph'),
click (menuItem, focusedWindow) {
actions.paragraph(focusedWindow)
}
}, {
id: 'horizontalLineMenuItem',
label: 'Horizontal Rule',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.horizontal-line'),
click (menuItem, focusedWindow) {
actions.horizontalLine(focusedWindow)
}
}, {
id: 'frontMatterMenuItem',
label: 'Front Matter',
type: 'checkbox',
accelerator: keybindings.getAccelerator('paragraph.front-matter'),
click (menuItem, focusedWindow) {
actions.frontMatter(focusedWindow)
}
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/marktext.js | src/main/menu/templates/marktext.js | import { app } from 'electron'
import { showAboutDialog } from '../actions/help'
import * as actions from '../actions/marktext'
// macOS only menu.
export default function (keybindings) {
return {
label: 'MarkText',
submenu: [{
label: 'About MarkText',
click (menuItem, focusedWindow) {
showAboutDialog(focusedWindow)
}
}, {
label: 'Check for updates...',
click (menuItem, focusedWindow) {
actions.checkUpdates(focusedWindow)
}
}, {
label: 'Preferences',
accelerator: keybindings.getAccelerator('file.preferences'),
click () {
actions.userSetting()
}
}, {
type: 'separator'
}, {
label: 'Services',
role: 'services',
submenu: []
}, {
type: 'separator'
}, {
label: 'Hide MarkText',
accelerator: keybindings.getAccelerator('mt.hide'),
click () {
actions.osxHide()
}
}, {
label: 'Hide Others',
accelerator: keybindings.getAccelerator('mt.hide-others'),
click () {
actions.osxHideAll()
}
}, {
label: 'Show All',
click () {
actions.osxShowAll()
}
}, {
type: 'separator'
}, {
label: 'Quit MarkText',
accelerator: keybindings.getAccelerator('file.quit'),
click: app.quit
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/file.js | src/main/menu/templates/file.js | import { app } from 'electron'
import * as actions from '../actions/file'
import { userSetting } from '../actions/marktext'
import { isOsx } from '../../config'
export default function (keybindings, userPreference, recentlyUsedFiles) {
const { autoSave } = userPreference.getAll()
const fileMenu = {
label: '&File',
submenu: [{
label: 'New Tab',
accelerator: keybindings.getAccelerator('file.new-tab'),
click (menuItem, browserWindow) {
actions.newBlankTab(browserWindow)
}
}, {
label: 'New Window',
accelerator: keybindings.getAccelerator('file.new-window'),
click (menuItem, browserWindow) {
actions.newEditorWindow()
}
}, {
type: 'separator'
}, {
label: 'Open File...',
accelerator: keybindings.getAccelerator('file.open-file'),
click (menuItem, browserWindow) {
actions.openFile(browserWindow)
}
}, {
label: 'Open Folder...',
accelerator: keybindings.getAccelerator('file.open-folder'),
click (menuItem, browserWindow) {
actions.openFolder(browserWindow)
}
}]
}
if (!isOsx) {
const recentlyUsedMenu = {
label: 'Open Recent',
submenu: []
}
for (const item of recentlyUsedFiles) {
recentlyUsedMenu.submenu.push({
label: item,
click (menuItem, browserWindow) {
actions.openFileOrFolder(browserWindow, menuItem.label)
}
})
}
recentlyUsedMenu.submenu.push({
type: 'separator',
visible: recentlyUsedFiles.length > 0
}, {
label: 'Clear Recently Used',
enabled: recentlyUsedFiles.length > 0,
click (menuItem, browserWindow) {
actions.clearRecentlyUsed()
}
})
fileMenu.submenu.push(recentlyUsedMenu)
} else {
fileMenu.submenu.push({
role: 'recentdocuments',
submenu: [
{
role: 'clearrecentdocuments'
}
]
})
}
fileMenu.submenu.push({
type: 'separator'
}, {
label: 'Save',
accelerator: keybindings.getAccelerator('file.save'),
click (menuItem, browserWindow) {
actions.save(browserWindow)
}
}, {
label: 'Save As...',
accelerator: keybindings.getAccelerator('file.save-as'),
click (menuItem, browserWindow) {
actions.saveAs(browserWindow)
}
}, {
label: 'Auto Save',
type: 'checkbox',
checked: autoSave,
id: 'autoSaveMenuItem',
click (menuItem, browserWindow) {
actions.autoSave(menuItem, browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Move To...',
accelerator: keybindings.getAccelerator('file.move-file'),
click (menuItem, browserWindow) {
actions.moveTo(browserWindow)
}
}, {
label: 'Rename...',
accelerator: keybindings.getAccelerator('file.rename-file'),
click (menuItem, browserWindow) {
actions.rename(browserWindow)
}
}, {
type: 'separator'
}, {
label: 'Import...',
click (menuItem, browserWindow) {
actions.importFile(browserWindow)
}
}, {
label: 'Export',
submenu: [
{
label: 'HTML',
click (menuItem, browserWindow) {
actions.exportFile(browserWindow, 'styledHtml')
}
}, {
label: 'PDF',
click (menuItem, browserWindow) {
actions.exportFile(browserWindow, 'pdf')
}
}
]
}, {
label: 'Print',
accelerator: keybindings.getAccelerator('file.print'),
click (menuItem, browserWindow) {
actions.printDocument(browserWindow)
}
}, {
type: 'separator',
visible: !isOsx
}, {
label: 'Preferences...',
accelerator: keybindings.getAccelerator('file.preferences'),
visible: !isOsx,
click () {
userSetting()
}
}, {
type: 'separator'
}, {
label: 'Close Tab',
accelerator: keybindings.getAccelerator('file.close-tab'),
click (menuItem, browserWindow) {
actions.closeTab(browserWindow)
}
}, {
label: 'Close Window',
accelerator: keybindings.getAccelerator('file.close-window'),
click (menuItem, browserWindow) {
actions.closeWindow(browserWindow)
}
}, {
type: 'separator',
visible: !isOsx
}, {
label: 'Quit',
accelerator: keybindings.getAccelerator('file.quit'),
visible: !isOsx,
click: app.quit
})
return fileMenu
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/menu/templates/format.js | src/main/menu/templates/format.js | import * as actions from '../actions/format'
export default function (keybindings) {
return {
id: 'formatMenuItem',
label: 'F&ormat',
submenu: [{
id: 'strongMenuItem',
label: 'Bold',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.strong'),
click (menuItem, focusedWindow) {
actions.strong(focusedWindow)
}
}, {
id: 'emphasisMenuItem',
label: 'Italic',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.emphasis'),
click (menuItem, focusedWindow) {
actions.emphasis(focusedWindow)
}
}, {
id: 'underlineMenuItem',
label: 'Underline',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.underline'),
click (menuItem, focusedWindow) {
actions.underline(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'superscriptMenuItem',
label: 'Superscript',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.superscript'),
click (menuItem, focusedWindow) {
actions.superscript(focusedWindow)
}
}, {
id: 'subscriptMenuItem',
label: 'Subscript',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.subscript'),
click (menuItem, focusedWindow) {
actions.subscript(focusedWindow)
}
}, {
id: 'highlightMenuItem',
label: 'Highlight',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.highlight'),
click (menuItem, focusedWindow) {
actions.highlight(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'inlineCodeMenuItem',
label: 'Inline Code',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.inline-code'),
click (menuItem, focusedWindow) {
actions.inlineCode(focusedWindow)
}
}, {
id: 'inlineMathMenuItem',
label: 'Inline Math',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.inline-math'),
click (menuItem, focusedWindow) {
actions.inlineMath(focusedWindow)
}
}, {
type: 'separator'
}, {
id: 'strikeMenuItem',
label: 'Strikethrough',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.strike'),
click (menuItem, focusedWindow) {
actions.strikethrough(focusedWindow)
}
}, {
id: 'hyperlinkMenuItem',
label: 'Hyperlink',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.hyperlink'),
click (menuItem, focusedWindow) {
actions.hyperlink(focusedWindow)
}
}, {
id: 'imageMenuItem',
label: 'Image',
type: 'checkbox',
accelerator: keybindings.getAccelerator('format.image'),
click (menuItem, focusedWindow) {
actions.image(focusedWindow)
}
}, {
type: 'separator'
}, {
label: 'Clear Formatting',
accelerator: keybindings.getAccelerator('format.clear-format'),
click (menuItem, focusedWindow) {
actions.clearFormat(focusedWindow)
}
}]
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/keyboard/keybindingsLinux.js | src/main/keyboard/keybindingsLinux.js | // Key bindings for Linux.
// NOTE: Avoid `Ctrl+Alt` and `Alt` shortcuts on Linux because Ubuntu based OSs have reserved system shortcuts (see GH#2370).
// Binding shortcuts to these modifiers will result in odd behavior on Ubuntu.
// NOTE: Don't use `Ctrl+Shift+U` because it's used IBus for unicode support.
// NOTE: We can't determine the character for a dead key and no translation is provided. E.g. Ctrl+` (=Ctrl+Shift+´) on a
// none nodeadkeys german keyboard cannot be interpreted. In general don't bind default shortcuts to characters that
// can be produced with ^ or ` on any keyboard. --> ^, `, ", ~, ...
export default new Map([
// MarkText menu on macOS only
['mt.hide', ''],
['mt.hide-others', ''],
// File menu
['file.new-window', 'Ctrl+N'],
['file.new-tab', 'Ctrl+T'],
['file.open-file', 'Ctrl+O'],
['file.open-folder', 'Ctrl+Shift+O'],
['file.save', 'Ctrl+S'],
['file.save-as', 'Ctrl+Shift+S'],
['file.move-file', ''],
['file.rename-file', ''],
['file.print', ''],
['file.preferences', 'Ctrl+,'],
['file.close-tab', 'Ctrl+W'],
['file.close-window', 'Ctrl+Shift+W'],
['file.quit', 'Ctrl+Q'],
// Edit menu
['edit.undo', 'Ctrl+Z'],
['edit.redo', 'Ctrl+Shift+Z'],
['edit.cut', 'Ctrl+X'],
['edit.copy', 'Ctrl+C'],
['edit.paste', 'Ctrl+V'],
['edit.copy-as-markdown', 'Ctrl+Shift+C'],
['edit.copy-as-html', ''],
['edit.paste-as-plaintext', 'Ctrl+Shift+V'],
['edit.select-all', 'Ctrl+A'],
['edit.duplicate', 'Ctrl+Shift+E'],
['edit.create-paragraph', 'Ctrl+Shift+N'],
['edit.delete-paragraph', 'Ctrl+Shift+D'],
['edit.find', 'Ctrl+F'],
['edit.find-next', 'F3'],
['edit.find-previous', 'Shift+F3'],
['edit.replace', 'Ctrl+R'],
['edit.find-in-folder', 'Ctrl+Shift+F'],
['edit.screenshot', ''], // macOS only
// Paragraph menu
['paragraph.heading-1', 'Ctrl+Alt+1'],
['paragraph.heading-2', 'Ctrl+Alt+2'],
['paragraph.heading-3', 'Ctrl+Alt+3'],
['paragraph.heading-4', 'Ctrl+Alt+4'],
['paragraph.heading-5', 'Ctrl+Alt+5'],
['paragraph.heading-6', 'Ctrl+Alt+6'],
['paragraph.upgrade-heading', 'Ctrl+Plus'],
['paragraph.degrade-heading', 'Ctrl+-'],
['paragraph.table', 'Ctrl+Shift+T'],
['paragraph.code-fence', 'Ctrl+Shift+K'],
['paragraph.quote-block', 'Ctrl+Shift+Q'],
['paragraph.math-formula', 'Ctrl+Alt+M'],
['paragraph.html-block', 'Ctrl+Alt+H'],
['paragraph.order-list', 'Ctrl+G'],
['paragraph.bullet-list', 'Ctrl+H'],
['paragraph.task-list', 'Ctrl+Shift+X'],
['paragraph.loose-list-item', 'Ctrl+Shift+L'],
['paragraph.paragraph', 'Ctrl+Shift+0'],
['paragraph.horizontal-line', 'Ctrl+_'], // Ctrl+Shift+-
['paragraph.front-matter', 'Ctrl+Shift+Y'],
// Format menu
['format.strong', 'Ctrl+B'],
['format.emphasis', 'Ctrl+I'],
['format.underline', 'Ctrl+U'],
['format.superscript', ''],
['format.subscript', ''],
['format.highlight', 'Ctrl+Shift+H'],
['format.inline-code', 'Ctrl+Y'],
['format.inline-math', 'Ctrl+Shift+M'],
['format.strike', 'Ctrl+D'],
['format.hyperlink', 'Ctrl+L'],
['format.image', 'Ctrl+Shift+I'],
['format.clear-format', 'Ctrl+Shift+R'],
// Window menu
['window.minimize', 'Ctrl+M'],
['window.toggle-always-on-top', ''],
['window.zoom-in', ''],
['window.zoom-out', ''],
['window.toggle-full-screen', 'F11'],
// View menu
['view.command-palette', 'Ctrl+Shift+P'],
['view.source-code-mode', 'Ctrl+E'],
['view.typewriter-mode', 'Ctrl+Shift+G'],
['view.focus-mode', 'Ctrl+Shift+J'],
['view.toggle-sidebar', 'Ctrl+J'],
['view.toggle-toc', 'Ctrl+K'],
['view.toggle-tabbar', 'Ctrl+Shift+B'],
['view.toggle-dev-tools', 'Ctrl+Alt+I'],
['view.dev-reload', 'Ctrl+F5'],
['view.reload-images', 'F5'],
// ======== Not included in application menu ========================
['tabs.cycle-forward', 'Ctrl+Tab'],
['tabs.cycle-backward', 'Ctrl+Shift+Tab'],
['tabs.switch-to-left', 'Ctrl+PageUp'],
['tabs.switch-to-right', 'Ctrl+PageDown'],
['tabs.switch-to-first', 'Ctrl+1'],
['tabs.switch-to-second', 'Ctrl+2'],
['tabs.switch-to-third', 'Ctrl+3'],
['tabs.switch-to-fourth', 'Ctrl+4'],
['tabs.switch-to-fifth', 'Ctrl+5'],
['tabs.switch-to-sixth', 'Ctrl+6'],
['tabs.switch-to-seventh', 'Ctrl+7'],
['tabs.switch-to-eighth', 'Ctrl+8'],
['tabs.switch-to-ninth', 'Ctrl+9'],
['tabs.switch-to-tenth', 'Ctrl+0'],
['file.quick-open', 'Ctrl+P']
])
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/keyboard/keybindingsDarwin.js | src/main/keyboard/keybindingsDarwin.js | // Key bindings for macOS.
// NOTE: Avoid pure `Option` aka `Alt` shortcuts on macOS because these are used to produce alternative characters on all letters and digits.
// Our current key manager will forbid the usage of these key combinations too.
export default new Map([
// MarkText menu
['mt.hide', 'Command+H'],
['mt.hide-others', 'Command+Option+H'],
['file.preferences', 'Command+,'], // located under MarkText menu in macOS only
// File menu
['file.new-window', 'Command+N'],
['file.new-tab', 'Command+T'],
['file.open-file', 'Command+O'],
['file.open-folder', 'Command+Shift+O'],
['file.save', 'Command+S'],
['file.save-as', 'Command+Shift+S'],
['file.move-file', ''],
['file.rename-file', ''],
['file.print', ''],
['file.close-tab', 'Command+W'],
['file.close-window', 'Command+Shift+W'],
['file.quit', 'Command+Q'],
// Edit menu
['edit.undo', 'Command+Z'],
['edit.redo', 'Command+Shift+Z'],
['edit.cut', 'Command+X'],
['edit.copy', 'Command+C'],
['edit.paste', 'Command+V'],
['edit.copy-as-markdown', 'Command+Shift+C'],
['edit.copy-as-html', ''],
['edit.paste-as-plaintext', 'Command+Shift+V'],
['edit.select-all', 'Command+A'],
['edit.duplicate', 'Command+Option+D'],
['edit.create-paragraph', 'Shift+Command+N'],
['edit.delete-paragraph', 'Shift+Command+D'],
['edit.find', 'Command+F'],
['edit.find-next', 'Cmd+G'],
['edit.find-previous', 'Cmd+Shift+G'],
['edit.replace', 'Command+Option+F'],
['edit.find-in-folder', 'Shift+Command+F'],
['edit.screenshot', 'Command+Option+A'], // macOS only
// Paragraph menu
['paragraph.heading-1', 'Command+1'],
['paragraph.heading-2', 'Command+2'],
['paragraph.heading-3', 'Command+3'],
['paragraph.heading-4', 'Command+4'],
['paragraph.heading-5', 'Command+5'],
['paragraph.heading-6', 'Command+6'],
['paragraph.upgrade-heading', 'Command+Plus'],
['paragraph.degrade-heading', 'Command+-'],
['paragraph.table', 'Command+Shift+T'],
['paragraph.code-fence', 'Command+Option+C'],
['paragraph.quote-block', 'Command+Option+Q'],
['paragraph.math-formula', 'Command+Option+M'],
['paragraph.html-block', 'Command+Option+J'],
['paragraph.order-list', 'Command+Option+O'],
['paragraph.bullet-list', 'Command+Option+U'],
['paragraph.task-list', 'Command+Option+X'],
['paragraph.loose-list-item', 'Command+Option+L'],
['paragraph.paragraph', 'Command+0'],
['paragraph.horizontal-line', 'Command+Option+-'],
['paragraph.front-matter', 'Command+Option+Y'],
// Format menu
['format.strong', 'Command+B'],
['format.emphasis', 'Command+I'],
['format.underline', 'Command+U'],
['format.superscript', ''],
['format.subscript', ''],
['format.highlight', 'Shift+Command+H'],
['format.inline-code', 'Command+`'],
['format.inline-math', 'Shift+Command+M'],
['format.strike', 'Command+D'],
['format.hyperlink', 'Command+L'],
['format.image', 'Command+Shift+I'],
['format.clear-format', 'Shift+Command+R'],
// Window menu
['window.minimize', 'Command+M'],
['window.toggle-always-on-top', ''],
['window.zoom-in', ''],
['window.zoom-out', ''],
['window.toggle-full-screen', 'Ctrl+Command+F'],
// View menu
['view.command-palette', 'Command+Shift+P'],
['view.source-code-mode', 'Command+Option+S'],
['view.typewriter-mode', 'Command+Option+T'],
['view.focus-mode', 'Command+Shift+J'],
['view.toggle-sidebar', 'Command+J'],
['view.toggle-toc', 'Command+K'],
['view.toggle-tabbar', 'Command+Option+B'],
['view.toggle-dev-tools', 'Command+Option+I'],
['view.dev-reload', 'Command+Option+R'],
['view.reload-images', 'Command+R'],
// ======== Not included in application menu ========================
['tabs.cycle-forward', 'Ctrl+Tab'],
['tabs.cycle-backward', 'Ctrl+Shift+Tab'],
['tabs.switch-to-left', 'Command+PageUp'],
['tabs.switch-to-right', 'Command+PageDown'],
['tabs.switch-to-first', 'Ctrl+1'],
['tabs.switch-to-second', 'Ctrl+2'],
['tabs.switch-to-third', 'Ctrl+3'],
['tabs.switch-to-fourth', 'Ctrl+4'],
['tabs.switch-to-fifth', 'Ctrl+5'],
['tabs.switch-to-sixth', 'Ctrl+6'],
['tabs.switch-to-seventh', 'Ctrl+7'],
['tabs.switch-to-eighth', 'Ctrl+8'],
['tabs.switch-to-ninth', 'Ctrl+9'],
['tabs.switch-to-tenth', 'Ctrl+0'],
['file.quick-open', 'Command+P']
])
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/keyboard/index.js | src/main/keyboard/index.js | import { ipcMain, shell } from 'electron'
import log from 'electron-log'
import EventEmitter from 'events'
import fsPromises from 'fs/promises'
import { getCurrentKeyboardLayout, getKeyMap, onDidChangeKeyboardLayout } from 'native-keymap'
import os from 'os'
import path from 'path'
let currentKeyboardInfo = null
const loadKeyboardInfo = () => {
currentKeyboardInfo = {
layout: getCurrentKeyboardLayout(),
keymap: getKeyMap()
}
return currentKeyboardInfo
}
export const getKeyboardInfo = () => {
if (!currentKeyboardInfo) {
return loadKeyboardInfo()
}
return currentKeyboardInfo
}
const KEYBOARD_LAYOUT_MONITOR_CHANNEL_ID = 'onDidChangeKeyboardLayout'
class KeyboardLayoutMonitor extends EventEmitter {
constructor () {
super()
this._isSubscribed = false
this._emitTimer = null
}
addListener (callback) {
this._ensureNativeListener()
this.on(KEYBOARD_LAYOUT_MONITOR_CHANNEL_ID, callback)
}
removeListener (callback) {
this.removeListener(KEYBOARD_LAYOUT_MONITOR_CHANNEL_ID, callback)
}
_ensureNativeListener () {
if (!this._isSubscribed) {
this._isSubscribed = true
onDidChangeKeyboardLayout(() => {
// The keyboard layout change event may be emitted multiple times.
clearTimeout(this._emitTimer)
this._emitTimer = setTimeout(() => {
this.emit(KEYBOARD_LAYOUT_MONITOR_CHANNEL_ID, loadKeyboardInfo())
this._emitTimer = null
}, 150)
})
}
}
}
// Export a single-instance of the monitor.
export const keyboardLayoutMonitor = new KeyboardLayoutMonitor()
export const registerKeyboardListeners = () => {
ipcMain.handle('mt::keybinding-get-keyboard-info', async () => {
return getKeyboardInfo()
})
ipcMain.on('mt::keybinding-debug-dump-keyboard-info', async () => {
const dumpPath = path.join(os.tmpdir(), 'marktext_keyboard_info.json')
const content = JSON.stringify(getKeyboardInfo(), null, 2)
fsPromises.writeFile(dumpPath, content, 'utf8')
.then(() => {
console.log(`Keyboard information written to "${dumpPath}".`)
shell.openPath(dumpPath)
})
.catch(error => {
log.error('Error dumping keyboard information:', error)
})
})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/keyboard/shortcutHandler.js | src/main/keyboard/shortcutHandler.js | import { shell } from 'electron'
import fs from 'fs'
import fsPromises from 'fs/promises'
import path from 'path'
import log from 'electron-log'
import { electronLocalshortcut, isValidElectronAccelerator } from '@hfelix/electron-localshortcut'
import { isFile2 } from 'common/filesystem'
import { isEqualAccelerator } from 'common/keybinding'
import { isLinux, isOsx } from '../config'
import { getKeyboardInfo, keyboardLayoutMonitor } from '../keyboard'
import keybindingsDarwin from './keybindingsDarwin'
import keybindingsLinux from './keybindingsLinux'
import keybindingsWindows from './keybindingsWindows'
class Keybindings {
/**
* @param {CommandManager} commandManager The command manager instance.
* @param {AppEnvironment} appEnvironment The application environment instance.
*/
constructor (commandManager, appEnvironment) {
const { userDataPath } = appEnvironment.paths
this.configPath = path.join(userDataPath, 'keybindings.json')
this.commandManager = commandManager
this.userKeybindings = new Map()
this.keys = this.getDefaultKeybindings()
this._prepareKeyMapper()
if (appEnvironment.isDevMode) {
for (const [id, accelerator] of this.keys) {
if (!commandManager.has(id)) {
console.error(`[DEBUG] Command with id="${id}" isn't available for accelerator="${accelerator}".`)
}
}
}
// Load user-defined keybindings
this._loadLocalKeybindings()
}
getAccelerator (id) {
const name = this.keys.get(id)
if (!name) {
return null
}
return name
}
registerAccelerator (win, accelerator, callback) {
if (!win || !accelerator || !callback) {
throw new Error(`addKeyHandler: invalid arguments (accelerator="${accelerator}").`)
}
// Register shortcuts on the BrowserWindow instead of using Chromium's native menu.
// This makes it possible to receive key down events before Chromium/Electron and we
// can handle reserved Chromium shortcuts. Afterwards prevent the default action of
// the event so the native menu is not triggered.
electronLocalshortcut.register(win, accelerator, () => {
callback(win)
return true // prevent default action
})
}
unregisterAccelerator (win, accelerator) {
electronLocalshortcut.unregister(win, accelerator)
}
registerEditorKeyHandlers (win) {
for (const [id, accelerator] of this.keys) {
if (accelerator && accelerator.length > 1) {
this.registerAccelerator(win, accelerator, () => {
this.commandManager.execute(id, win)
})
}
}
}
openConfigInFileManager () {
const { configPath } = this
if (!isFile2(configPath)) {
fs.writeFileSync(configPath, '{\n\n\n}\n', 'utf-8')
}
shell.openPath(configPath)
.catch(err => console.error(err))
}
getDefaultKeybindings () {
if (isOsx) {
return keybindingsDarwin
} else if (isLinux) {
return keybindingsLinux
}
return keybindingsWindows
}
/**
* Returns all user key bindings.
*
* @returns {Map<String, String>} User key bindings.
*/
getUserKeybindings () {
return this.userKeybindings
}
/**
* Sets and saves the given user key bindings on disk.
*
* @param {Map<String, String>} userKeybindings New user key bindings.
* @returns {Promise<Boolean>}
*/
async setUserKeybindings (userKeybindings) {
this.userKeybindings = new Map(userKeybindings)
return this._saveUserKeybindings()
}
// --- private --------------------------------
_prepareKeyMapper () {
// Update the key mapper to prevent problems on non-US keyboards.
const { layout, keymap } = getKeyboardInfo()
electronLocalshortcut.setKeyboardLayout(layout, keymap)
// Notify key mapper when the keyboard layout was changed.
keyboardLayoutMonitor.addListener(({ layout, keymap }) => {
if (global.MARKTEXT_DEBUG && process.env.MARKTEXT_DEBUG_KEYBOARD) {
console.log('[DEBUG] Keyboard layout changed:\n', layout)
}
electronLocalshortcut.setKeyboardLayout(layout, keymap)
})
}
async _saveUserKeybindings () {
const { configPath, userKeybindings } = this
try {
const userKeybindingJson = JSON.stringify(Object.fromEntries(userKeybindings), null, 2)
await fsPromises.writeFile(configPath, userKeybindingJson, 'utf8')
return true
} catch (_) {
return false
}
}
_loadLocalKeybindings () {
if (global.MARKTEXT_SAFE_MODE || !isFile2(this.configPath)) {
return
}
const rawUserKeybindings = this._loadUserKeybindingsFromDisk()
if (!rawUserKeybindings) {
log.warn('Invalid keybinding configuration: failed to load or parse file.')
return
}
// keybindings.json example:
// {
// "file.save": "CmdOrCtrl+S",
// "file.save-as": "CmdOrCtrl+Shift+S"
// }
const userAccelerators = new Map()
for (const key in rawUserKeybindings) {
if (this.keys.has(key)) {
const value = rawUserKeybindings[key]
if (typeof value === 'string') {
if (value.length === 0) {
// Unset key
userAccelerators.set(key, '')
} else if (isValidElectronAccelerator(value)) {
userAccelerators.set(key, value)
} else {
console.error(`[WARNING] "${value}" is not a valid accelerator.`)
}
}
}
}
// Check for duplicate user shortcuts
for (const [keyA, valueA] of userAccelerators) {
for (const [keyB, valueB] of userAccelerators) {
if (valueA !== '' && keyA !== keyB && isEqualAccelerator(valueA, valueB)) {
const err = `Invalid keybindings.json configuration: Duplicate value for "${keyA}" and "${keyB}"!`
console.log(err)
log.error(err)
return
}
}
}
if (userAccelerators.size === 0) {
return
}
// Deep clone shortcuts
const accelerators = new Map(this.keys)
// Check for duplicate shortcuts
for (const [userKey, userValue] of userAccelerators) {
for (const [key, value] of accelerators) {
// This is a workaround to unset key bindings that the user used in `keybindings.json` before
// proper settings. Keep this for now, but add the ID to the users key binding that we show the
// right bindings in settings.
if (isEqualAccelerator(value, userValue)) {
// Unset default key
accelerators.set(key, '')
// This entry is actually unset because the user used the accelerator.
if (userAccelerators.get(key) == null) {
userAccelerators.set(key, '')
}
// A accelerator should only exist once in the default map.
break
}
}
accelerators.set(userKey, userValue)
}
// Update key bindings
this.keys = accelerators
// Save user keybindings for settings
this.userKeybindings = userAccelerators
}
_loadUserKeybindingsFromDisk () {
try {
const obj = JSON.parse(fs.readFileSync(this.configPath, 'utf8'))
if (typeof obj !== 'object') {
return null
}
return obj
} catch (_) {
return null
}
}
}
export default Keybindings
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/main/keyboard/keybindingsWindows.js | src/main/keyboard/keybindingsWindows.js | // Key bindings for Windows.
// NOTE: Avoid `Ctrl+Alt` and `AltGr` shortcuts on Windows because these are used to produce alternative characters.
// Unlike Linux, `Ctrl+Alt` is an alias to `AltGr` on Windows and will produce alternative characters too.
// We'll should try bind no keys to `Alt` "modifiers" because there are only a few key bindings available.
export default new Map([
// MarkText menu on macOS only
['mt.hide', ''],
['mt.hide-others', ''],
// File menu
['file.new-window', 'Ctrl+N'],
['file.new-tab', 'Ctrl+T'],
['file.open-file', 'Ctrl+O'],
['file.open-folder', 'Ctrl+Shift+O'],
['file.save', 'Ctrl+S'],
['file.save-as', 'Ctrl+Shift+S'],
['file.move-file', ''],
['file.rename-file', ''],
['file.print', ''],
['file.preferences', 'Ctrl+,'],
['file.close-tab', 'Ctrl+W'],
['file.close-window', 'Ctrl+Shift+W'],
['file.quit', 'Ctrl+Q'],
// Edit menu
['edit.undo', 'Ctrl+Z'],
['edit.redo', 'Ctrl+Shift+Z'],
['edit.cut', 'Ctrl+X'],
['edit.copy', 'Ctrl+C'],
['edit.paste', 'Ctrl+V'],
['edit.copy-as-markdown', 'Ctrl+Shift+C'],
['edit.copy-as-html', ''],
['edit.paste-as-plaintext', 'Ctrl+Shift+V'],
['edit.select-all', 'Ctrl+A'],
['edit.duplicate', 'Ctrl+Alt+D'],
['edit.create-paragraph', 'Ctrl+Shift+N'],
['edit.delete-paragraph', 'Ctrl+Shift+D'],
['edit.find', 'Ctrl+F'],
['edit.find-next', 'F3'],
['edit.find-previous', 'Shift+F3'],
['edit.replace', 'Ctrl+R'],
['edit.find-in-folder', 'Ctrl+Shift+F'],
['edit.screenshot', ''], // macOS only
// Paragraph menu
// NOTE: We cannot set a default value for heading size because `Ctrl+Alt` is an alias
// to `AltGr` on Windows and `Ctrl+Shift+1` is mapped to the underlying character.
['paragraph.heading-1', ''],
['paragraph.heading-2', ''],
['paragraph.heading-3', ''],
['paragraph.heading-4', ''],
['paragraph.heading-5', ''],
['paragraph.heading-6', ''],
['paragraph.upgrade-heading', 'Ctrl+Plus'],
['paragraph.degrade-heading', 'Ctrl+-'],
['paragraph.table', 'Ctrl+Shift+T'],
['paragraph.code-fence', 'Ctrl+Shift+K'],
['paragraph.quote-block', 'Ctrl+Shift+Q'],
['paragraph.math-formula', 'Ctrl+Alt+N'],
['paragraph.html-block', 'Ctrl+Alt+H'],
['paragraph.order-list', 'Ctrl+G'],
['paragraph.bullet-list', 'Ctrl+H'],
['paragraph.task-list', 'Ctrl+Alt+X'],
['paragraph.loose-list-item', 'Ctrl+Alt+L'],
['paragraph.paragraph', 'Ctrl+Shift+0'],
['paragraph.horizontal-line', 'Ctrl+Shift+U'],
['paragraph.front-matter', 'Ctrl+Alt+Y'],
// Format menu
['format.strong', 'Ctrl+B'],
['format.emphasis', 'Ctrl+I'],
['format.underline', 'Ctrl+U'],
['format.superscript', ''],
['format.subscript', ''],
['format.highlight', 'Ctrl+Shift+H'],
['format.inline-code', 'Ctrl+`'],
['format.inline-math', 'Ctrl+Shift+M'],
['format.strike', 'Ctrl+D'],
['format.hyperlink', 'Ctrl+L'],
['format.image', 'Ctrl+Shift+I'],
['format.clear-format', 'Ctrl+Shift+R'],
// Window menu
['window.minimize', 'Ctrl+M'],
['window.toggle-always-on-top', ''],
['window.zoom-in', ''],
['window.zoom-out', ''],
['window.toggle-full-screen', 'F11'],
// View menu
['view.command-palette', 'Ctrl+Shift+P'],
['view.source-code-mode', 'Ctrl+E'],
['view.typewriter-mode', 'Ctrl+Shift+G'],
['view.focus-mode', 'Ctrl+Shift+J'],
['view.toggle-sidebar', 'Ctrl+J'],
['view.toggle-toc', 'Ctrl+K'],
['view.toggle-tabbar', 'Ctrl+Shift+B'],
['view.toggle-dev-tools', 'Ctrl+Alt+I'],
['view.dev-reload', 'Ctrl+F5'],
['view.reload-images', 'F5'],
// ======== Not included in application menu ========================
['tabs.cycle-forward', 'Ctrl+Tab'],
['tabs.cycle-backward', 'Ctrl+Shift+Tab'],
['tabs.switch-to-left', 'Ctrl+PageUp'],
['tabs.switch-to-right', 'Ctrl+PageDown'],
['tabs.switch-to-first', 'Ctrl+1'],
['tabs.switch-to-second', 'Ctrl+2'],
['tabs.switch-to-third', 'Ctrl+3'],
['tabs.switch-to-fourth', 'Ctrl+4'],
['tabs.switch-to-fifth', 'Ctrl+5'],
['tabs.switch-to-sixth', 'Ctrl+6'],
['tabs.switch-to-seventh', 'Ctrl+7'],
['tabs.switch-to-eighth', 'Ctrl+8'],
['tabs.switch-to-ninth', 'Ctrl+9'],
['tabs.switch-to-tenth', 'Ctrl+0'],
['file.quick-open', 'Ctrl+P']
])
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/e2e/launch.spec.js | test/e2e/launch.spec.js | const { expect, test } = require('@playwright/test')
const { launchElectron } = require('./helpers')
test.describe('Check Launch MarkText', async () => {
let app = null
let page = null
test.beforeAll(async () => {
const { app: electronApp, page: firstPage } = await launchElectron()
app = electronApp
page = firstPage
})
test.afterAll(async () => {
await app.close()
})
test('Empty MarkText', async () => {
const title = await page.title()
expect(/^MarkText|Untitled-1 - MarkText$/.test(title)).toBeTruthy()
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/e2e/playwright.config.js | test/e2e/playwright.config.js | const config = {
workers: 1,
use: {
headless: false,
viewport: { width: 1280, height: 720 },
timeout: 30000
}
}
module.exports = config
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/e2e/xss.spec.js | test/e2e/xss.spec.js | const { expect, test } = require('@playwright/test')
const { launchElectron } = require('./helpers')
test.describe('Test XSS Vulnerabilities', async () => {
let app = null
let page = null
test.beforeAll(async () => {
const { app: electronApp, page: firstPage } = await launchElectron(['test/e2e/data/xss.md'])
app = electronApp
page = firstPage
// Wait to parse and render the document.
await new Promise((resolve) => setTimeout(resolve, 3000))
})
test.afterAll(async () => {
await app.close()
})
test('Load malicious document', async () => {
const { isVisible, isCrashed } = await app.evaluate(async process => {
const mainWindow = process.BrowserWindow.getAllWindows()[0]
return {
isVisible: mainWindow.isVisible(),
isCrashed: mainWindow.webContents.isCrashed()
}
})
expect(isVisible).toBeTruthy()
expect(isCrashed).toBeFalsy()
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/e2e/helpers.js | test/e2e/helpers.js | const os = require('os')
const path = require('path')
const { _electron } = require('playwright')
const mainEntrypoint = 'dist/electron/main.js'
const getDateAsFilename = () => {
const date = new Date()
return '' + date.getFullYear() + (date.getMonth() + 1) + date.getDay()
}
const getTempPath = () => {
const name = 'marktext-e2etest-' + getDateAsFilename()
return path.join(os.tmpdir(), name)
}
const getElectronPath = () => {
const launcherName = process.platform === 'win32' ? 'electron.cmd' : 'electron'
return path.resolve(path.join('node_modules', '.bin', launcherName))
}
const launchElectron = async userArgs => {
userArgs = userArgs || []
const executablePath = getElectronPath()
const args = [mainEntrypoint, '--user-data-dir', getTempPath()].concat(userArgs)
const app = await _electron.launch({
executablePath,
args,
timeout: 30000
})
const page = await app.firstWindow()
await page.waitForLoadState('domcontentloaded')
await new Promise((resolve) => setTimeout(resolve, 500))
return { app, page }
}
module.exports = { getElectronPath, launchElectron}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/index.js | test/unit/index.js | import Vue from 'vue'
Vue.config.devtools = false
Vue.config.productionTip = false
// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/)
testsContext.keys().forEach(testsContext)
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src/renderer', true, /^\.\/(?!main(\.js)?$).+\.(?:js|vue)$/)
srcContext.keys().forEach(srcContext)
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/markdown.js | test/unit/markdown.js | import fs from 'fs'
import path from 'path'
const loadMarkdownContent = pathname => {
// Load file and ensure LF line endings.
return fs.readFileSync(path.resolve('test/unit/data', pathname), 'utf-8').replace(/(?:\r\n|\n)/g, '\n')
}
export const BasicTextFormattingTemplate = () => {
return loadMarkdownContent('common/BasicTextFormatting.md')
}
export const BlockquotesTemplate= () => {
return loadMarkdownContent('common/Blockquotes.md')
}
export const CodeBlocksTemplate = () => {
return loadMarkdownContent('common/CodeBlocks.md')
}
export const EscapesTemplate = () => {
return loadMarkdownContent('common/Escapes.md')
}
export const HeadingsTemplate = () => {
return loadMarkdownContent('common/Headings.md')
}
export const ImagesTemplate = () => {
return loadMarkdownContent('common/Images.md')
}
export const LinksTemplate = () => {
return loadMarkdownContent('common/Links.md')
}
export const ListsTemplate = () => {
return loadMarkdownContent('common/Lists.md')
}
// --------------------------------------------------------
// GFM templates
//
export const GfmBasicTextFormattingTemplate = () => {
return loadMarkdownContent('gfm/BasicTextFormatting.md')
}
export const GfmListsTemplate = () => {
return loadMarkdownContent('gfm/Lists.md')
}
export const GfmTablesTemplate = () => {
return loadMarkdownContent('gfm/Tables.md')
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/karma.conf.js | test/unit/karma.conf.js | 'use strict'
const fs = require('fs')
const path = require('path')
const { merge } = require('webpack-merge')
const webpack = require('webpack')
const baseConfig = require('../../.electron-vue/webpack.renderer.config')
// Set BABEL_ENV to use proper preset config
process.env.BABEL_ENV = 'test'
// We need to create the build directory before launching Karma.
try {
fs.mkdirSync(path.join('dist', 'electron'), { recursive: true })
} catch(e) {
if (e.code !== 'EEXIST') {
throw e
}
}
let webpackConfig = merge(baseConfig, {
devtool: 'inline-source-map',
cache: false,
output: {
publicPath: '/'
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"development"'
})
]
})
// don't treat dependencies as externals
delete webpackConfig.entry
delete webpackConfig.externals
delete webpackConfig.output.libraryTarget
// BUG: TypeError: Cannot read property 'loaders' of undefined
// // apply vue option to apply isparta-loader on js
// webpackConfig.module.rules
// .find(rule => rule.use.loader === 'vue-loader').use.options.loaders.js = 'babel-loader'
module.exports = config => {
config.set({
browserNoActivityTimeout: 120000,
browserDisconnectTimeout: 60000,
browsers: ['CustomElectron'],
customLaunchers: {
CustomElectron: {
base: 'Electron',
browserWindowOptions: {
webPreferences: {
contextIsolation: false,
spellcheck: false,
nodeIntegration: true,
webSecurity: false,
sandbox: false
}
}
}
},
mode: 'development',
client: {
useIframe: false
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
},
frameworks: ['mocha', 'chai', 'webpack'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
reporters: ['spec', 'coverage'],
singleRun: true,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
}
})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/specs/markdown-footnotes.spec.js | test/unit/specs/markdown-footnotes.spec.js | import { Lexer } from '../../../src/muya/lib/parser/marked'
const parseMarkdown = markdown => {
const lexer = new Lexer({
disableInline: true,
footnote: true
})
return lexer.lex(markdown)
}
const convertToken = token => {
const obj = {}
for (const key of Object.keys(token)) {
obj[key] = token[key]
}
return obj
}
const convertTokens = tokenList => {
const tokens = []
for (const token of tokenList) {
tokens.push(convertToken(token))
}
return tokens
}
// ----------------------------------------------------------------------------
describe('Markdown Footnotes', () => {
it('Footnote according pandoc specification', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^1]' },
{ type: 'space' },
{ type: 'footnote_start', identifier: '1' },
{ type: 'paragraph', text: 'foo' },
{ type: 'footnote_end' }
]
const markdown =
`foo[^1]
[^1]: foo`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote according pandoc specification with more text', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy[^1] eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: '1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy[^1] eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
[^1]: At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with text as tag', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]: At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote without space between footnote tag and text', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with non-ASCII text', () => {
const expected = [
{ type: 'paragraph', text: '掲応自情表使[^掲応自情表]供業辞金打論将' },
{ type: 'space' },
{ type: 'footnote_start', identifier: '掲応自情表' },
{ type: 'paragraph', text: '別率重帰更科申会前後度計' },
{ type: 'footnote_end' }
]
const markdown =
`掲応自情表使[^掲応自情表]供業辞金打論将
[^掲応自情表]: 別率重帰更科申会前後度計`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with non-ASCII text as tag', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^掲応自情表] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: '掲応自情表' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^掲応自情表] sadipscing elitr.
[^掲応自情表]: At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with text in next paragraph', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with text in next line', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with inline text and text in next paragraph', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.' },
{ type: 'space' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]: Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with multiline text in next paragraphs', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'space' },
{ type: 'paragraph', text: 'Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with multiline text in next line and paragraph', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'space' },
{ type: 'paragraph', text: 'Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with multiline text and list elements', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'space' },
{ type: 'list_start', ordered: false, listType: 'bullet', start: '' },
{ checked: undefined, listItemType: 'bullet', bulletMarkerOrDelimiter: '-', type: 'list_item_start' },
{ type: 'text', text: 'list element 1' },
{ type: 'list_item_end' },
{ checked: undefined, listItemType: 'bullet', bulletMarkerOrDelimiter: '-', type: 'list_item_start' },
{ type: 'text', text: 'list element 2' },
{ type: 'list_item_end' },
{ checked: undefined, listItemType: 'bullet', bulletMarkerOrDelimiter: '-', type: 'list_item_start' },
{ type: 'text', text: 'list element 2' },
{ type: 'space' },
{ type: 'list_item_end' },
{ type: 'list_end' },
{ type: 'paragraph', text: 'Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!
- list element 1
- list element 2
- list element 2
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with multiline text and code block', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'space' },
{ type: 'code', codeBlockStyle: 'fenced', lang: '', text: 'code block text' },
{ type: 'paragraph', text: 'Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]:
At vero eos et accusam et justo duo dolores et ea rebum!
\`\`\`
code block text
\`\`\`
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote with prefix is not a footnote', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'paragraph', text: 'a[^foo1]: At vero eos et accusam et justo duo dolores et ea rebum!' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
a[^foo1]: At vero eos et accusam et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote inside paragraph is not a footnote', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'paragraph', text: 'At vero eos et accusam [^foo1]: et justo duo dolores et ea rebum!' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
At vero eos et accusam [^foo1]: et justo duo dolores et ea rebum!`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote is paragraph if escaped (front)', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^1]' },
{ type: 'space' },
{ type: 'paragraph', text: '\\[^1]: foo' }
]
const markdown =
`foo[^1]
\\[^1]: foo`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Footnote is paragraph if escaped (back)', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^1]' },
{ type: 'space' },
{ type: 'paragraph', text: '[^1\\]: foo' }
]
const markdown =
`foo[^1]
[^1\\]: foo`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
it('Invalid footenote token', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^1]' },
{ type: 'space' },
{ type: 'paragraph', text: '[ ^1]: foo' }
]
const markdown =
`foo[^1]
[ ^1]: foo`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
})
// These tests depend on the parsing style.
describe('Markdown Footnotes (*)', () => {
// // TODO: This should be a footnote according pandoc but no specification details available.
// it('Empty footnotes should be a footnote without content', () => {
// const expected = [
// { type: 'paragraph', text: 'foo[^foo1]' },
// { type: 'space' },
// { type: 'footnote_start', identifier: 'foo1' },
// { type: 'footnote_end' }
// ]
// const markdown =
// `foo[^foo1]
//
// [^foo1]:`
//
// const tokens = parseTokens(markdown)
// expect(convertTokens(tokens)).to.deep.equal(expected)
// })
it('Empty footnotes with newline should be a footnote without content', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^foo1]' },
{ type: 'space' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'footnote_end' }
]
const markdown =
`foo[^foo1]
[^foo1]:
`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
// According to pandoc the following test is correct but it seems wrong. Why do we
// consume `aaaaaa` as footnote content?
it('Strange footnote content', () => {
const expected = [
{ type: 'paragraph', text: 'foo[^foo1]' },
{ type: 'space' },
{ type: 'space' },
{ type: 'paragraph', text: 'bbbbbb' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'aaaaaa' },
{ type: 'footnote_end' }
]
const markdown =
`foo[^foo1]
[^foo1]:
aaaaaa
bbbbbb
`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
// NOTE: Currently all footnotes are moved to the bottom of the document.
it('Footnote should end on normal paragraph', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'space' }, // TODO: Double space seems to be wrong due to reordering?
{ type: 'paragraph', text: 'Sed diam nonumy eirmod tempor.' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.' },
{ type: 'space' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]: Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
At vero eos et accusam et justo duo dolores et ea rebum!
Sed diam nonumy eirmod tempor.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
// NOTE: Currently all footnotes are moved to the bottom of the document.
it('Footnote should end on wrong indentation', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'space' },
{ type: 'paragraph', text: ' Sed diam nonumy eirmod tempor.' },
{ type: 'footnote_start', identifier: 'foo1' },
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.' },
{ type: 'space' },
{ type: 'paragraph', text: 'At vero eos et accusam et justo duo dolores et ea rebum!' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^foo1] sadipscing elitr.
[^foo1]: Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
At vero eos et accusam et justo duo dolores et ea rebum!
Sed diam nonumy eirmod tempor.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
// NOTE: Missing footnotes should be ignored according specification, but MarkText have to
// display even incomplete footnotes. The user should be able to edit and use these.
it('Footnotes should be always reported', () => {
const expected = [
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur[^1] sadipscing elitr.' },
{ type: 'space' },
{ type: 'footnote_start', identifier: '2' },
{ type: 'paragraph', text: 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr.' },
{ type: 'footnote_end' }
]
const markdown =
`Lorem ipsum dolor sit amet, consetetur[^1] sadipscing elitr.
[^2]: Lorem ipsum dolor sit amet, consetetur sadipscing elitr.`
const tokens = parseMarkdown(markdown)
expect(convertTokens(tokens)).to.deep.equal(expected)
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/specs/markdown-basic.spec.js | test/unit/specs/markdown-basic.spec.js | import ContentState from '../../../src/muya/lib/contentState'
import EventCenter from '../../../src/muya/lib/eventHandler/event'
import ExportMarkdown from '../../../src/muya/lib/utils/exportMarkdown'
import { MUYA_DEFAULT_OPTION } from '../../../src/muya/lib/config'
import * as templates from '../markdown'
const defaultOptions = { endOfLine: 'lf' }
const defaultOptionsCrlf = Object.assign({}, defaultOptions, { endOfLine: 'crlf' })
const createMuyaContext = options => {
const ctx = {}
ctx.options = Object.assign({}, MUYA_DEFAULT_OPTION, options)
ctx.eventCenter = new EventCenter()
ctx.contentState = new ContentState(ctx, ctx.options)
return ctx
}
// ----------------------------------------------------------------------------
// Muya parser (Markdown to HTML to Markdown)
//
const verifyMarkdown = (markdown, options) => {
const ctx = createMuyaContext(options)
ctx.contentState.importMarkdown(markdown)
const blocks = ctx.contentState.getBlocks()
const exportedMarkdown = new ExportMarkdown(blocks).generate()
// FIXME: We always need to add a new line at the end of the document. Add a option to disable the new line.
// Muya always use LF line endings.
expect(exportedMarkdown).to.equal(markdown)
}
describe('Muya parser', () => {
it('Basic Text Formatting', () => {
verifyMarkdown(templates.BasicTextFormattingTemplate(), defaultOptions)
})
it('Blockquotes', () => {
verifyMarkdown(templates.BlockquotesTemplate(), defaultOptions)
})
it('Code Blocks', () => {
verifyMarkdown(templates.CodeBlocksTemplate(), defaultOptions)
})
it('Escapes', () => {
verifyMarkdown(templates.EscapesTemplate(), defaultOptions)
})
it('Headings', () => {
verifyMarkdown(templates.HeadingsTemplate(), defaultOptions)
})
it('Images', () => {
verifyMarkdown(templates.ImagesTemplate(), defaultOptions)
})
it('Links', () => {
verifyMarkdown(templates.LinksTemplate(), defaultOptions)
})
it('Lists', () => {
verifyMarkdown(templates.ListsTemplate(), defaultOptions)
})
it('GFM - Basic Text Formatting', () => {
verifyMarkdown(templates.GfmBasicTextFormattingTemplate(), defaultOptions)
})
it('GFM - Lists', () => {
verifyMarkdown(templates.GfmListsTemplate(), defaultOptions)
})
it('GFM - Tables', () => {
verifyMarkdown(templates.GfmTablesTemplate(), defaultOptions)
})
})
describe('Muya parser (CRLF)', () => {
it('Basic Text Formatting', () => {
verifyMarkdown(templates.BasicTextFormattingTemplate(), defaultOptionsCrlf)
})
it('Blockquotes', () => {
verifyMarkdown(templates.BlockquotesTemplate(), defaultOptionsCrlf)
})
it('Code Blocks', () => {
verifyMarkdown(templates.CodeBlocksTemplate(), defaultOptionsCrlf)
})
it('Escapes', () => {
verifyMarkdown(templates.EscapesTemplate(), defaultOptionsCrlf)
})
it('Headings', () => {
verifyMarkdown(templates.HeadingsTemplate(), defaultOptionsCrlf)
})
it('Images', () => {
verifyMarkdown(templates.ImagesTemplate(), defaultOptionsCrlf)
})
it('Links', () => {
verifyMarkdown(templates.LinksTemplate(), defaultOptionsCrlf)
})
it('Lists', () => {
verifyMarkdown(templates.ListsTemplate(), defaultOptionsCrlf)
})
it('GFM - Basic Text Formatting', () => {
verifyMarkdown(templates.GfmBasicTextFormattingTemplate(), defaultOptionsCrlf)
})
it('GFM - Lists', () => {
verifyMarkdown(templates.GfmListsTemplate(), defaultOptionsCrlf)
})
it('GFM - Tables', () => {
verifyMarkdown(templates.GfmTablesTemplate(), defaultOptionsCrlf)
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/specs/extract-word.spec.js | test/unit/specs/extract-word.spec.js | import { extractWord } from '../../../src/muya/lib/marktext/spellchecker.js'
const basicCheck = 'Lorem ipsum dolor'
const basicText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce pharetra turpis in ante viverra, sit amet euismod tortor rutrum. Sed eu libero velit. Aliquam erat volutpat. Sed ullamcorper ultricies auctor. Vestibulum vitae odio eleifend, finibus justo a, vestibulum orci.'
const basicMdText = '**Lorem** ipsum ~~dolor~~ sit <sub>amet</sub>, ----- **** **虥諰諨** consectetur adipiscing elit.'
const nonAscii = '虥諰 鯦鯢鯡 媓幁惁 墏, 邆錉霋 鱐鱍鱕 銪 鈌鈅, 韎餀 骱 噮噦噞 虥諰諨 樆樦潏 蝺 嬔嬚嬞 脬舑莕 騩鰒...'
const buildResult = (left, right, word) => {
return { left, right, word }
}
const test = (text, offset, expectedWord) => {
const wordInfo = extractWord(text, offset)
if (expectedWord !== wordInfo && (
expectedWord.left !== wordInfo.left ||
expectedWord.right !== wordInfo.right ||
expectedWord.word !== wordInfo.word
)) {
// NOTE: Always invalid.
expect(expectedWord).to.equal(wordInfo)
}
}
describe('Test extractWord', () => {
it('Basic - Invalid text', () => {
test(null, 0, null)
})
it('Basic - Empty text', () => {
test('', 0, null)
})
it('Basic - Invalid offset 1', () => {
test(basicCheck, -182, buildResult(0, 5, 'Lorem'))
})
it('Basic - Invalid offset 2', () => {
test(basicCheck, undefined, null)
})
it('Basic - Invalid offset 3', () => {
test(basicCheck, 478343, buildResult(12, 17, 'dolor'))
})
it('Get first word', () => {
test(basicText, 0, buildResult(0, 5, 'Lorem'))
})
it('Get second word', () => {
test(basicText, 8, buildResult(6, 11, 'ipsum'))
})
it('Get last word', () => {
test(basicText, 268, buildResult(266, 270, 'orci'))
})
it('Last character is not a valid word', () => {
test(basicText, 271, null)
})
it('Get custom index (1)', () => {
test(basicText, 79, buildResult(79, 81, 'in'))
})
it('Get custom index (2)', () => {
console.log(basicText[104], basicText[105], basicText[106])
test(basicText, 106, buildResult(105, 112, 'euismod'))
})
it('Markdown - Get first word', () => {
test(basicMdText, 2, buildResult(2, 7, 'Lorem'))
})
it('Markdown - Get second word', () => {
test(basicMdText, 14, buildResult(10, 15, 'ipsum'))
})
it('Markdown - Get custom index (1)', () => {
test(basicMdText, 20, buildResult(18, 23, 'dolor'))
})
it('Markdown - Get custom index (2)', () => {
test(basicMdText, 37, buildResult(35, 39, 'amet'))
})
it('Markdown - Not valid word', () => {
test(basicMdText, 50, null)
})
it('Markdown - Not valid word', () => {
test(basicMdText, 55, null)
})
it('Markdown - Valid non-ASCII word', () => {
test(basicMdText, 61, buildResult(60, 63, '虥諰諨'))
})
it('Non-ASCII - Get first word', () => {
test(nonAscii, 0, buildResult(0, 2, '虥諰'))
})
it('Non-ASCII - Get second word', () => {
test(nonAscii, 4, buildResult(3, 6, '鯦鯢鯡'))
})
it('Non-ASCII - Get last word', () => {
test(nonAscii, 56, buildResult(55, 57, '騩鰒'))
})
it('Non-ASCII - Last character is not a valid word', () => {
test(nonAscii, 58, null)
})
it('Non-ASCII - Get custom index', () => {
test(nonAscii, 19, buildResult(18, 21, '鱐鱍鱕'))
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/specs/markdown-list-indentation.spec.js | test/unit/specs/markdown-list-indentation.spec.js | import ContentState from '../../../src/muya/lib/contentState'
import EventCenter from '../../../src/muya/lib/eventHandler/event'
import ExportMarkdown from '../../../src/muya/lib/utils/exportMarkdown'
import { MUYA_DEFAULT_OPTION } from '../../../src/muya/lib/config'
const createMuyaContext = listIdentation => {
const ctx = {}
ctx.options = Object.assign({}, MUYA_DEFAULT_OPTION, { listIdentation })
ctx.eventCenter = new EventCenter()
ctx.contentState = new ContentState(ctx, ctx.options)
return ctx
}
// ----------------------------------------------------------------------------
// Muya parser (Markdown to HTML to Markdown)
//
const verifyMarkdown = (expectedMarkdown, listIdentation, markdown = '') => {
if (!markdown) {
markdown = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
141. foo
1. foo
`
}
const ctx = createMuyaContext(listIdentation)
ctx.contentState.importMarkdown(markdown)
const blocks = ctx.contentState.getBlocks()
const exportedMarkdown = new ExportMarkdown(blocks, listIdentation).generate()
expect(exportedMarkdown).to.equal(expectedMarkdown)
}
describe('Muya list identation', () => {
it('Indent by 1 space', () => {
const md = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
141. foo
1. foo
`
verifyMarkdown(md, 1)
})
it('Indent by 2 spaces', () => {
const md = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
141. foo
1. foo
`
verifyMarkdown(md, 2)
})
it('Indent by 3 spaces', () => {
const md = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
141. foo
1. foo
`
verifyMarkdown(md, 3)
})
it('Indent by 4 spaces', () => {
const md = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
141. foo
1. foo
`
verifyMarkdown(md, 4)
})
/* it('Indent by one tab', () => {
const md = `start
- foo
- foo
\t- foo
\t- foo
\t\t- foo
\t\t- foo
\t\t\t- foo
\t- foo
- foo
sep
1. foo
2. foo
\t1. foo
\t2. foo
\t\t1. foo
\t3. foo
3. foo
\t20. foo
\t\t141. foo
\t\t\t1. foo
`
verifyMarkdown(md, "tab")
}) */
it('Indent using Daring Fireball Markdown Spec', () => {
const md = `start
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
- foo
sep
1. foo
2. foo
1. foo
2. foo
1. foo
3. foo
3. foo
20. foo
99. foo
1. foo
`
verifyMarkdown(md, 'dfm', md)
})
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/unit/specs/match-electron-accelerator.spec.js | test/unit/specs/match-electron-accelerator.spec.js | import { isEqualAccelerator } from 'common/keybinding'
const characterKeys = [
'0',
'1',
'9',
'A',
'b',
'G',
'Z',
'~',
'!',
'@',
'#'
]
const nonCharacterKeys = [
'F1',
'F5',
'F24',
'Plus',
'Space',
'Tab',
'Backspace',
'Delete',
'Insert',
'Return',
'Enter',
'Up',
'Down',
'Left',
'Right',
'Home',
'End',
'PageUp',
'PageDown',
'Escape',
'Esc',
'VolumeUp',
'VolumeDown',
'VolumeMute',
'MediaNextTrack',
'MediaPreviousTrack',
'MediaStop',
'MediaPlayPause',
'PrintScreen'
]
const keys = [...characterKeys, ...nonCharacterKeys]
const modifiers = [
'Command',
'Cmd',
'Control',
'Ctrl',
'CommandOrControl',
'CmdOrCtrl',
'Alt',
'Option',
'AltGr',
'Shift'
]
describe('Test equal with non characte key', () => {
it('Match F2', () => {
expect(isEqualAccelerator('F2', 'F2')).to.equal(true)
})
it('Match F10', () => {
expect(isEqualAccelerator('F10', 'F10')).to.equal(true)
})
it('Match PageUp', () => {
expect(isEqualAccelerator('PageUp', 'PageUp')).to.equal(true)
})
it('Match Tab', () => {
expect(isEqualAccelerator('Tab', 'Tab')).to.equal(true)
})
it('Mismatch F2 and F3', () => {
expect(isEqualAccelerator('F2', 'F3')).to.equal(false)
})
it('Mismatch Left and Down', () => {
expect(isEqualAccelerator('Left', 'Down')).to.equal(false)
})
it('Mismatch F1 and 1', () => {
expect(isEqualAccelerator('F1', '1')).to.equal(false)
})
it('Mismatch F2 and Ctrl+F2', () => {
expect(isEqualAccelerator('F2', 'Ctrl+F2')).to.equal(false)
})
})
describe('Test equal with basis keys', () => {
it('Match Ctrl+A', () => {
expect(isEqualAccelerator('Ctrl+A', 'A+Ctrl')).to.equal(true)
})
it('Match case insensitive with multiple modifiers', () => {
expect(isEqualAccelerator('Ctrl+Alt+A', 'ctrl+alt+a')).to.equal(true)
})
it('Match case insensitive with multiple modifiers and upper-case letter', () => {
expect(isEqualAccelerator('Ctrl+Shift+A', 'ctrl+shift+A')).to.equal(true)
})
it('Match mixed case with multiple modifiers', () => {
expect(isEqualAccelerator('Ctrl+a+shift', 'ctrl+Shift+a')).to.equal(true)
})
})
describe('Test not equal with basis keys', () => {
it('Mismatch Ctrl+A', () => {
expect(isEqualAccelerator('Ctrl+A', 'A+Ctrl+Alt')).to.equal(false)
})
it('Mismatch case insensitive with multiple modifiers', () => {
expect(isEqualAccelerator('Ctrl+A', 'ctrl+alt+a')).to.equal(false)
})
it('Mismatch letters only', () => {
expect(isEqualAccelerator('a', 'b')).to.equal(false)
})
it('Mismatch same modifiers but different key', () => {
expect(isEqualAccelerator('Ctrl+a+shift', 'ctrl+Shift+b')).to.equal(false)
})
})
describe('Test invalid accelerator', () => {
it('Ctrl+', () => {
expect(isEqualAccelerator('Ctrl+', 'Ctrl+Plus')).to.equal(false)
})
it('Ctrl++', () => {
expect(isEqualAccelerator('Ctrl++', 'Ctrl+Plus')).to.equal(false)
})
it('Emtpy accelerator 1', () => {
expect(isEqualAccelerator('', 'Ctrl+A')).to.equal(false)
})
it('Emtpy accelerator 2', () => {
expect(isEqualAccelerator('ctrl+Shift+b', '')).to.equal(false)
})
})
describe('Match combination for modifier and key', () => {
modifiers.forEach(mod =>
keys.forEach(key => {
it(`Should match ${mod}+${key}`, () => {
expect(isEqualAccelerator(`${mod}+${key}`, `${key}+${mod}`)).to.equal(true)
})
})
)
})
describe('Match non-character keys', () => {
nonCharacterKeys.forEach(nonCharacterKey =>
it(`Should match ${nonCharacterKey}`, () => {
expect(isEqualAccelerator(`${nonCharacterKey}`, `${nonCharacterKey}`)).to.equal(true)
})
)
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/specs/help.js | test/specs/help.js | export const removeCustomClass = html => {
const customClass = ['indented-code-block', 'fenced-code-block', 'task-list-item']
customClass.forEach(className => {
if (html.indexOf(className) > -1) {
const REG_EXP = new RegExp(`class="${className}"`, 'g')
/* eslint-disable no-useless-escape */
const REG_EXP_SIMPLE = new RegExp(className + ' \*', 'g')
/* eslint-enable no-useless-escape */
html = html.replace(REG_EXP, '')
.replace(REG_EXP_SIMPLE, '')
}
})
return html
}
export const padding = (str, len, marker = ' ') => {
const spaceLen = len - str.length
let preLen = 0
let postLen = 0
if (spaceLen % 2 === 0) {
preLen = postLen = spaceLen / 2
} else {
preLen = (spaceLen - 1) / 2
postLen = (spaceLen + 1) / 2
}
return marker.repeat(preLen) + str + marker.repeat(postLen)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/specs/config.js | test/specs/config.js | export const MT_MARKED_OPTIONS = Object.freeze({
headerIds: false,
emoji: false,
math: false,
frontMatter: false
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/specs/gfm/run.spec.js | test/specs/gfm/run.spec.js | // This file is copy from https://github.com/markedjs/marked/blob/master/test/specs/gfm/getSpecs.js
// And for custom use.
import { removeCustomClass } from '../help'
import { writeResult } from '../commonMark/run.spec'
import { MT_MARKED_OPTIONS } from '../config'
const fetch = require('node-fetch')
const cheerio = require('cheerio')
const marked = require('../../../src/muya/lib/parser/marked/index.js').default
const HtmlDiffer = require('@markedjs/html-differ').HtmlDiffer
const fs = require('fs')
const path = require('path')
const options = { ignoreSelfClosingSlash: true, ignoreAttributes: ['id', 'class'] }
const htmlDiffer = new HtmlDiffer(options)
const getSpecs = () => {
return fetch('https://github.github.com/gfm/')
.then(res => res.text())
.then(html => cheerio.load(html))
.then($ => {
const version = $('.version').text().match(/\d+\.\d+/)[0]
if (!version) {
throw new Error('No version found')
}
const specs = []
$('.extension').each((i, ext) => {
const section = $('.definition', ext).text().trim().replace(/^\d+\.\d+(.*?) \(extension\)[\s\S]*$/, '$1')
$('.example', ext).each((j, exa) => {
const example = +$(exa).attr('id').replace(/\D/g, '')
const markdown = $('.language-markdown', exa).text().trim()
const html = $('.language-html', exa).text().trim()
specs.push({
section,
html,
markdown,
example
})
})
})
return [version, specs]
})
}
const getMarkedSpecs = async (version) => {
return fetch(`https://raw.githubusercontent.com/markedjs/marked/master/test/specs/gfm/gfm.${version}.json`)
.then(res => res.json())
}
const diffAndGenerateResult = async () => {
const [version, specs] = await getSpecs()
const markedSpecs = await getMarkedSpecs(version)
specs.forEach(spec => {
const html = removeCustomClass(marked(spec.markdown, MT_MARKED_OPTIONS))
if (!htmlDiffer.isEqual(html, spec.html)) {
spec.shouldFail = true
}
})
fs.writeFileSync(path.resolve(__dirname, `./gfm.${version}.json`), JSON.stringify(specs, null, 2) + '\n')
writeResult(version, specs, markedSpecs, 'gfm')
}
try {
diffAndGenerateResult()
} catch (err) {
console.log(err)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/test/specs/commonMark/run.spec.js | test/specs/commonMark/run.spec.js | // This file is copy from marked and modified.
import { removeCustomClass, padding } from '../help'
import { MT_MARKED_OPTIONS } from '../config'
const fetch = require('node-fetch')
const markedJs = require('marked')
const marked = require('../../../src/muya/lib/parser/marked/index.js').default
const HtmlDiffer = require('@markedjs/html-differ').HtmlDiffer
const fs = require('fs')
const path = require('path')
const options = { ignoreSelfClosingSlash: true, ignoreAttributes: ['id', 'class'] }
const htmlDiffer = new HtmlDiffer(options)
const getSpecs = async () => {
const version = await fetch('https://raw.githubusercontent.com/commonmark/commonmark.js/master/package.json')
.then(res => res.json())
.then(pkg => pkg.version.replace(/^(\d+\.\d+).*$/, '$1'))
return fetch(`https://spec.commonmark.org/${version}/spec.json`)
.then(res => res.json())
.then(specs => ({ specs, version }))
}
const getMarkedSpecs = async (version) => {
return fetch(`https://raw.githubusercontent.com/markedjs/marked/master/test/specs/commonmark/commonmark.${version}.json`)
.then(res => res.json())
}
export const writeResult = (version, specs, markedSpecs, type = 'commonmark') => {
let result = '## Test Result\n\n'
const totalCount = specs.length
const failedCount = specs.filter(s => s.shouldFail).length
const classifiedResult = {}
for (const spec of specs) {
const { example, section, shouldFail } = spec
const item = classifiedResult[section]
if (item) {
item.count++
if (shouldFail) {
item.failed++
item.failedExamples.push(example)
}
} else {
classifiedResult[section] = {
count: 1,
failed: 0,
failedExamples: []
}
if (shouldFail) {
classifiedResult[section].failed++
classifiedResult[section].failedExamples.push(example)
}
}
}
result += `Total test ${totalCount} examples, and failed ${failedCount} examples:\n\n`
// |section|failed/total|percentage|
const sectionMaxLen = Math.max(...Object.keys(classifiedResult).map(key => key.length))
const failedTotalLen = 15
const percentageLen = 15
result += `|${padding('Section', sectionMaxLen)}|${padding('Failed/Total', failedTotalLen)}|${padding('Percentage', percentageLen)}|\n`
result += `|${padding('-'.repeat(sectionMaxLen - 2), sectionMaxLen, ':')}|${padding('-'.repeat(failedTotalLen - 2), failedTotalLen, ':')}|${padding('-'.repeat(percentageLen - 2), percentageLen, ':')}|\n`
for (const key of Object.keys(classifiedResult)) {
const { count, failed } = classifiedResult[key]
result += `|${padding(key, sectionMaxLen)}`
result += `|${padding(failed + '/' + count, failedTotalLen)}`
result += `|${padding(((count - failed) / count * 100).toFixed(2) + '%', percentageLen)}|\n`
}
result += '\n'
specs.filter(s => s.shouldFail)
.forEach(spec => {
const expectedHtml = spec.html
const acturalHtml = marked(spec.markdown, MT_MARKED_OPTIONS)
result += `**Example${spec.example}**\n\n`
result += '```markdown\n'
result += 'Markdown content\n'
result += `${spec.markdown.replace(/`/g, '\\`')}\n`
result += 'Expected Html\n'
result += `${expectedHtml}\n`
result += 'Actural Html\n'
result += `${acturalHtml}\n`
result += '```\n\n'
})
const failedPath = type === 'commonmark' ? `./${type}.${version}.md` : `../gfm/${type}.${version}.md`
fs.writeFileSync(path.join(__dirname, failedPath), result)
// compare with markedjs
let compareResult = '## Compare with `marked.js`\n\n'
compareResult += `Marked.js failed examples count: ${markedSpecs.filter(s => s.shouldFail).length}\n`
compareResult += `MarkText failed examples count: ${failedCount}\n\n`
let count = 0
specs.forEach((spec, i) => {
if (spec.shouldFail !== markedSpecs[i].shouldFail) {
count++
const acturalHtml = marked(spec.markdown, MT_MARKED_OPTIONS)
compareResult += `**Example${spec.example}**\n\n`
compareResult += `MarkText ${spec.shouldFail ? 'fail' : 'success'} and marked.js ${markedSpecs[i].shouldFail ? 'fail' : 'success'}\n\n`
compareResult += '```markdown\n'
compareResult += 'Markdown content\n'
compareResult += `${spec.markdown.replace(/`/g, '\\`')}\n`
compareResult += 'Expected Html\n'
compareResult += `${spec.html}\n`
compareResult += 'Actural Html\n'
compareResult += `${acturalHtml}\n`
compareResult += 'marked.js html\n'
compareResult += `${markedJs(spec.markdown, { headerIds: false })}\n`
compareResult += '```\n\n'
}
})
compareResult += `There are ${count} examples are different with marked.js.`
const comparePath = type === 'commonmark' ? './compare.marked.md' : '../gfm/compare.marked.md'
fs.writeFileSync(path.join(__dirname, comparePath), compareResult)
}
const diffAndGenerateResult = async () => {
const { specs, version } = await getSpecs()
const markedSpecs = await getMarkedSpecs(version)
specs.forEach(spec => {
const html = removeCustomClass(marked(spec.markdown, MT_MARKED_OPTIONS))
if (!htmlDiffer.isEqual(html, spec.html)) {
spec.shouldFail = true
}
})
fs.writeFileSync(path.join(__dirname, `./commonmark.${version}.json`), JSON.stringify(specs, null, 2) + '\n')
writeResult(version, specs, markedSpecs, 'commonmark')
}
try {
diffAndGenerateResult()
} catch (err) {
console.log(err)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/postinstall.js | .electron-vue/postinstall.js | 'use strict'
const fs = require('fs')
const path = require('path')
// WORKAROUND: Fix slow startup time on Windows due to blocking powershell call(s) in windows-release.
// Replace the problematic file with our "fixed" version.
const windowsReleasePath = path.resolve(__dirname, '../node_modules/windows-release')
if (fs.existsSync(windowsReleasePath)) {
const windowsReleaseJson = path.join(windowsReleasePath, 'package.json')
const packageJson = JSON.parse(fs.readFileSync(windowsReleaseJson, { encoding : 'utf-8' }))
const windowsReleaseMajor = Number(packageJson.version.match(/^(\d+)\./)[1])
if (windowsReleaseMajor >= 5) {
console.error('[ERROR] "windows-release" workaround failed because version is >=5.\n')
process.exit(1)
}
const srcPath = path.resolve(__dirname, '../resources/build/windows-release.js')
const destPath = path.join(windowsReleasePath, 'index.js')
fs.copyFileSync(srcPath, destPath)
}
// WORKAROUND: electron-builder downloads the wrong prebuilt architecture on macOS and the reason is unknown.
// For now, we rebuild all native libraries from source.
const keytarPath = path.resolve(__dirname, '../node_modules/keytar')
if (process.platform === 'darwin' && fs.existsSync(keytarPath)) {
const keytarPackageJsonPath = path.join(keytarPath, 'package.json')
let packageText = fs.readFileSync(keytarPackageJsonPath, { encoding : 'utf-8' })
packageText = packageText.replace(/"install": "prebuild-install \|\| npm run build",/i, '"install": "npm run build",')
fs.writeFileSync(keytarPackageJsonPath, packageText, { encoding : 'utf-8' })
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/dev-client.js | .electron-vue/dev-client.js | const hotClient = require('webpack-hot-middleware/client?reload=true')
hotClient.subscribe(event => {
/**
* Reload browser when HTMLWebpackPlugin emits a new index.html
*
* Currently disabled until jantimon/html-webpack-plugin#680 is resolved.
* https://github.com/SimulatedGREG/electron-vue/issues/437
* https://github.com/jantimon/html-webpack-plugin/issues/680
*/
// if (event.action === 'reload') {
// window.location.reload()
// }
/**
* Notify `mainWindow` when `main` process is compiling,
* giving notice for an expected reload of the `electron` process
*/
if (event.action === 'compiling') {
document.body.innerHTML += `
<style>
#dev-client {
background: #4fc08d;
border-radius: 4px;
bottom: 20px;
box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
color: #fff;
font-family: 'Source Sans Pro', sans-serif;
left: 20px;
padding: 8px 12px;
position: absolute;
}
</style>
<div id="dev-client">
Compiling Main Process...
</div>
`
}
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/webpack.renderer.config.js | .electron-vue/webpack.renderer.config.js | 'use strict'
process.env.BABEL_ENV = 'renderer'
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const SpritePlugin = require('svg-sprite-loader/plugin')
const postcssPresetEnv = require('postcss-preset-env')
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const ESLintPlugin = require('eslint-webpack-plugin')
const { getRendererEnvironmentDefinitions } = require('./marktextEnvironment')
const { dependencies } = require('../package.json')
const isProduction = process.env.NODE_ENV === 'production'
/**
* List of node_modules to include in webpack bundle
* Required for specific packages like Vue UI libraries
* that provide pure *.vue files that need compiling
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/webpack-configurations.html#white-listing-externals
*/
const whiteListedModules = ['vue']
/** @type {import('webpack').Configuration} */
const rendererConfig = {
mode: 'development',
devtool: 'eval-cheap-module-source-map',
optimization: {
emitOnErrors: false
},
infrastructureLogging: {
level: 'warn',
},
entry: {
renderer: path.join(__dirname, '../src/renderer/main.js')
},
externals: [
...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d))
],
module: {
rules: [
{
test: require.resolve(path.join(__dirname, '../src/muya/lib/assets/libs/snap.svg-min.js')),
use: 'imports-loader?this=>window,fix=>module.exports=0'
},
{
test: /\.vue$/,
use: {
loader: 'vue-loader',
options: {
sourceMap: true
}
}
},
{
test: /(theme\-chalk(?:\/|\\)index|exportStyle|katex|github\-markdown|prism[\-a-z]*|\.theme|headerFooterStyle)\.css$/,
use: [
'to-string-loader',
'css-loader'
]
},
{
test: /\.css$/,
exclude: /(theme\-chalk(?:\/|\\)index|exportStyle|katex|github\-markdown|prism[\-a-z]*|\.theme|headerFooterStyle)\.css$/,
use: [
isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 }
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
postcssPresetEnv({ stage: 0 })
],
},
}
}
]
},
{
test: /\.html$/,
use: 'vue-html-loader'
},
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true
}
}
],
exclude: /node_modules/
},
{
test: /\.node$/,
loader: 'node-loader',
options: {
name: '[name].[ext]'
}
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-sprite-loader',
options: {
extract: true,
publicPath: './static/'
}
},
'svgo-loader'
]
},
{
test: /\.(png|jpe?g|gif)(\?.*)?$/,
type: 'asset',
generator: {
filename: 'images/[name].[contenthash:8][ext]'
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
type: 'asset/resource',
generator: {
filename: 'media/[name].[contenthash:8][ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
type: 'asset/resource',
generator: {
filename: 'fonts/[name].[contenthash:8][ext]'
}
},
{
test: /\.md$/,
type: 'asset/source'
}
]
},
node: {
__dirname: !isProduction,
__filename: !isProduction
},
plugins: [
new ESLintPlugin({
cache: !isProduction,
extensions: ['js', 'vue'],
files: [
'src',
'test'
],
exclude: [
'node_modules'
],
emitError: true,
failOnError: true,
// NB: Threads must be disabled, otherwise no errors are emitted.
threads: false,
formatter: require('eslint-friendly-formatter'),
context: path.resolve(__dirname, '../'),
overrideConfigFile: '.eslintrc.js'
}),
new SpritePlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
minifyJS: true,
minifyCSS: true
},
isBrowser: false,
isDevelopment: !isProduction,
nodeModules: !isProduction
? path.resolve(__dirname, '../node_modules')
: false
}),
new webpack.DefinePlugin(getRendererEnvironmentDefinitions()),
// Use node http request instead axios's XHR adapter.
new webpack.NormalModuleReplacementPlugin(
/.+[\/\\]node_modules[\/\\]axios[\/\\]lib[\/\\]adapters[\/\\]xhr\.js$/,
'http.js'
),
new VueLoaderPlugin()
],
cache: false,
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: path.join(__dirname, '../dist/electron'),
assetModuleFilename: 'assets/[name].[contenthash:8][ext]',
asyncChunks: true
},
resolve: {
alias: {
'main': path.join(__dirname, '../src/main'),
'@': path.join(__dirname, '../src/renderer'),
'common': path.join(__dirname, '../src/common'),
'muya': path.join(__dirname, '../src/muya'),
snapsvg: path.join(__dirname, '../src/muya/lib/assets/libs/snap.svg-min.js'),
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['.js', '.vue', '.json', '.css', '.node']
},
target: 'electron-renderer'
}
/**
* Adjust rendererConfig for development settings
*/
if (!isProduction) {
rendererConfig.cache = { type: 'memory' }
// NOTE: Caching between builds is currently not possible because all SVGs are invalid on second build due to svgo-loader.
// rendererConfig.cache = {
// name: 'renderer-dev',
// type: 'filesystem'
// }
rendererConfig.plugins.push(
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"`
})
)
}
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' &&
!process.env.MARKTEXT_DEV_HIDE_BROWSER_ANALYZER) {
rendererConfig.plugins.push(
new BundleAnalyzerPlugin()
)
}
// Fix debugger breakpoints
if (!isProduction && process.env.MARKTEXT_BUILD_VSCODE_DEBUG) {
rendererConfig.devtool = 'inline-source-map'
}
/**
* Adjust rendererConfig for production settings
*/
if (isProduction) {
rendererConfig.devtool = 'nosources-source-map'
rendererConfig.mode = 'production'
rendererConfig.optimization.minimize = true
rendererConfig.plugins.push(
new webpack.DefinePlugin({
'process.env.UNSPLASH_ACCESS_KEY': JSON.stringify(process.env.UNSPLASH_ACCESS_KEY)
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].[contenthash].css',
chunkFilename: '[id].[contenthash].css'
}),
new CopyWebpackPlugin({
patterns: [
{
from: path.join(__dirname, '../static'),
to: path.join(__dirname, '../dist/electron/static'),
globOptions: {
ignore: ['.*']
}
},
{
from: path.resolve(__dirname, '../node_modules/codemirror/mode/*/*').replace(/\\/g, '/'),
to: path.join(__dirname, '../dist/electron/codemirror/mode/[name]/[name][ext]')
}
]
})
)
}
module.exports = rendererConfig
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/thirdPartyChecker.js | .electron-vue/thirdPartyChecker.js | 'use strict'
const checker = require('license-checker')
const getLicenses = (rootDir, callback) => {
checker.init({
start: rootDir,
production: true,
development: false,
direct: true,
excludePackages: '[email protected]', // file-icons is under MIT License, but license-checker shows no license.
json: true,
onlyAllow: 'Unlicense;WTFPL;ISC;MIT;BSD;ISC;Apache-2.0;MIT*;Apache;Apache*;BSD*;CC0-1.0;CC-BY-4.0;CC-BY-3.0',
customPath: {
licenses: '',
licenseText: 'none'
}
}, function (err, packages) {
callback(err, packages, checker)
})
}
// Check that all production dependencies are allowed.
const validateLicenses = rootDir => {
getLicenses(rootDir, (err, packages, checker) => {
if (err) {
console.log(`[ERROR] ${err}`)
process.exit(1)
}
console.log(checker.asSummary(packages))
})
}
module.exports = {
getLicenses: getLicenses,
validateLicenses: validateLicenses
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/build.js | .electron-vue/build.js | 'use strict'
process.env.NODE_ENV = 'production'
const { say } = require('cfonts')
const path = require('path')
const chalk = require('chalk')
const del = require('del')
const fs = require('fs-extra')
const webpack = require('webpack')
const Listr = require('listr')
const mainConfig = require('./webpack.main.config')
const rendererConfig = require('./webpack.renderer.config')
const doneLog = chalk.bgGreen.white(' DONE ') + ' '
const errorLog = chalk.bgRed.white(' ERROR ') + ' '
const okayLog = chalk.bgBlue.white(' OKAY ') + ' '
const isCI = process.env.CI || false
if (process.env.BUILD_TARGET === 'clean') clean()
else if (process.env.BUILD_TARGET === 'web') web()
else build()
function clean () {
del.sync(['build/*', '!build/icons', '!build/icons/icon.*'])
console.log(`\n${doneLog}\n`)
process.exit()
}
async function build () {
greeting()
del.sync(['dist/electron/*', '!.gitkeep'])
del.sync(['static/themes/*'])
const from = path.resolve(__dirname, '../src/muya/themes')
const to = path.resolve(__dirname, '../static/themes')
await fs.copy(from, to)
let results = ''
const tasks = new Listr(
[
{
title: 'building main process',
task: async () => {
await pack(mainConfig)
.then(result => {
results += result + '\n\n'
})
.catch(err => {
console.log(`\n ${errorLog}failed to build main process`)
console.error(`\n${err}\n`)
process.exit(1)
})
}
},
{
title: 'building renderer process',
task: async () => {
await pack(rendererConfig)
.then(result => {
results += result + '\n\n'
})
.catch(err => {
console.log(`\n ${errorLog}failed to build renderer process`)
console.error(`\n${err}\n`)
process.exit(1)
})
}
}
],
{ concurrent: 2 }
)
await tasks
.run()
.then(() => {
process.stdout.write('\x1B[2J\x1B[0f')
console.log(`\n\n${results}`)
console.log(`${okayLog}take it away ${chalk.yellow('`electron-builder`')}\n`)
process.exit()
})
.catch(err => {
process.exit(1)
})
}
function pack (config) {
return new Promise((resolve, reject) => {
webpack(config, (err, stats) => {
if (err) reject(err.stack || err)
else if (stats.hasErrors()) {
let err = ''
stats.toString({
chunks: false,
colors: true
})
.split(/\r?\n/)
.forEach(line => {
err += ` ${line}\n`
})
reject(err)
} else {
resolve(stats.toString({
chunks: false,
colors: true
}))
}
})
})
}
function greeting () {
const cols = process.stdout.columns
let text = ''
if (cols > 155) text = 'building marktext'
else if (cols > 76) text = 'building|marktext'
else text = false
if (text && !isCI) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else {
console.log(chalk.yellow.bold('\n building marktext'))
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/marktextEnvironment.js | .electron-vue/marktextEnvironment.js | const { GitRevisionPlugin } = require('git-revision-webpack-plugin')
const { version } = require('../package.json')
const getEnvironmentDefinitions = function () {
let shortHash = 'N/A'
let fullHash = 'N/A'
try {
const gitRevisionPlugin = new GitRevisionPlugin()
shortHash = gitRevisionPlugin.version()
fullHash = gitRevisionPlugin.commithash()
} catch(_) {
// Ignore error if we build without git.
}
const isStableRelease = !!process.env.MARKTEXT_IS_STABLE
const versionSuffix = isStableRelease ? '' : ` (${shortHash})`
return {
'global.MARKTEXT_GIT_SHORT_HASH': JSON.stringify(shortHash),
'global.MARKTEXT_GIT_HASH': JSON.stringify(fullHash),
'global.MARKTEXT_VERSION': JSON.stringify(version),
'global.MARKTEXT_VERSION_STRING': JSON.stringify(`v${version}${versionSuffix}`),
'global.MARKTEXT_IS_STABLE': JSON.stringify(isStableRelease)
}
}
const getRendererEnvironmentDefinitions = function () {
const env = getEnvironmentDefinitions()
return {
'process.versions.MARKTEXT_VERSION': env['global.MARKTEXT_VERSION'],
'process.versions.MARKTEXT_VERSION_STRING': env['global.MARKTEXT_VERSION_STRING'],
}
}
module.exports = {
getEnvironmentDefinitions: getEnvironmentDefinitions,
getRendererEnvironmentDefinitions: getRendererEnvironmentDefinitions
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/preinstall.js | .electron-vue/preinstall.js | 'use strict'
const nodeMajor = Number(process.versions.node.match(/^(\d+)\./)[1])
if (nodeMajor < 14) {
console.error('[ERROR] Node.js v14 or above is required.\n')
process.exit(1)
}
if (!/yarn\.js$/.test(process.env.npm_execpath)) {
console.error('[ERROR] Please use yarn to install dependencies.\n')
process.exit(1)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/dev-runner.js | .electron-vue/dev-runner.js | 'use strict'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackDevServer = require('webpack-dev-server')
const webpackHotMiddleware = require('webpack-hot-middleware')
const mainConfig = require('./webpack.main.config')
const rendererConfig = require('./webpack.renderer.config')
let electronProcess = null
let manualRestart = false
let hotMiddleware
function logStats (proc, data) {
let log = ''
log += chalk.yellow.bold(`┏ ${proc} Process ${new Array((19 - proc.length) + 1).join('-')}`)
log += '\n\n'
if (typeof data === 'object') {
data.toString({
colors: true,
chunks: false
}).split(/\r?\n/).forEach(line => {
log += ' ' + line + '\n'
})
} else {
log += ` ${data}\n`
}
log += '\n' + chalk.yellow.bold(`┗ ${new Array(28 + 1).join('-')}`) + '\n'
console.log(log)
}
function startRenderer () {
return new Promise((resolve, reject) => {
rendererConfig.entry.renderer = [path.join(__dirname, 'dev-client')].concat(rendererConfig.entry.renderer)
const compiler = webpack(rendererConfig)
hotMiddleware = webpackHotMiddleware(compiler, {
log: false,
heartbeat: 2500
})
compiler.hooks.compilation.tap('HtmlWebpackPluginAfterEmit', compilation => {
HtmlWebpackPlugin.getHooks(compilation).afterEmit.tapAsync(
'AfterPlugin',
(data, cb) => {
hotMiddleware.publish({ action: 'reload' })
// Tell webpack to move on
cb(null, data)
}
)
})
compiler.hooks.done.tap('AfterCompiler', stats => {
logStats('Renderer', stats)
})
const server = new WebpackDevServer({
host: '127.0.0.1',
port: 9091,
hot: true,
liveReload: true,
compress: true,
static: [
{
directory: path.join(__dirname, '../node_modules/codemirror/mode'),
publicPath: '/codemirror/mode',
watch: false
}
],
onBeforeSetupMiddleware ({ app, middleware }) {
app.use(hotMiddleware)
middleware.waitUntilValid(() => {
resolve()
})
}
}, compiler)
server.start()
})
}
function startMain () {
return new Promise((resolve, reject) => {
mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main)
const compiler = webpack(mainConfig)
compiler.hooks.watchRun.tapAsync('Compiling', (_, done) => {
logStats('Main', chalk.white.bold('compiling...'))
hotMiddleware.publish({ action: 'compiling' })
done()
})
compiler.watch({}, (err, stats) => {
if (err) {
console.log(err)
return
}
logStats('Main', stats)
if (electronProcess && electronProcess.kill) {
manualRestart = true
process.kill(electronProcess.pid)
electronProcess = null
startElectron()
setTimeout(() => {
manualRestart = false
}, 5000)
}
resolve()
})
})
}
function startElectron () {
electronProcess = spawn(electron, [
'--inspect=5858',
'--remote-debugging-port=8315',
'--nolazy',
path.join(__dirname, '../dist/electron/main.js')
])
electronProcess.stdout.on('data', data => {
electronLog(data, 'blue')
})
electronProcess.stderr.on('data', data => {
electronLog(data, 'red')
})
electronProcess.on('close', () => {
if (!manualRestart) process.exit()
})
}
function electronLog (data, color) {
let log = ''
data = data.toString().split(/\r?\n/)
data.forEach(line => {
log += ` ${line}\n`
})
if (/[0-9A-z]+/.test(log)) {
console.log(
chalk[color].bold('┏ Electron -------------------') +
'\n\n' +
log +
chalk[color].bold('┗ ----------------------------') +
'\n'
)
}
}
function greeting () {
const cols = process.stdout.columns
let text = ''
if (cols > 155) text = 'building marktext'
else if (cols > 76) text = 'building|marktext'
else text = false
if (text) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else {
console.log(chalk.yellow.bold('\n building marktext'))
}
console.log(chalk.blue(' getting ready...') + '\n')
}
function init () {
greeting()
Promise.all([startRenderer(), startMain()])
.then(() => {
startElectron()
})
.catch(err => {
console.error(err)
})
}
init()
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.electron-vue/webpack.main.config.js | .electron-vue/webpack.main.config.js | 'use strict'
process.env.BABEL_ENV = 'main'
const path = require('path')
const webpack = require('webpack')
const ESLintPlugin = require('eslint-webpack-plugin')
const { getEnvironmentDefinitions } = require('./marktextEnvironment')
const { dependencies } = require('../package.json')
const isProduction = process.env.NODE_ENV === 'production'
/** @type {import('webpack').Configuration} */
const mainConfig = {
mode: 'development',
devtool: 'eval-cheap-module-source-map',
optimization: {
emitOnErrors: false
},
entry: {
main: path.join(__dirname, '../src/main/index.js')
},
externals: [
...Object.keys(dependencies || {})
],
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.node$/,
loader: 'node-loader',
options: {
name: '[name].[ext]'
}
}
]
},
node: {
__dirname: !isProduction,
__filename: !isProduction
},
cache: false,
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: path.join(__dirname, '../dist/electron')
},
plugins: [
new ESLintPlugin({
extensions: ['js'],
files: [
'src',
'test'
],
exclude: [
'node_modules'
],
emitError: true,
failOnError: true,
// NB: Threads must be disabled, otherwise no errors are emitted.
threads: false,
formatter: require('eslint-friendly-formatter'),
context: path.resolve(__dirname, '../'),
overrideConfigFile: '.eslintrc.js'
}),
// Add global environment definitions.
new webpack.DefinePlugin(getEnvironmentDefinitions())
],
resolve: {
alias: {
'common': path.join(__dirname, '../src/common')
},
extensions: ['.js', '.json', '.node']
},
target: 'electron-main'
}
// Fix debugger breakpoints
if (!isProduction && process.env.MARKTEXT_BUILD_VSCODE_DEBUG) {
mainConfig.devtool = 'inline-source-map'
}
/**
* Adjust mainConfig for development settings
*/
if (!isProduction) {
mainConfig.cache = {
name: 'main-dev',
type: 'filesystem'
}
mainConfig.plugins.push(
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"`
})
)
}
/**
* Adjust mainConfig for production settings
*/
if (isProduction) {
mainConfig.devtool = 'nosources-source-map'
mainConfig.mode = 'production'
mainConfig.optimization.minimize = true
}
module.exports = mainConfig
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/resources/build/windows-release.js | resources/build/windows-release.js | // MIT License
//
// Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const os = require('os');
// const execa = require('execa');
// Reference: https://www.gaijin.at/en/lstwinver.php
// Windows 11 reference: https://docs.microsoft.com/en-us/windows/release-health/windows11-release-information
const names = new Map([
['10.0.22', '11'], // It's unclear whether future Windows 11 versions will use this version scheme: https://github.com/sindresorhus/windows-release/pull/26/files#r744945281
['10.0', '10'],
['6.3', '8.1'],
['6.2', '8'],
['6.1', '7'],
['6.0', 'Vista'],
['5.2', 'Server 2003'],
['5.1', 'XP'],
['5.0', '2000'],
['4.90', 'ME'],
['4.10', '98'],
['4.03', '95'],
['4.00', '95'],
]);
const windowsRelease = release => {
const version = /(\d+\.\d+)(?:\.(\d+))?/.exec(release || os.release());
if (release && !version) {
throw new Error('`release` argument doesn\'t match `n.n`');
}
let ver = version[1] || '';
const build = version[2] || '';
// // Server 2008, 2012, 2016, and 2019 versions are ambiguous with desktop versions and must be detected at runtime.
// // If `release` is omitted or we're on a Windows system, and the version number is an ambiguous version
// // then use `wmic` to get the OS caption: https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx
// // If `wmic` is obsoloete (later versions of Windows 10), use PowerShell instead.
// // If the resulting caption contains the year 2008, 2012, 2016 or 2019, it is a server version, so return a server OS name.
// if ((!release || release === os.release()) && ['6.1', '6.2', '6.3', '10.0'].includes(ver)) {
// let stdout;
// try {
// stdout = execa.sync('powershell', ['(Get-CimInstance -ClassName Win32_OperatingSystem).caption']).stdout || '';
// } catch (_) {
// stdout = execa.sync('wmic', ['os', 'get', 'Caption']).stdout || '';
// }
//
// const year = (stdout.match(/2008|2012|2016|2019/) || [])[0];
//
// if (year) {
// return `Server ${year}`;
// }
// }
// Windows 11
if (ver === '10.0' && build.startsWith('22')) {
ver = '10.0.22';
}
return names.get(ver);
};
module.exports = windowsRelease;
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/genReadme.js | genReadme.js | const fs = require("fs/promises");
const path = require("path");
const Fm = require("front-matter");
const Toc = require("markdown-toc");
const prettier = require("prettier");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const repositoryRootPath = __dirname;
const readmePath = path.resolve(repositoryRootPath, "./README.md");
/**
* level of the heading under which the generated content is displayed
*/
const baseHeadingLevel = 2;
const defaultOptions = {
withKey: "title",
withToc: false,
showHeading: true,
relativeHeadingLevel: 2,
tabLevel: 1,
prefix: "",
suffix: "",
};
async function readContentFromPath(relativePath) {
let MdDoc = await fs.readFile(path.join(repositoryRootPath, relativePath), {
encoding: "utf8",
});
let MdContent = Fm(MdDoc.toString());
let TableOfContents = Toc(MdContent.body).content;
return {
frontmatter: MdContent.attributes,
body: MdContent.body,
toc: TableOfContents,
};
}
async function updateSectionWith(options) {
const {
from,
relativeHeadingLevel,
name,
path,
prefix,
showHeading,
suffix,
tabLevel,
to,
withKey,
withToc,
} = { ...defaultOptions, ...options };
let md = await readContentFromPath(path);
let oldFences = getFenceForSection(from, name);
let fenceOptions = {
name,
content: md,
tabLevel,
relativeHeadingLevel,
showHeading,
withKey,
prefix,
suffix,
};
let newFences = generateContentForSection({
...fenceOptions,
withToc: false,
});
let oldTocFences = getFenceForSection(from, name, true);
let newTocFences = generateContentForSection({
...fenceOptions,
withToc: true,
});
let updatedContents = to.replace(oldFences.regex, newFences);
updatedContents = updatedContents.replace(oldTocFences.regex, newTocFences);
if (withToc)
console.log(
`✅ 🗜️ Rewrote Table of Contents for '${md.frontmatter.title}'`
);
console.log(`✅ 📝 Rewrote Section for '${md.frontmatter.title}'`);
return updatedContents;
}
/**
* Adjusts the headings in the given `markdown` to be in a given heading context.
* Headings must start in a line.
* Preceding whitespace or any other character will result in the heading not being recognized.
*
* @example `withHeadingContext(2, '# Heading') === '### Heading'`
* @param {number} relativeHeadingLevel
* @param {string} markdown
*/
function withHeadingContext(relativeHeadingLevel, markdown) {
return markdown.replaceAll(/^(#+)/gm, (match, markdownHeadingTokens) => {
return "#".repeat(markdownHeadingTokens.length + relativeHeadingLevel);
});
}
function generateContentForSection(options) {
const {
content,
relativeHeadingLevel,
name,
prefix,
showHeading,
suffix,
tabLevel,
withKey,
withToc,
} = {
...defaultOptions,
...options,
};
let fence = getFence(name, withToc);
let fenceContent = fence.start + "\n";
if (withToc) {
let lines = content.toc.split("\n");
for (let i = 0, len = lines.length; i < len; i += 1)
fenceContent +=
" ".repeat(tabLevel) + lines[i] + (i !== len - 1 ? "\n" : "");
} else {
fenceContent += showHeading
? `${"#".repeat(baseHeadingLevel + relativeHeadingLevel)} ` +
prefix +
content.frontmatter[withKey] +
suffix +
"\n\n"
: "";
fenceContent += withHeadingContext(baseHeadingLevel, content.body) + "\n";
}
fenceContent += fence.end;
return fenceContent;
}
function getFenceForSection(readme, sectionName, isToc = false) {
try {
let fence = getFence(sectionName, isToc);
let regex = new RegExp(`(${fence.start}[\\s\\S]+${fence.end})`, "gm");
return { regex: regex, content: regex.exec(readme.content) };
} catch (err) {
console.error(
`🚨 You've encountered a ${err.name} ➜ ${err.message} \n` +
`💡 ProTip ➜ Please ensure the comments exist and are separated by a newline.`
);
console.error({ readme, sectionName });
console.error(err);
}
}
function getFence(sectionName, isToc = false) {
let name = isToc ? sectionName + "-toc" : sectionName;
let START_COMMENT = "<!--START-SECTION:" + name + "-->";
let END_COMMENT = "<!--END-SECTION:" + name + "-->";
return { start: START_COMMENT, end: END_COMMENT };
}
async function main(argv) {
let currentReadme = await fs.readFile(readmePath, { encoding: "utf-8" });
let pendingReadme = currentReadme;
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "setup",
path: "docs/basic/setup.md",
withToc: true,
relativeHeadingLevel: 1,
prefix: "Section 1: ",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "basic-type-examples",
path: "docs/basic/getting-started/basic-type-examples.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "function-components",
path: "docs/basic/getting-started/function-components.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "hooks",
path: "docs/basic/getting-started/hooks.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "class-components",
path: "docs/basic/getting-started/class-components.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "default-props",
path: "docs/basic/getting-started/default-props.md",
showHeading: false,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "forms-and-events",
path: "docs/basic/getting-started/forms-and-events.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "context",
path: "docs/basic/getting-started/context.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "forward-create-ref",
path: "docs/basic/getting-started/forward-create-ref.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "portals",
path: "docs/basic/getting-started/portals.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "error-boundaries",
path: "docs/basic/getting-started/error-boundaries.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "concurrent",
path: "docs/basic/getting-started/concurrent.md",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "types",
path: "docs/basic/troubleshooting/types.md",
withToc: true,
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "operators",
path: "docs/basic/troubleshooting/operators.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "utilities",
path: "docs/basic/troubleshooting/utilities.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "ts-config",
path: "docs/basic/troubleshooting/ts-config.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "official-typings-bugs",
path: "docs/basic/troubleshooting/official-typings-bugs.md",
relativeHeadingLevel: 1,
withKey: "sidebar_label",
prefix: "Troubleshooting Handbook: ",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "non-ts-files",
path: "docs/basic/troubleshooting/non-ts-files.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "non-ts-files",
path: "docs/basic/troubleshooting/non-ts-files.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "editor-integration",
path: "docs/basic/editor-integration.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "linting",
path: "docs/basic/linting.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "resources",
path: "docs/basic/recommended/resources.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "talks",
path: "docs/basic/recommended/talks.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "codebases",
path: "docs/basic/recommended/codebases.md",
relativeHeadingLevel: 1,
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "learn-ts",
path: "docs/basic/troubleshooting/learn-ts.md",
relativeHeadingLevel: 1,
withKey: "sidebar_label",
});
pendingReadme = await updateSectionWith({
from: currentReadme,
to: pendingReadme,
name: "examples",
path: "docs/basic/examples.md",
relativeHeadingLevel: 1,
});
const prettierConfig = await prettier.resolveConfig(readmePath);
pendingReadme = prettier.format(pendingReadme, {
...prettierConfig,
filepath: path.basename(readmePath),
});
await fs.writeFile(readmePath, pendingReadme);
}
yargs(hideBin(process.argv))
.command({
command: "$0",
describe: "Generate the README.md from docs/ folder",
handler: main,
})
.usage("node $0 [args]")
.help()
.strict()
.parse();
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/copyFile.js | copyFile.js | const fs = require("fs");
const filesTopCopy = [
{
src: "../CONTRIBUTORS.md",
dest: "src/pages/contributors.md",
},
{
src: "../CONTRIBUTING.md",
dest: "src/pages/contributing.md",
},
];
function copyFile(src, dest) {
fs.copyFile(src, dest, (err) => {
if (err) {
console.log("Error Found:", err);
} else {
console.log("Files copied");
}
});
}
filesTopCopy.forEach(({ src, dest }) => {
copyFile(src, dest);
});
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/website/docusaurus.config.js | website/docusaurus.config.js | const { themes } = require("prism-react-renderer");
// List of projects/orgs using your project for the users page.
const users = [
{
caption: "Docusaurus",
image: "https://docusaurus.io/img/docusaurus.svg",
infoLink: "https://docusaurus.io/",
pinned: true,
},
];
const setupDoc = "docs/basic/setup";
module.exports = {
favicon: "img/icon.png",
title: "React TypeScript Cheatsheets", // Title for your website.
tagline:
"Cheatsheets for experienced React developers getting started with TypeScript",
url: "https://react-typescript-cheatsheet.netlify.app", // Your website URL
baseUrl: "/",
projectName: "react-typescript-cheatsheet",
organizationName: "typescript-cheatsheets",
presets: [
[
"@docusaurus/preset-classic",
{
theme: {
customCss: require.resolve("./src/css/custom.css"),
},
docs: {
// Docs folder path relative to website dir.
path: "../docs",
// Sidebars file relative to website dir.
sidebarPath: require.resolve("./sidebars.json"),
editUrl:
"https://github.com/typescript-cheatsheets/react/tree/main/docs",
},
// ...
},
],
],
themeConfig: {
colorMode: {
defaultMode: "dark",
},
image:
"https://user-images.githubusercontent.com/6764957/53868378-2b51fc80-3fb3-11e9-9cee-0277efe8a927.png",
// Equivalent to `docsSideNavCollapsible`.
// sidebarCollapsible: false,
prism: {
defaultLanguage: "typescript",
theme: themes.github,
darkTheme: themes.dracula,
},
navbar: {
title: "React TypeScript Cheatsheet",
logo: {
alt: "Logo",
src: "img/icon.png",
},
items: [
{
to: setupDoc,
label: "Docs",
position: "right",
},
{
to: "help",
label: "Help",
position: "right",
},
{
to: "https://discord.gg/wTGS5z9",
label: "Discord",
position: "right",
},
// {to: 'blog', label: 'Blog', position: 'right'},
],
},
footer: {
style: "dark",
logo: {
alt: "TypeScript Cheatsheets Logo",
src: "img/icon.png",
// maxWidth: 128,
// style: { maxWidth: 128, maxHeight: 128 },
},
copyright: `Copyright © ${new Date().getFullYear()} TypeScript Cheatsheets`,
links: [
{
title: "Docs",
items: [
{
label: "Introduction",
to: setupDoc,
},
{
label: "High Order Component (HOC)",
to: "docs/hoc",
},
{
label: "Advanced Guides",
to: "docs/advanced",
},
{
label: "Migrating",
to: "docs/migration",
},
],
},
{
title: "Community",
items: [
{
label: "Stack Overflow",
href: "https://stackoverflow.com/questions/tagged/typescript",
},
{
label: "User Showcase",
to: "users",
},
{
label: "Help",
to: "help",
},
{
label: "Contributors",
to: "contributors",
},
{
label: "Contributing",
to: "contributing",
},
],
},
{
title: "More",
items: [
{
label: "GitHub",
href: "https://github.com/typescript-cheatsheets/react",
},
{
html: `<a class="footer__link-item" href="https://github.com/typescript-cheatsheets/react">
<img src="https://img.shields.io/github/stars/typescript-cheatsheets/react-typescript-cheatsheet.svg?style=social&label=Star&maxAge=2592000" alt="GitHub stars" data-canonical-src="https://img.shields.io/github/stars/typescript-cheatsheets/react-typescript-cheatsheet.svg?style=social&label=Star&maxAge=2592000" style="max-width:100%;">
</a>`,
},
{
// label: "Discord",
html: `<a class="footer__link-item" href="https://discord.gg/wTGS5z9">
<img src="https://img.shields.io/discord/508357248330760243.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" style="max-width:100%;" alt="Discord">
</a>`,
},
{
// label: "Spread the word",
html: `<a class="footer__link-item" href="http://twitter.com/home?status=Awesome%20%40Reactjs%20%2B%20%40TypeScript%20cheatsheet%20by%20%40ferdaber%2C%20%40sebsilbermann%2C%20%40swyx%20%26%20others!%20https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact">
<img src="https://img.shields.io/twitter/url?label=Help%20spread%20the%20word%21&style=social&url=https%3A%2F%2Fgithub.com%2Ftypescript-cheatsheets%2Freact" style="max-width:100%;" alt="X">
</a>`,
},
],
},
],
},
algolia: {
apiKey: "9a22585d1841d2fa758da919cd08a764",
indexName: "react-typescript-cheatsheet",
appId: "J65EL4UPXZ",
algoliaOptions: {
//... },
},
},
},
customFields: {
firstDoc: setupDoc,
// TODO useless user showcase page ?
users,
addUserUrl:
"https://github.com/typescript-cheatsheets/react/blob/main/website/docusaurus.config.js",
},
};
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/website/src/pages/help.js | website/src/pages/help.js | import React from "react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import Link from "@docusaurus/Link";
import Layout from "@theme/Layout";
const SupportLink = ({ title, content }) => (
<div>
<h2>{title}</h2>
<div>{content}</div>
</div>
);
export default function Help() {
const { siteConfig } = useDocusaurusContext();
const supportLinks = [
{
title: "Browse Docs",
content: (
<>
Learn more using the{" "}
<Link to={useBaseUrl(siteConfig.customFields.firstDoc)}>
documentation on this site
</Link>
.
</>
),
},
{
title: "Join the community",
content: "Ask questions about the documentation and project",
},
{
title: "Stay up to date",
content: "Find out what's new with this project",
},
];
return (
<Layout title="Help" permalink="/help" description="Help">
<div className="container margin-vert--xl">
<div>
<header>
<h1>Need help?</h1>
</header>
<p>This project is maintained by a dedicated group of people.</p>
</div>
<div className="row">
{supportLinks.map((supportLink, i) => (
<div className="col col--4 margin-top--lg" key={i}>
<SupportLink {...supportLink} />
</div>
))}
</div>
</div>
</Layout>
);
}
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/website/src/pages/index.js | website/src/pages/index.js | import React from "react";
import Link from "@docusaurus/Link";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import Layout from "@theme/Layout";
export default function Home() {
const { siteConfig } = useDocusaurusContext();
return (
<Layout
title="React TypeScript Cheatsheets"
permalink="/"
description="React TypeScript Cheatsheets"
>
<div className="hero text--center">
<div className="container ">
<div className="padding-vert--md">
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
</div>
<div className="homePageBtns">
<Link
to={useBaseUrl(siteConfig.customFields.firstDoc)}
className="button button--lg button--outline button--primary"
>
Getting started
</Link>
<Link
to={"https://discord.gg/wTGS5z9"}
className="button button--lg button--outline button--secondary"
>
Join Official Discord
</Link>
</div>
</div>
</div>
</Layout>
);
}
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
typescript-cheatsheets/react | https://github.com/typescript-cheatsheets/react/blob/911f92807caafbf71956973219991aa8e9be1af0/website/src/pages/users.js | website/src/pages/users.js | import React from "react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import Layout from "@theme/Layout";
// TODO useless user showcase page ?
export default function Users() {
const { siteConfig } = useDocusaurusContext();
const { users, addUserUrl } = siteConfig.customFields;
return (
<Layout title="Users" permalink="/users" description="Users">
<div className="container">
<div className="margin-vert--xl text--center">
<div>
<h1>Who is Using This?</h1>
<p>This project is used by many folks</p>
</div>
<div className="row">
{users && users.length>0&& users.map((user) => (
<a
className="col-2"
href={user.infoLink}
key={user.infoLink}
style={{ flexGrow: 1 }}
>
<img
className="padding--md"
src={user.image}
alt={user.caption}
title={user.caption}
style={{
maxHeight: 128,
width: 128,
}}
/>
</a>
))}
</div>
<p>Are you using this project?</p>
<a
href={addUserUrl}
className="button button--lg button--outline button--primary"
>
Add your company
</a>
</div>
</div>
</Layout>
);
}
| javascript | MIT | 911f92807caafbf71956973219991aa8e9be1af0 | 2026-01-04T14:58:00.774836Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import { combineReducers, createStore } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import { routerReducer } from 'react-router-redux';
import App from 'components/App';
import * as reducers from 'reducers';
import './stylesheet.scss';
const store = createStore(combineReducers({ ...reducers, routing: routerReducer }));
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Switch>
<Route exact path="/scratch-paper/:gistId" component={App}/>
<Route exact path="/:categoryKey/:algorithmKey" component={App}/>
<Route path="/" component={App}/>
</Switch>
</BrowserRouter>
</Provider>, document.getElementById('root'));
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/toast.js | src/reducers/toast.js | import { combineActions, createAction, handleActions } from 'redux-actions';
import uuid from 'uuid';
const prefix = 'TOAST';
const showSuccessToast = createAction(`${prefix}/SHOW_SUCCESS_TOAST`, message => ({ type: 'success', message }));
const showErrorToast = createAction(`${prefix}/SHOW_ERROR_TOAST`, message => ({ type: 'error', message }));
const hideToast = createAction(`${prefix}/HIDE_TOAST`, id => ({ id }));
export const actions = {
showSuccessToast,
showErrorToast,
hideToast,
};
const defaultState = {
toasts: [],
};
export default handleActions({
[combineActions(
showSuccessToast,
showErrorToast,
)]: (state, { payload }) => {
const id = uuid.v4();
const toast = {
id,
...payload,
};
const toasts = [
...state.toasts,
toast,
];
return {
...state,
toasts,
};
},
[hideToast]: (state, { payload }) => {
const { id } = payload;
const toasts = state.toasts.filter(toast => toast.id !== id);
return {
...state,
toasts,
};
},
}, defaultState);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/env.js | src/reducers/env.js | import Cookies from 'js-cookie';
import { combineActions, createAction, handleActions } from 'redux-actions';
const prefix = 'ENV';
const setExt = createAction(`${prefix}/SET_EXT`, ext => {
Cookies.set('ext', ext);
return { ext };
});
const setUser = createAction(`${prefix}/SET_USER`, user => ({ user }));
export const actions = {
setExt,
setUser,
};
const defaultState = {
ext: Cookies.get('ext') || 'js',
user: undefined,
};
export default handleActions({
[combineActions(
setExt,
setUser,
)]: (state, { payload }) => ({
...state,
...payload,
}),
}, defaultState);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/current.js | src/reducers/current.js | import { combineActions, createAction, handleActions } from 'redux-actions';
import { ROOT_README_MD } from 'files';
import { extension, isSaved } from 'common/util';
const prefix = 'CURRENT';
const setHome = createAction(`${prefix}/SET_HOME`, () => defaultState);
const setAlgorithm = createAction(`${prefix}/SET_ALGORITHM`, ({ categoryKey, categoryName, algorithmKey, algorithmName, files, description }) => ({
algorithm: { categoryKey, algorithmKey },
titles: [categoryName, algorithmName],
files,
description,
}));
const setScratchPaper = createAction(`${prefix}/SET_SCRATCH_PAPER`, ({ login, gistId, title, files }) => ({
scratchPaper: { login, gistId },
titles: ['Scratch Paper', title],
files,
description: homeDescription,
}));
const setEditingFile = createAction(`${prefix}/SET_EDITING_FILE`, file => ({ file }));
const modifyTitle = createAction(`${prefix}/MODIFY_TITLE`, title => ({ title }));
const addFile = createAction(`${prefix}/ADD_FILE`, file => ({ file }));
const renameFile = createAction(`${prefix}/RENAME_FILE`, (file, name) => ({ file, name }));
const modifyFile = createAction(`${prefix}/MODIFY_FILE`, (file, content) => ({ file, content }));
const deleteFile = createAction(`${prefix}/DELETE_FILE`, file => ({ file }));
export const actions = {
setHome,
setAlgorithm,
setScratchPaper,
setEditingFile,
modifyTitle,
addFile,
modifyFile,
deleteFile,
renameFile,
};
const homeTitles = ['Algorithm Visualizer'];
const homeFiles = [ROOT_README_MD];
const homeDescription = 'Algorithm Visualizer is an interactive online platform that visualizes algorithms from code.';
const defaultState = {
algorithm: {
categoryKey: 'algorithm-visualizer',
algorithmKey: 'home',
},
scratchPaper: undefined,
titles: homeTitles,
files: homeFiles,
lastTitles: homeTitles,
lastFiles: homeFiles,
description: homeDescription,
editingFile: undefined,
shouldBuild: true,
saved: true,
};
export default handleActions({
[combineActions(
setHome,
setAlgorithm,
setScratchPaper,
)]: (state, { payload }) => {
const { algorithm, scratchPaper, titles, files, description } = payload;
return {
...state,
algorithm,
scratchPaper,
titles,
files,
lastTitles: titles,
lastFiles: files,
description,
editingFile: undefined,
shouldBuild: true,
saved: true,
};
},
[setEditingFile]: (state, { payload }) => {
const { file } = payload;
return {
...state,
editingFile: file,
shouldBuild: true,
};
},
[modifyTitle]: (state, { payload }) => {
const { title } = payload;
const newState = {
...state,
titles: [state.titles[0], title],
};
return {
...newState,
saved: isSaved(newState),
};
},
[addFile]: (state, { payload }) => {
const { file } = payload;
const newState = {
...state,
files: [...state.files, file],
editingFile: file,
shouldBuild: true,
};
return {
...newState,
saved: isSaved(newState),
};
},
[combineActions(
renameFile,
modifyFile,
)]: (state, { payload }) => {
const { file, ...update } = payload;
const editingFile = { ...file, ...update };
const newState = {
...state,
files: state.files.map(oldFile => oldFile === file ? editingFile : oldFile),
editingFile,
shouldBuild: extension(editingFile.name) === 'md',
};
return {
...newState,
saved: isSaved(newState),
};
},
[deleteFile]: (state, { payload }) => {
const { file } = payload;
const index = state.files.indexOf(file);
const files = state.files.filter(oldFile => oldFile !== file);
const editingFile = files[Math.min(index, files.length - 1)];
const newState = {
...state,
files,
editingFile,
shouldBuild: true,
};
return {
...newState,
saved: isSaved(newState),
};
},
}, defaultState);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/player.js | src/reducers/player.js | import { combineActions, createAction, handleActions } from 'redux-actions';
const prefix = 'PLAYER';
const setChunks = createAction(`${prefix}/SET_CHUNKS`, chunks => ({ chunks }));
const setCursor = createAction(`${prefix}/SET_CURSOR`, cursor => ({ cursor }));
const setLineIndicator = createAction(`${prefix}/SET_LINE_INDICATOR`, lineIndicator => ({ lineIndicator }));
export const actions = {
setChunks,
setCursor,
setLineIndicator,
};
const defaultState = {
chunks: [],
cursor: 0,
lineIndicator: undefined,
};
export default handleActions({
[combineActions(
setChunks,
setCursor,
setLineIndicator,
)]: (state, { payload }) => ({
...state,
...payload,
}),
}, defaultState);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/index.js | src/reducers/index.js | import { actions as currentActions } from './current';
import { actions as directoryActions } from './directory';
import { actions as envActions } from './env';
import { actions as playerActions } from './player';
import { actions as toastActions } from './toast';
export { default as current } from './current';
export { default as directory } from './directory';
export { default as env } from './env';
export { default as player } from './player';
export { default as toast } from './toast';
export const actions = {
...currentActions,
...directoryActions,
...envActions,
...playerActions,
...toastActions,
};
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/reducers/directory.js | src/reducers/directory.js | import { combineActions, createAction, handleActions } from 'redux-actions';
const prefix = 'DIRECTORY';
const setCategories = createAction(`${prefix}/SET_CATEGORIES`, categories => ({ categories }));
const setScratchPapers = createAction(`${prefix}/SET_SCRATCH_PAPERS`, scratchPapers => ({ scratchPapers }));
export const actions = {
setCategories,
setScratchPapers,
};
const defaultState = {
categories: [],
scratchPapers: [],
};
export default handleActions({
[combineActions(
setCategories,
setScratchPapers,
)]: (state, { payload }) => ({
...state,
...payload,
}),
}, defaultState);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/index.js | src/components/index.js | export { default as App } from './App';
export { default as BaseComponent } from './BaseComponent';
export { default as Button } from './Button';
export { default as CodeEditor } from './CodeEditor';
export { default as Divider } from './Divider';
export { default as Ellipsis } from './Ellipsis';
export { default as ExpandableListItem } from './ExpandableListItem';
export { default as FoldableAceEditor } from './FoldableAceEditor';
export { default as Header } from './Header';
export { default as ListItem } from './ListItem';
export { default as Navigator } from './Navigator';
export { default as Player } from './Player';
export { default as ProgressBar } from './ProgressBar';
export { default as ResizableContainer } from './ResizableContainer';
export { default as TabContainer } from './TabContainer';
export { default as ToastContainer } from './ToastContainer';
export { default as VisualizationViewer } from './VisualizationViewer';
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/VisualizationViewer/index.js | src/components/VisualizationViewer/index.js | import React from 'react';
import { connect } from 'react-redux';
import { BaseComponent } from 'components';
import { actions } from 'reducers';
import styles from './VisualizationViewer.module.scss';
import * as TracerClasses from 'core/tracers';
import * as LayoutClasses from 'core/layouts';
import { classes } from 'common/util';
class VisualizationViewer extends BaseComponent {
constructor(props) {
super(props);
this.reset();
}
reset() {
this.root = null;
this.objects = {};
}
componentDidMount() {
const { chunks, cursor } = this.props.player;
this.update(chunks, cursor);
}
componentWillReceiveProps(nextProps) {
const { chunks, cursor } = nextProps.player;
const { chunks: oldChunks, cursor: oldCursor } = this.props.player;
if (chunks !== oldChunks || cursor !== oldCursor) {
this.update(chunks, cursor, oldChunks, oldCursor);
}
}
update(chunks, cursor, oldChunks = [], oldCursor = 0) {
let applyingChunks;
if (cursor > oldCursor) {
applyingChunks = chunks.slice(oldCursor, cursor);
} else {
this.reset();
applyingChunks = chunks.slice(0, cursor);
}
applyingChunks.forEach(chunk => this.applyChunk(chunk));
const lastChunk = applyingChunks[applyingChunks.length - 1];
if (lastChunk && lastChunk.lineNumber !== undefined) {
this.props.setLineIndicator({ lineNumber: lastChunk.lineNumber, cursor });
} else {
this.props.setLineIndicator(undefined);
}
}
applyCommand(command) {
const { key, method, args } = command;
try {
if (key === null && method === 'setRoot') {
const [root] = args;
this.root = this.objects[root];
} else if (method === 'destroy') {
delete this.objects[key];
} else if (method in LayoutClasses) {
const [children] = args;
const LayoutClass = LayoutClasses[method];
this.objects[key] = new LayoutClass(key, key => this.objects[key], children);
} else if (method in TracerClasses) {
const className = method;
const [title = className] = args;
const TracerClass = TracerClasses[className];
this.objects[key] = new TracerClass(key, key => this.objects[key], title);
} else {
this.objects[key][method](...args);
}
} catch (error) {
this.handleError(error);
}
}
applyChunk(chunk) {
chunk.commands.forEach(command => this.applyCommand(command));
}
render() {
const { className } = this.props;
return (
<div className={classes(styles.visualization_viewer, className)}>
{
this.root && this.root.render()
}
</div>
);
}
}
export default connect(({ player }) => ({ player }), actions)(
VisualizationViewer,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/ExpandableListItem/index.js | src/components/ExpandableListItem/index.js | import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import faCaretDown from '@fortawesome/fontawesome-free-solid/faCaretDown';
import faCaretRight from '@fortawesome/fontawesome-free-solid/faCaretRight';
import styles from './ExpandableListItem.module.scss';
import { ListItem } from 'components';
import { classes } from 'common/util';
class ExpandableListItem extends React.Component {
render() {
const { className, children, opened, ...props } = this.props;
return opened ? (
<div className={classes(styles.expandable_list_item, className)}>
<ListItem className={styles.category} {...props}>
<FontAwesomeIcon className={styles.icon} fixedWidth icon={faCaretDown} />
</ListItem>
{children}
</div>
) : (
<ListItem className={classes(styles.category, className)} {...props}>
<FontAwesomeIcon className={styles.icon} fixedWidth icon={faCaretRight} />
</ListItem>
);
}
}
export default ExpandableListItem;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Ellipsis/index.js | src/components/Ellipsis/index.js | import React from 'react';
import styles from './Ellipsis.module.scss';
import { classes } from 'common/util';
class Ellipsis extends React.Component {
render() {
const { className, children } = this.props;
return (
<span className={classes(styles.ellipsis, className)}>
{children}
</span>
);
}
}
export default Ellipsis;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/FoldableAceEditor/index.js | src/components/FoldableAceEditor/index.js | import { connect } from 'react-redux';
import AceEditor from 'react-ace';
import 'brace/mode/plain_text';
import 'brace/mode/markdown';
import 'brace/mode/json';
import 'brace/mode/javascript';
import 'brace/mode/c_cpp';
import 'brace/mode/java';
import 'brace/theme/tomorrow_night_eighties';
import 'brace/ext/searchbox';
import { actions } from 'reducers';
class FoldableAceEditor extends AceEditor {
componentDidMount() {
super.componentDidMount();
const { shouldBuild } = this.props.current;
if (shouldBuild) this.foldTracers();
}
componentDidUpdate(prevProps, prevState, snapshot) {
super.componentDidUpdate(prevProps, prevState, snapshot);
const { editingFile, shouldBuild } = this.props.current;
if (editingFile !== prevProps.current.editingFile) {
if (shouldBuild) this.foldTracers();
}
}
foldTracers() {
const session = this.editor.getSession();
for (let row = 0; row < session.getLength(); row++) {
if (!/^\s*\/\/.+{\s*$/.test(session.getLine(row))) continue;
const range = session.getFoldWidgetRange(row);
if (range) {
session.addFold('...', range);
row = range.end.row;
}
}
}
resize() {
this.editor.resize();
}
}
export default connect(({ current }) => ({ current }), actions, null, { forwardRef: true })(
FoldableAceEditor,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/ProgressBar/index.js | src/components/ProgressBar/index.js | import React from 'react';
import { classes } from 'common/util';
import styles from './ProgressBar.module.scss';
class ProgressBar extends React.Component {
constructor(props) {
super(props);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
}
handleMouseDown(e) {
this.target = e.target;
this.handleMouseMove(e);
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
}
handleMouseMove(e) {
const { left } = this.target.getBoundingClientRect();
const { offsetWidth } = this.target;
const { onChangeProgress } = this.props;
const progress = (e.clientX - left) / offsetWidth;
if (onChangeProgress) onChangeProgress(progress);
}
handleMouseUp(e) {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
render() {
const { className, total, current } = this.props;
return (
<div className={classes(styles.progress_bar, className)} onMouseDown={this.handleMouseDown}>
<div className={styles.active} style={{ width: `${current / total * 100}%` }} />
<div className={styles.label}>
<span className={styles.current}>{current}</span> / {total}
</div>
</div>
);
}
}
export default ProgressBar;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Player/index.js | src/components/Player/index.js | import React from 'react';
import { connect } from 'react-redux';
import InputRange from 'react-input-range';
import axios from 'axios';
import faPlay from '@fortawesome/fontawesome-free-solid/faPlay';
import faChevronLeft from '@fortawesome/fontawesome-free-solid/faChevronLeft';
import faChevronRight from '@fortawesome/fontawesome-free-solid/faChevronRight';
import faPause from '@fortawesome/fontawesome-free-solid/faPause';
import faWrench from '@fortawesome/fontawesome-free-solid/faWrench';
import { classes, extension } from 'common/util';
import { TracerApi } from 'apis';
import { actions } from 'reducers';
import { BaseComponent, Button, ProgressBar } from 'components';
import styles from './Player.module.scss';
class Player extends BaseComponent {
constructor(props) {
super(props);
this.state = {
speed: 2,
playing: false,
building: false,
};
this.tracerApiSource = null;
this.reset();
}
componentDidMount() {
const { editingFile, shouldBuild } = this.props.current;
if (shouldBuild) this.build(editingFile);
}
componentWillReceiveProps(nextProps) {
const { editingFile, shouldBuild } = nextProps.current;
if (editingFile !== this.props.current.editingFile) {
if (shouldBuild) this.build(editingFile);
}
}
reset(commands = []) {
const chunks = [{
commands: [],
lineNumber: undefined,
}];
while (commands.length) {
const command = commands.shift();
const { key, method, args } = command;
if (key === null && method === 'delay') {
const [lineNumber] = args;
chunks[chunks.length - 1].lineNumber = lineNumber;
chunks.push({
commands: [],
lineNumber: undefined,
});
} else {
chunks[chunks.length - 1].commands.push(command);
}
}
this.props.setChunks(chunks);
this.props.setCursor(0);
this.pause();
this.props.setLineIndicator(undefined);
}
build(file) {
this.reset();
if (!file) return;
if (this.tracerApiSource) this.tracerApiSource.cancel();
this.tracerApiSource = axios.CancelToken.source();
this.setState({ building: true });
const ext = extension(file.name);
if (ext in TracerApi) {
TracerApi[ext]({ code: file.content }, undefined, this.tracerApiSource.token)
.then(commands => {
this.tracerApiSource = null;
this.setState({ building: false });
this.reset(commands);
this.next();
})
.catch(error => {
if (axios.isCancel(error)) return;
this.tracerApiSource = null;
this.setState({ building: false });
this.handleError(error);
});
} else {
this.setState({ building: false });
this.handleError(new Error('Language Not Supported'));
}
}
isValidCursor(cursor) {
const { chunks } = this.props.player;
return 1 <= cursor && cursor <= chunks.length;
}
prev() {
this.pause();
const cursor = this.props.player.cursor - 1;
if (!this.isValidCursor(cursor)) return false;
this.props.setCursor(cursor);
return true;
}
resume(wrap = false) {
this.pause();
if (this.next() || (wrap && this.props.setCursor(1))) {
const interval = 4000 / Math.pow(Math.E, this.state.speed);
this.timer = window.setTimeout(() => this.resume(), interval);
this.setState({ playing: true });
}
}
pause() {
if (this.timer) {
window.clearTimeout(this.timer);
this.timer = undefined;
this.setState({ playing: false });
}
}
next() {
this.pause();
const cursor = this.props.player.cursor + 1;
if (!this.isValidCursor(cursor)) return false;
this.props.setCursor(cursor);
return true;
}
handleChangeSpeed(speed) {
this.setState({ speed });
}
handleChangeProgress(progress) {
const { chunks } = this.props.player;
const cursor = Math.max(1, Math.min(chunks.length, Math.round(progress * chunks.length)));
this.pause();
this.props.setCursor(cursor);
}
render() {
const { className } = this.props;
const { editingFile } = this.props.current;
const { chunks, cursor } = this.props.player;
const { speed, playing, building } = this.state;
return (
<div className={classes(styles.player, className)}>
<Button icon={faWrench} primary disabled={building} inProgress={building}
onClick={() => this.build(editingFile)}>
{building ? 'Building' : 'Build'}
</Button>
{
playing ? (
<Button icon={faPause} primary active onClick={() => this.pause()}>Pause</Button>
) : (
<Button icon={faPlay} primary onClick={() => this.resume(true)}>Play</Button>
)
}
<Button icon={faChevronLeft} primary disabled={!this.isValidCursor(cursor - 1)} onClick={() => this.prev()}/>
<ProgressBar className={styles.progress_bar} current={cursor} total={chunks.length}
onChangeProgress={progress => this.handleChangeProgress(progress)}/>
<Button icon={faChevronRight} reverse primary disabled={!this.isValidCursor(cursor + 1)}
onClick={() => this.next()}/>
<div className={styles.speed}>
Speed
<InputRange
classNames={{
inputRange: styles.range,
labelContainer: styles.range_label_container,
slider: styles.range_slider,
track: styles.range_track,
}} minValue={0} maxValue={4} step={.5} value={speed}
onChange={speed => this.handleChangeSpeed(speed)}/>
</div>
</div>
);
}
}
export default connect(({ current, player }) => ({ current, player }), actions)(
Player,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/TabContainer/index.js | src/components/TabContainer/index.js | import React from 'react';
import { connect } from 'react-redux';
import AutosizeInput from 'react-input-autosize';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import faPlus from '@fortawesome/fontawesome-free-solid/faPlus';
import { classes } from 'common/util';
import { actions } from 'reducers';
import { languages } from 'common/config';
import styles from './TabContainer.module.scss';
class TabContainer extends React.Component {
handleAddFile() {
const { ext } = this.props.env;
const { files } = this.props.current;
const language = languages.find(language => language.ext === ext);
const newFile = { ...language.skeleton };
let count = 0;
while (files.some(file => file.name === newFile.name)) newFile.name = `code-${++count}.${ext}`;
this.props.addFile(newFile);
}
render() {
const { className, children } = this.props;
const { editingFile, files } = this.props.current;
return (
<div className={classes(styles.tab_container, className)}>
<div className={styles.tab_bar}>
<div className={classes(styles.title, styles.fake)}/>
{
files.map((file, i) => file === editingFile ? (
<div className={classes(styles.title, styles.selected)} key={i}
onClick={() => this.props.setEditingFile(file)}>
<AutosizeInput className={styles.input_title} value={file.name}
onClick={e => e.stopPropagation()}
onChange={e => this.props.renameFile(file, e.target.value)}/>
</div>
) : (
<div className={styles.title} key={i} onClick={() => this.props.setEditingFile(file)}>
{file.name}
</div>
))
}
<div className={styles.title} onClick={() => this.handleAddFile()}>
<FontAwesomeIcon fixedWidth icon={faPlus}/>
</div>
<div className={classes(styles.title, styles.fake)}/>
</div>
<div className={styles.content}>
{children}
</div>
</div>
);
}
}
export default connect(({ current, env }) => ({ current, env }), actions)(
TabContainer,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Navigator/index.js | src/components/Navigator/index.js | import React from 'react';
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import faSearch from '@fortawesome/fontawesome-free-solid/faSearch';
import faCode from '@fortawesome/fontawesome-free-solid/faCode';
import faBook from '@fortawesome/fontawesome-free-solid/faBook';
import faGithub from '@fortawesome/fontawesome-free-brands/faGithub';
import { ExpandableListItem, ListItem } from 'components';
import { classes } from 'common/util';
import { actions } from 'reducers';
import styles from './Navigator.module.scss';
class Navigator extends React.Component {
constructor(props) {
super(props);
this.state = {
categoriesOpened: {},
scratchPaperOpened: true,
query: '',
};
}
componentDidMount() {
const { algorithm } = this.props.current;
if (algorithm) {
this.toggleCategory(algorithm.categoryKey, true);
}
}
componentWillReceiveProps(nextProps) {
const { algorithm } = nextProps.current;
if (algorithm) {
this.toggleCategory(algorithm.categoryKey, true);
}
}
toggleCategory(key, categoryOpened = !this.state.categoriesOpened[key]) {
const categoriesOpened = {
...this.state.categoriesOpened,
[key]: categoryOpened,
};
this.setState({ categoriesOpened });
}
toggleScratchPaper(scratchPaperOpened = !this.state.scratchPaperOpened) {
this.setState({ scratchPaperOpened });
}
handleChangeQuery(e) {
const { categories } = this.props.directory;
const categoriesOpened = {};
const query = e.target.value;
categories.forEach(category => {
if (this.testQuery(category.name) || category.algorithms.find(algorithm => this.testQuery(algorithm.name))) {
categoriesOpened[category.key] = true;
}
});
this.setState({ categoriesOpened, query });
}
testQuery(value) {
const { query } = this.state;
const refine = string => string.replace(/-/g, ' ').replace(/[^\w ]/g, '');
const refinedQuery = refine(query);
const refinedValue = refine(value);
return new RegExp(`(^| )${refinedQuery}`, 'i').test(refinedValue) ||
new RegExp(refinedQuery, 'i').test(refinedValue.split(' ').map(v => v && v[0]).join(''));
}
render() {
const { categoriesOpened, scratchPaperOpened, query } = this.state;
const { className } = this.props;
const { categories, scratchPapers } = this.props.directory;
const { algorithm, scratchPaper } = this.props.current;
const categoryKey = algorithm && algorithm.categoryKey;
const algorithmKey = algorithm && algorithm.algorithmKey;
const gistId = scratchPaper && scratchPaper.gistId;
return (
<nav className={classes(styles.navigator, className)}>
<div className={styles.search_bar_container}>
<FontAwesomeIcon fixedWidth icon={faSearch} className={styles.search_icon}/>
<input type="text" className={styles.search_bar} aria-label="Search" placeholder="Search ..." autoFocus
value={query} onChange={e => this.handleChangeQuery(e)}/>
</div>
<div className={styles.algorithm_list}>
{
categories.map(category => {
const categoryOpened = categoriesOpened[category.key];
let algorithms = category.algorithms;
if (!this.testQuery(category.name)) {
algorithms = algorithms.filter(algorithm => this.testQuery(algorithm.name));
if (!algorithms.length) return null;
}
return (
<ExpandableListItem key={category.key} onClick={() => this.toggleCategory(category.key)}
label={category.name}
opened={categoryOpened}>
{
algorithms.map(algorithm => (
<ListItem indent key={algorithm.key}
selected={category.key === categoryKey && algorithm.key === algorithmKey}
to={`/${category.key}/${algorithm.key}`} label={algorithm.name}/>
))
}
</ExpandableListItem>
);
})
}
</div>
<div className={styles.footer}>
<ExpandableListItem icon={faCode} label="Scratch Paper" onClick={() => this.toggleScratchPaper()}
opened={scratchPaperOpened}>
<ListItem indent label="New ..." to="/scratch-paper/new"/>
{
scratchPapers.map(scratchPaper => (
<ListItem indent key={scratchPaper.key} selected={scratchPaper.key === gistId}
to={`/scratch-paper/${scratchPaper.key}`} label={scratchPaper.name}/>
))
}
</ExpandableListItem>
<ListItem icon={faBook} label="API Reference"
href="https://github.com/algorithm-visualizer/algorithm-visualizer/wiki"/>
<ListItem icon={faGithub} label="Fork me on GitHub"
href="https://github.com/algorithm-visualizer/algorithm-visualizer"/>
</div>
</nav>
);
}
}
export default connect(({ current, directory, env }) => ({ current, directory, env }), actions)(
Navigator,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/CodeEditor/index.js | src/components/CodeEditor/index.js | import React from 'react';
import faTrashAlt from '@fortawesome/fontawesome-free-solid/faTrashAlt';
import faUser from '@fortawesome/fontawesome-free-solid/faUser';
import { classes, extension } from 'common/util';
import { actions } from 'reducers';
import { connect } from 'react-redux';
import { languages } from 'common/config';
import { Button, Ellipsis, FoldableAceEditor } from 'components';
import styles from './CodeEditor.module.scss';
class CodeEditor extends React.Component {
constructor(props) {
super(props);
this.aceEditorRef = React.createRef();
}
handleResize() {
this.aceEditorRef.current.resize();
}
render() {
const { className } = this.props;
const { editingFile } = this.props.current;
const { user } = this.props.env;
const { lineIndicator } = this.props.player;
if (!editingFile) return null;
const fileExt = extension(editingFile.name);
const language = languages.find(language => language.ext === fileExt);
const mode = language ? language.mode :
fileExt === 'md' ? 'markdown' :
fileExt === 'json' ? 'json' :
'plain_text';
return (
<div className={classes(styles.code_editor, className)}>
<FoldableAceEditor
className={styles.ace_editor}
ref={this.aceEditorRef}
mode={mode}
theme="tomorrow_night_eighties"
name="code_editor"
editorProps={{ $blockScrolling: true }}
onChange={code => this.props.modifyFile(editingFile, code)}
markers={lineIndicator ? [{
startRow: lineIndicator.lineNumber,
startCol: 0,
endRow: lineIndicator.lineNumber,
endCol: Infinity,
className: styles.current_line_marker,
type: 'line',
inFront: true,
_key: lineIndicator.cursor,
}] : []}
value={editingFile.content}/>
<div className={classes(styles.contributors_viewer, className)}>
<span className={classes(styles.contributor, styles.label)}>Contributed by</span>
{
(editingFile.contributors || [user || { login: 'guest', avatar_url: faUser }]).map(contributor => (
<Button className={styles.contributor} icon={contributor.avatar_url} key={contributor.login}
href={`https://github.com/${contributor.login}`}>
{contributor.login}
</Button>
))
}
<div className={styles.empty}>
<div className={styles.empty}/>
<Button className={styles.delete} icon={faTrashAlt} primary confirmNeeded
onClick={() => this.props.deleteFile(editingFile)}>
<Ellipsis>Delete File</Ellipsis>
</Button>
</div>
</div>
</div>
);
}
}
export default connect(({ current, env, player }) => ({ current, env, player }), actions, null, { forwardRef: true })(
CodeEditor,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/ToastContainer/index.js | src/components/ToastContainer/index.js | import React from 'react';
import { connect } from 'react-redux';
import { actions } from 'reducers';
import { classes } from 'common/util';
import styles from './ToastContainer.module.scss';
class ToastContainer extends React.Component {
componentWillReceiveProps(nextProps) {
const newToasts = nextProps.toast.toasts.filter(toast => !this.props.toast.toasts.includes(toast));
newToasts.forEach(toast => {
window.setTimeout(() => this.props.hideToast(toast.id), 3000);
});
}
render() {
const { className } = this.props;
const { toasts } = this.props.toast;
return (
<div className={classes(styles.toast_container, className)}>
{
toasts.map(toast => (
<div className={classes(styles.toast, styles[toast.type])} key={toast.id}>
{toast.message}
</div>
))
}
</div>
);
}
}
export default connect(({ toast }) => ({ toast }), actions)(
ToastContainer,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/ListItem/index.js | src/components/ListItem/index.js | import React from 'react';
import styles from './ListItem.module.scss';
import { classes } from 'common/util';
import { Button, Ellipsis } from 'components';
class ListItem extends React.Component {
render() {
const { className, children, indent, label, ...props } = this.props;
return (
<Button className={classes(styles.list_item, indent && styles.indent, className)} {...props}>
<Ellipsis className={styles.label}>{label}</Ellipsis>
{children}
</Button>
);
}
}
export default ListItem;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/App/index.js | src/components/App/index.js | import React from 'react';
import Cookies from 'js-cookie';
import { connect } from 'react-redux';
import Promise from 'bluebird';
import { Helmet } from 'react-helmet';
import queryString from 'query-string';
import {
BaseComponent,
CodeEditor,
Header,
Navigator,
ResizableContainer,
TabContainer,
ToastContainer,
VisualizationViewer,
} from 'components';
import { AlgorithmApi, GitHubApi, VisualizationApi } from 'apis';
import { actions } from 'reducers';
import { createUserFile, extension, refineGist } from 'common/util';
import { exts, languages } from 'common/config';
import { SCRATCH_PAPER_README_MD } from 'files';
import styles from './App.module.scss';
class App extends BaseComponent {
constructor(props) {
super(props);
this.state = {
workspaceVisibles: [true, true, true],
workspaceWeights: [1, 2, 2],
};
this.codeEditorRef = React.createRef();
this.ignoreHistoryBlock = this.ignoreHistoryBlock.bind(this);
this.handleClickTitleBar = this.handleClickTitleBar.bind(this);
this.loadScratchPapers = this.loadScratchPapers.bind(this);
this.handleChangeWorkspaceWeights = this.handleChangeWorkspaceWeights.bind(this);
}
componentDidMount() {
window.signIn = this.signIn.bind(this);
window.signOut = this.signOut.bind(this);
const { params } = this.props.match;
const { search } = this.props.location;
this.loadAlgorithm(params, queryString.parse(search));
const accessToken = Cookies.get('access_token');
if (accessToken) this.signIn(accessToken);
AlgorithmApi.getCategories()
.then(({ categories }) => this.props.setCategories(categories))
.catch(this.handleError);
this.toggleHistoryBlock(true);
}
componentWillUnmount() {
delete window.signIn;
delete window.signOut;
this.toggleHistoryBlock(false);
}
componentWillReceiveProps(nextProps) {
const { params } = nextProps.match;
const { search } = nextProps.location;
if (params !== this.props.match.params || search !== this.props.location.search) {
const { categoryKey, algorithmKey, gistId } = params;
const { algorithm, scratchPaper } = nextProps.current;
if (algorithm && algorithm.categoryKey === categoryKey && algorithm.algorithmKey === algorithmKey) return;
if (scratchPaper && scratchPaper.gistId === gistId) return;
this.loadAlgorithm(params, queryString.parse(search));
}
}
toggleHistoryBlock(enable = !this.unblock) {
if (enable) {
const warningMessage = 'Are you sure you want to discard changes?';
window.onbeforeunload = () => {
const { saved } = this.props.current;
if (!saved) return warningMessage;
};
this.unblock = this.props.history.block((location) => {
if (location.pathname === this.props.location.pathname) return;
const { saved } = this.props.current;
if (!saved) return warningMessage;
});
} else {
window.onbeforeunload = undefined;
this.unblock();
this.unblock = undefined;
}
}
ignoreHistoryBlock(process) {
this.toggleHistoryBlock(false);
process();
this.toggleHistoryBlock(true);
}
signIn(accessToken) {
Cookies.set('access_token', accessToken);
GitHubApi.auth(accessToken)
.then(() => GitHubApi.getUser())
.then(user => {
const { login, avatar_url } = user;
this.props.setUser({ login, avatar_url });
})
.then(() => this.loadScratchPapers())
.catch(() => this.signOut());
}
signOut() {
Cookies.remove('access_token');
GitHubApi.auth(undefined)
.then(() => {
this.props.setUser(undefined);
})
.then(() => this.props.setScratchPapers([]));
}
loadScratchPapers() {
const per_page = 100;
const paginateGists = (page = 1, scratchPapers = []) => GitHubApi.listGists({
per_page,
page,
timestamp: Date.now(),
}).then(gists => {
scratchPapers.push(...gists.filter(gist => 'algorithm-visualizer' in gist.files).map(gist => ({
key: gist.id,
name: gist.description,
files: Object.keys(gist.files),
})));
if (gists.length < per_page) {
return scratchPapers;
} else {
return paginateGists(page + 1, scratchPapers);
}
});
return paginateGists()
.then(scratchPapers => this.props.setScratchPapers(scratchPapers))
.catch(this.handleError);
}
loadAlgorithm({ categoryKey, algorithmKey, gistId }, { visualizationId }) {
const { ext } = this.props.env;
const fetch = () => {
if (window.__PRELOADED_ALGORITHM__) {
this.props.setAlgorithm(window.__PRELOADED_ALGORITHM__);
delete window.__PRELOADED_ALGORITHM__;
} else if (window.__PRELOADED_ALGORITHM__ === null) {
delete window.__PRELOADED_ALGORITHM__;
return Promise.reject(new Error('Algorithm Not Found'));
} else if (categoryKey && algorithmKey) {
return AlgorithmApi.getAlgorithm(categoryKey, algorithmKey)
.then(({ algorithm }) => this.props.setAlgorithm(algorithm));
} else if (gistId === 'new' && visualizationId) {
return VisualizationApi.getVisualization(visualizationId)
.then(content => {
this.props.setScratchPaper({
login: undefined,
gistId,
title: 'Untitled',
files: [SCRATCH_PAPER_README_MD, createUserFile('visualization.json', JSON.stringify(content))],
});
});
} else if (gistId === 'new') {
const language = languages.find(language => language.ext === ext);
this.props.setScratchPaper({
login: undefined,
gistId,
title: 'Untitled',
files: [SCRATCH_PAPER_README_MD, language.skeleton],
});
} else if (gistId) {
return GitHubApi.getGist(gistId, { timestamp: Date.now() })
.then(refineGist)
.then(this.props.setScratchPaper);
} else {
this.props.setHome();
}
return Promise.resolve();
};
fetch()
.then(() => {
this.selectDefaultTab();
return null; // to suppress unnecessary bluebird warning
})
.catch(error => {
this.handleError(error);
this.props.history.push('/');
});
}
selectDefaultTab() {
const { ext } = this.props.env;
const { files } = this.props.current;
const editingFile = files.find(file => extension(file.name) === 'json') ||
files.find(file => extension(file.name) === ext) ||
files.find(file => exts.includes(extension(file.name))) ||
files[files.length - 1];
this.props.setEditingFile(editingFile);
}
handleChangeWorkspaceWeights(workspaceWeights) {
this.setState({ workspaceWeights });
this.codeEditorRef.current.handleResize();
}
toggleNavigatorOpened(navigatorOpened = !this.state.workspaceVisibles[0]) {
const workspaceVisibles = [...this.state.workspaceVisibles];
workspaceVisibles[0] = navigatorOpened;
this.setState({ workspaceVisibles });
}
handleClickTitleBar() {
this.toggleNavigatorOpened();
}
render() {
const { workspaceVisibles, workspaceWeights } = this.state;
const { titles, description, saved } = this.props.current;
const title = `${saved ? '' : '(Unsaved) '}${titles.join(' - ')}`;
const [navigatorOpened] = workspaceVisibles;
return (
<div className={styles.app}>
<Helmet>
<title>{title}</title>
<meta name="description" content={description}/>
</Helmet>
<Header className={styles.header} onClickTitleBar={this.handleClickTitleBar}
navigatorOpened={navigatorOpened} loadScratchPapers={this.loadScratchPapers}
ignoreHistoryBlock={this.ignoreHistoryBlock}/>
<ResizableContainer className={styles.workspace} horizontal weights={workspaceWeights}
visibles={workspaceVisibles} onChangeWeights={this.handleChangeWorkspaceWeights}>
<Navigator/>
<VisualizationViewer className={styles.visualization_viewer}/>
<TabContainer className={styles.editor_tab_container}>
<CodeEditor ref={this.codeEditorRef}/>
</TabContainer>
</ResizableContainer>
<ToastContainer className={styles.toast_container}/>
</div>
);
}
}
export default connect(({ current, env }) => ({ current, env }), actions)(
App,
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Button/index.js | src/components/Button/index.js | import React from 'react';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import faExclamationCircle from '@fortawesome/fontawesome-free-solid/faExclamationCircle';
import faSpinner from '@fortawesome/fontawesome-free-solid/faSpinner';
import { classes } from 'common/util';
import { Ellipsis } from 'components';
import styles from './Button.module.scss';
class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
confirming: false,
};
this.timeout = null;
}
componentWillUnmount() {
if (this.timeout) {
window.clearTimeout(this.timeout);
this.timeout = undefined;
}
}
render() {
let { className, children, to, href, onClick, icon, reverse, selected, disabled, primary, active, confirmNeeded, inProgress, ...rest } = this.props;
const { confirming } = this.state;
if (confirmNeeded) {
if (confirming) {
className = classes(styles.confirming, className);
icon = faExclamationCircle;
children = <Ellipsis key="text">Click to Confirm</Ellipsis>;
const onClickOriginal = onClick;
onClick = () => {
if (onClickOriginal) onClickOriginal();
if (this.timeout) {
window.clearTimeout(this.timeout);
this.timeout = undefined;
this.setState({ confirming: false });
}
};
} else {
to = null;
href = null;
onClick = () => {
this.setState({ confirming: true });
this.timeout = window.setTimeout(() => {
this.timeout = undefined;
this.setState({ confirming: false });
}, 2000);
};
}
}
const iconOnly = !children;
const props = {
className: classes(styles.button, reverse && styles.reverse, selected && styles.selected, disabled && styles.disabled, primary && styles.primary, active && styles.active, iconOnly && styles.icon_only, className),
to: disabled ? null : to,
href: disabled ? null : href,
onClick: disabled ? null : onClick,
children: [
icon && (
typeof icon === 'string' ?
<div className={classes(styles.icon, styles.image)} key="icon"
style={{ backgroundImage: `url(${icon})` }} /> :
<FontAwesomeIcon className={styles.icon} fixedWidth icon={inProgress ? faSpinner : icon} spin={inProgress}
key="icon" />
),
children,
],
...rest,
};
return to ? (
<Link {...props} />
) : href ? (
<a rel="noopener" target="_blank" {...props} />
) : (
<div {...props} />
);
}
}
export default Button;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/ResizableContainer/index.js | src/components/ResizableContainer/index.js | import React from 'react';
import { classes } from 'common/util';
import { Divider } from 'components';
import styles from './ResizableContainer.module.scss';
class ResizableContainer extends React.Component {
handleResize(prevIndex, index, targetElement, clientX, clientY) {
const { horizontal, visibles, onChangeWeights } = this.props;
const weights = [...this.props.weights];
const { left, top } = targetElement.getBoundingClientRect();
const { offsetWidth, offsetHeight } = targetElement.parentElement;
const position = horizontal ? clientX - left : clientY - top;
const containerSize = horizontal ? offsetWidth : offsetHeight;
let totalWeight = 0;
let subtotalWeight = 0;
weights.forEach((weight, i) => {
if (visibles && !visibles[i]) return;
totalWeight += weight;
if (i < index) subtotalWeight += weight;
});
const newWeight = position / containerSize * totalWeight;
let deltaWeight = newWeight - subtotalWeight;
deltaWeight = Math.max(deltaWeight, -weights[prevIndex]);
deltaWeight = Math.min(deltaWeight, weights[index]);
weights[prevIndex] += deltaWeight;
weights[index] -= deltaWeight;
onChangeWeights(weights);
}
render() {
const { className, children, horizontal, weights, visibles } = this.props;
const elements = [];
let lastIndex = -1;
const totalWeight = weights.filter((weight, i) => !visibles || visibles[i])
.reduce((sumWeight, weight) => sumWeight + weight, 0);
children.forEach((child, i) => {
if (!visibles || visibles[i]) {
if (~lastIndex) {
const prevIndex = lastIndex;
elements.push(
<Divider key={`divider-${i}`} horizontal={horizontal}
onResize={((target, dx, dy) => this.handleResize(prevIndex, i, target, dx, dy))} />,
);
}
elements.push(
<div key={i} className={classes(styles.wrapper)} style={{
flexGrow: weights[i] / totalWeight,
}}>
{child}
</div>,
);
lastIndex = i;
}
});
return (
<div className={classes(styles.resizable_container, horizontal && styles.horizontal, className)}>
{elements}
</div>
);
}
}
export default ResizableContainer;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Header/index.js | src/components/Header/index.js | import React from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import AutosizeInput from 'react-input-autosize';
import screenfull from 'screenfull';
import Promise from 'bluebird';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import faAngleRight from '@fortawesome/fontawesome-free-solid/faAngleRight';
import faCaretDown from '@fortawesome/fontawesome-free-solid/faCaretDown';
import faCaretRight from '@fortawesome/fontawesome-free-solid/faCaretRight';
import faCodeBranch from '@fortawesome/fontawesome-free-solid/faCodeBranch';
import faExpandArrowsAlt from '@fortawesome/fontawesome-free-solid/faExpandArrowsAlt';
import faGithub from '@fortawesome/fontawesome-free-brands/faGithub';
import faTrashAlt from '@fortawesome/fontawesome-free-solid/faTrashAlt';
import faSave from '@fortawesome/fontawesome-free-solid/faSave';
import faFacebook from '@fortawesome/fontawesome-free-brands/faFacebook';
import faStar from '@fortawesome/fontawesome-free-solid/faStar';
import { GitHubApi } from 'apis';
import { classes, refineGist } from 'common/util';
import { actions } from 'reducers';
import { languages } from 'common/config';
import { BaseComponent, Button, Ellipsis, ListItem, Player } from 'components';
import styles from './Header.module.scss';
class Header extends BaseComponent {
handleClickFullScreen() {
if (screenfull.enabled) {
if (screenfull.isFullscreen) {
screenfull.exit();
} else {
screenfull.request();
}
}
}
handleChangeTitle(e) {
const { value } = e.target;
this.props.modifyTitle(value);
}
saveGist() {
const { user } = this.props.env;
const { scratchPaper, titles, files, lastFiles, editingFile } = this.props.current;
const gist = {
description: titles[titles.length - 1],
files: {},
};
files.forEach(file => {
gist.files[file.name] = {
content: file.content,
};
});
lastFiles.forEach(lastFile => {
if (!(lastFile.name in gist.files)) {
gist.files[lastFile.name] = null;
}
});
gist.files['algorithm-visualizer'] = {
content: 'https://algorithm-visualizer.org/',
};
const save = gist => {
if (!user) return Promise.reject(new Error('Sign In Required'));
if (scratchPaper && scratchPaper.login) {
if (scratchPaper.login === user.login) {
return GitHubApi.editGist(scratchPaper.gistId, gist);
} else {
return GitHubApi.forkGist(scratchPaper.gistId).then(forkedGist => GitHubApi.editGist(forkedGist.id, gist));
}
}
return GitHubApi.createGist(gist);
};
save(gist)
.then(refineGist)
.then(newScratchPaper => {
this.props.setScratchPaper(newScratchPaper);
this.props.setEditingFile(newScratchPaper.files.find(file => file.name === editingFile.name));
if (!(scratchPaper && scratchPaper.gistId === newScratchPaper.gistId)) {
this.props.history.push(`/scratch-paper/${newScratchPaper.gistId}`);
}
})
.then(this.props.loadScratchPapers)
.catch(this.handleError);
}
hasPermission() {
const { scratchPaper } = this.props.current;
const { user } = this.props.env;
if (!scratchPaper) return false;
if (scratchPaper.gistId !== 'new') {
if (!user) return false;
if (scratchPaper.login !== user.login) return false;
}
return true;
}
deleteGist() {
const { scratchPaper } = this.props.current;
const { gistId } = scratchPaper;
if (gistId === 'new') {
this.props.ignoreHistoryBlock(() => this.props.history.push('/'));
} else {
GitHubApi.deleteGist(gistId)
.then(() => {
this.props.ignoreHistoryBlock(() => this.props.history.push('/'));
})
.then(this.props.loadScratchPapers)
.catch(this.handleError);
}
}
render() {
const { className, onClickTitleBar, navigatorOpened } = this.props;
const { scratchPaper, titles, saved } = this.props.current;
const { ext, user } = this.props.env;
const permitted = this.hasPermission();
return (
<header className={classes(styles.header, className)}>
<div className={styles.row}>
<div className={styles.section}>
<Button className={styles.title_bar} onClick={onClickTitleBar}>
{
titles.map((title, i) => [
scratchPaper && i === 1 ?
<AutosizeInput className={styles.input_title} key={`title-${i}`} value={title}
onClick={e => e.stopPropagation()} onChange={e => this.handleChangeTitle(e)}/> :
<Ellipsis key={`title-${i}`}>{title}</Ellipsis>,
i < titles.length - 1 &&
<FontAwesomeIcon className={styles.nav_arrow} fixedWidth icon={faAngleRight} key={`arrow-${i}`}/>,
])
}
<FontAwesomeIcon className={styles.nav_caret} fixedWidth
icon={navigatorOpened ? faCaretDown : faCaretRight}/>
</Button>
</div>
<div className={styles.section}>
<Button icon={permitted ? faSave : faCodeBranch} primary disabled={permitted && saved}
onClick={() => this.saveGist()}>{permitted ? 'Save' : 'Fork'}</Button>
{
permitted &&
<Button icon={faTrashAlt} primary onClick={() => this.deleteGist()} confirmNeeded>Delete</Button>
}
<Button icon={faFacebook} primary
href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(window.location.href)}`}>Share</Button>
<Button icon={faExpandArrowsAlt} primary
onClick={() => this.handleClickFullScreen()}>Fullscreen</Button>
</div>
</div>
<div className={styles.row}>
<div className={styles.section}>
{
user ?
<Button className={styles.btn_dropdown} icon={user.avatar_url}>
{user.login}
<div className={styles.dropdown}>
<ListItem label="Sign Out" href="/api/auth/destroy" rel="opener"/>
</div>
</Button> :
<Button icon={faGithub} primary href="/api/auth/request" rel="opener">
<Ellipsis>Sign In</Ellipsis>
</Button>
}
<Button className={styles.btn_dropdown} icon={faStar}>
{languages.find(language => language.ext === ext).name}
<div className={styles.dropdown}>
{
languages.map(language => language.ext === ext ? null : (
<ListItem key={language.ext} onClick={() => this.props.setExt(language.ext)}
label={language.name}/>
))
}
</div>
</Button>
</div>
<Player className={styles.section}/>
</div>
</header>
);
}
}
export default withRouter(
connect(({ current, env }) => ({ current, env }), actions)(
Header,
),
);
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/Divider/index.js | src/components/Divider/index.js | import React from 'react';
import { classes } from 'common/util';
import styles from './Divider.module.scss';
class Divider extends React.Component {
constructor(props) {
super(props);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
}
handleMouseDown(e) {
this.target = e.target;
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
}
handleMouseMove(e) {
const { onResize } = this.props;
if (onResize) onResize(this.target.parentElement, e.clientX, e.clientY);
}
handleMouseUp(e) {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
render() {
const { className, horizontal } = this.props;
return (
<div className={classes(styles.divider, horizontal ? styles.horizontal : styles.vertical, className)}
onMouseDown={this.handleMouseDown} />
);
}
}
export default Divider;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/components/BaseComponent/index.js | src/components/BaseComponent/index.js | import React from 'react';
class BaseComponent extends React.Component {
constructor(props) {
super(props);
this.handleError = this.handleError.bind(this);
}
handleError(error) {
if (error.response) {
const { data, statusText } = error.response;
const message = data ? typeof data === 'string' ? data : JSON.stringify(data) : statusText;
console.error(message);
this.props.showErrorToast(message);
} else {
console.error(error.message);
this.props.showErrorToast(error.message);
}
}
}
export default BaseComponent;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/files/index.js | src/files/index.js | import { createProjectFile, createUserFile } from 'common/util';
const getName = filePath => filePath.split('/').pop();
const getContent = filePath => require('!raw-loader!./' + filePath).default;
const readProjectFile = filePath => createProjectFile(getName(filePath), getContent(filePath));
const readUserFile = filePath => createUserFile(getName(filePath), getContent(filePath));
export const CODE_CPP = readUserFile('skeletons/code.cpp');
export const CODE_JAVA = readUserFile('skeletons/code.java');
export const CODE_JS = readUserFile('skeletons/code.js');
export const ROOT_README_MD = readProjectFile('algorithm-visualizer/README.md');
export const SCRATCH_PAPER_README_MD = readProjectFile('scratch-paper/README.md');
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/files/skeletons/code.js | src/files/skeletons/code.js | // import visualization libraries {
const { Array2DTracer, Layout, LogTracer, Tracer, VerticalLayout } = require('algorithm-visualizer');
// }
// define tracer variables {
const array2dTracer = new Array2DTracer('Grid');
const logTracer = new LogTracer('Console');
// }
// define input variables
const messages = [
'Visualize',
'your',
'own',
'code',
'here!',
];
// highlight each line of messages recursively
function highlight(line) {
if (line >= messages.length) return;
const message = messages[line];
// visualize {
logTracer.println(message);
array2dTracer.selectRow(line, 0, message.length - 1);
Tracer.delay();
array2dTracer.deselectRow(line, 0, message.length - 1);
// }
highlight(line + 1);
}
(function main() {
// visualize {
Layout.setRoot(new VerticalLayout([array2dTracer, logTracer]));
array2dTracer.set(messages);
Tracer.delay();
// }
highlight(0);
})();
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/common/config.js | src/common/config.js | import { CODE_CPP, CODE_JAVA, CODE_JS } from 'files';
const languages = [{
name: 'JavaScript',
ext: 'js',
mode: 'javascript',
skeleton: CODE_JS,
}, {
name: 'C++',
ext: 'cpp',
mode: 'c_cpp',
skeleton: CODE_CPP,
}, {
name: 'Java',
ext: 'java',
mode: 'java',
skeleton: CODE_JAVA,
}];
const exts = languages.map(language => language.ext);
export {
languages,
exts,
};
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/common/util.js | src/common/util.js | const classes = (...arr) => arr.filter(v => v).join(' ');
const distance = (a, b) => {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
};
const extension = fileName => /(?:\.([^.]+))?$/.exec(fileName)[1];
const refineGist = gist => {
const gistId = gist.id;
const title = gist.description;
delete gist.files['algorithm-visualizer'];
const { login, avatar_url } = gist.owner;
const files = Object.values(gist.files).map(file => ({
name: file.filename,
content: file.content,
contributors: [{ login, avatar_url }],
}));
return { login, gistId, title, files };
};
const createFile = (name, content, contributors) => ({ name, content, contributors });
const createProjectFile = (name, content) => createFile(name, content, [{
login: 'algorithm-visualizer',
avatar_url: 'https://github.com/algorithm-visualizer.png',
}]);
const createUserFile = (name, content) => createFile(name, content, undefined);
const isSaved = ({ titles, files, lastTitles, lastFiles }) => {
const serialize = (titles, files) => JSON.stringify({
titles,
files: files.map(({ name, content }) => ({ name, content })),
});
return serialize(titles, files) === serialize(lastTitles, lastFiles);
};
export {
classes,
distance,
extension,
refineGist,
createFile,
createProjectFile,
createUserFile,
isSaved,
};
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/index.js | src/core/renderers/index.js | export { default as Renderer } from './Renderer';
export { default as MarkdownRenderer } from './MarkdownRenderer';
export { default as LogRenderer } from './LogRenderer';
export { default as Array2DRenderer } from './Array2DRenderer';
export { default as Array1DRenderer } from './Array1DRenderer';
export { default as ChartRenderer } from './ChartRenderer';
export { default as GraphRenderer } from './GraphRenderer';
export { default as ScatterRenderer } from './ScatterRenderer';
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/ChartRenderer/index.js | src/core/renderers/ChartRenderer/index.js | import React from 'react';
import { Bar } from 'react-chartjs-2';
import { Array1DRenderer } from 'core/renderers';
import styles from './ChartRenderer.module.scss';
class ChartRenderer extends Array1DRenderer {
renderData() {
const { data: [row] } = this.props.data;
const chartData = {
labels: row.map(col => `${col.value}`),
datasets: [{
backgroundColor: row.map(col => col.patched ? styles.colorPatched : col.selected ? styles.colorSelected : styles.colorFont),
data: row.map(col => col.value),
}],
};
return (
<Bar data={chartData} options={{
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
animation: false,
legend: false,
responsive: true,
maintainAspectRatio: false
}} />
);
}
}
export default ChartRenderer;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
algorithm-visualizer/algorithm-visualizer | https://github.com/algorithm-visualizer/algorithm-visualizer/blob/18de2edf6b629e843ee4bcedfa2208d22b253f0f/src/core/renderers/Renderer/index.js | src/core/renderers/Renderer/index.js | import React from 'react';
import styles from './Renderer.module.scss';
import { Ellipsis } from 'components';
import { classes } from 'common/util';
class Renderer extends React.Component {
constructor(props) {
super(props);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleWheel = this.handleWheel.bind(this);
this._handleMouseDown = this.handleMouseDown;
this._handleWheel = this.handleWheel;
this.togglePan(false);
this.toggleZoom(false);
this.lastX = null;
this.lastY = null;
this.centerX = 0;
this.centerY = 0;
this.zoom = 1;
this.zoomFactor = 1.01;
this.zoomMax = 20;
this.zoomMin = 1 / 20;
}
componentDidUpdate(prevProps, prevState, snapshot) {
}
togglePan(enable = !this.handleMouseDown) {
this.handleMouseDown = enable ? this._handleMouseDown : undefined;
}
toggleZoom(enable = !this.handleWheel) {
this.handleWheel = enable ? this._handleWheel : undefined;
}
handleMouseDown(e) {
const { clientX, clientY } = e;
this.lastX = clientX;
this.lastY = clientY;
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
}
handleMouseMove(e) {
const { clientX, clientY } = e;
const dx = clientX - this.lastX;
const dy = clientY - this.lastY;
this.centerX -= dx;
this.centerY -= dy;
this.refresh();
this.lastX = clientX;
this.lastY = clientY;
}
handleMouseUp(e) {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
handleWheel(e) {
e.preventDefault();
const { deltaY } = e;
this.zoom *= Math.pow(this.zoomFactor, deltaY);
this.zoom = Math.min(this.zoomMax, Math.max(this.zoomMin, this.zoom));
this.refresh();
}
toString(value) {
switch (typeof(value)) {
case 'number':
return [Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER, 0x7fffffff].includes(value) ? '∞' :
[Number.NEGATIVE_INFINITY, Number.MIN_SAFE_INTEGER, -0x80000000].includes(value) ? '-∞' :
Number.isInteger(value) ? value.toString() :
value.toFixed(3);
case 'boolean':
return value ? 'T' : 'F';
default:
return value;
}
}
refresh() {
this.forceUpdate();
}
renderData() {
return null;
}
render() {
const { className, title } = this.props;
return (
<div className={classes(styles.renderer, className)} onMouseDown={this.handleMouseDown}
onWheel={this.handleWheel}>
<Ellipsis className={styles.title}>{title}</Ellipsis>
{
this.renderData()
}
</div>
);
}
}
export default Renderer;
| javascript | MIT | 18de2edf6b629e843ee4bcedfa2208d22b253f0f | 2026-01-04T14:57:32.646812Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.