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/renderer/prefComponents/keybindings/KeybindingConfigurator.js | src/renderer/prefComponents/keybindings/KeybindingConfigurator.js | import { ipcRenderer } from 'electron'
import { isEqualAccelerator } from 'common/keybinding'
import getCommandDescriptionById from '@/commands/descriptions'
import { isOsx } from '@/util'
const SHORTCUT_TYPE_DEFAULT = 0
const SHORTCUT_TYPE_USER = 1
const getShortcutDescriptionById = id => {
const description = getCommandDescriptionById(id)
if (!description) {
return id
}
return description
}
export default class KeybindingConfigurator {
/**
* ctor
*
* @param {Map<String, String>} defaultKeybindings
* @param {Map<String, String>} userKeybindings
*/
constructor (defaultKeybindings, userKeybindings) {
this.defaultKeybindings = defaultKeybindings
this.keybindingList = this._buildUiKeybindingList(defaultKeybindings, userKeybindings)
this.isDirty = false
}
_buildUiKeybindingList (defaultKeybindings, userKeybindings) {
const uiKeybindings = []
for (const [id] of defaultKeybindings) {
if (!isOsx && id.startsWith('mt.')) {
// Skip MarkText menu that is only available on macOS.
continue
}
uiKeybindings.push(this._toUiKeybinding(id, defaultKeybindings, userKeybindings))
}
uiKeybindings.sort((a, b) => a.description.localeCompare(b.description))
return uiKeybindings
}
_toUiKeybinding (id, defaultKeybindings, userKeybindings) {
const description = getShortcutDescriptionById(id)
const userAccelerator = userKeybindings.get(id)
let type = SHORTCUT_TYPE_DEFAULT
// Overwrite accelerator if key is present (empty string unset old binding).
let accelerator
if (userAccelerator != null) {
type = SHORTCUT_TYPE_USER
accelerator = userAccelerator
} else {
accelerator = defaultKeybindings.get(id)
}
return { id, description, accelerator, type }
}
getKeybindings () {
return this.keybindingList
}
async save () {
if (!this.isDirty) {
return true
}
const userKeybindings = this._getUserKeybindingMap()
const result = await ipcRenderer.invoke('mt::keybinding-save-user-keybindings', userKeybindings)
if (result) {
this.isDirty = false
return true
}
return false
}
_getUserKeybindingMap () {
const userKeybindings = new Map()
for (const entry of this.keybindingList) {
const { id, accelerator, type } = entry
if (type !== SHORTCUT_TYPE_DEFAULT) {
userKeybindings.set(id, accelerator)
}
}
return userKeybindings
}
change (id, accelerator) {
const entry = this.keybindingList.find(entry => entry.id === id)
if (!entry) {
return false
}
if (accelerator && this._isDuplicate(accelerator)) {
return false
}
entry.accelerator = accelerator
entry.type = this._isDefaultBinding(id, accelerator)
? SHORTCUT_TYPE_DEFAULT
: SHORTCUT_TYPE_USER
this.isDirty = true
return true
}
unbind (id) {
return this.change(id, '')
}
resetToDefault (id) {
const accelerator = this.defaultKeybindings.get(id)
if (accelerator == null) { // allow empty string
return false
}
return this.change(id, accelerator)
}
async resetAll () {
const { defaultKeybindings, keybindingList } = this
for (const entry of keybindingList) {
const defaultAccelerator = defaultKeybindings.get(entry.id)
if (defaultAccelerator) {
entry.accelerator = defaultAccelerator
} else {
entry.accelerator = ''
}
entry.type = SHORTCUT_TYPE_DEFAULT
}
this.isDirty = true
return this.save()
}
getDefaultAccelerator (id) {
return this.defaultKeybindings.get(id)
}
_isDuplicate (accelerator) {
return accelerator !== '' && this.keybindingList.findIndex(entry => isEqualAccelerator(entry.accelerator, accelerator)) !== -1
}
_isDefaultBinding (id, accelerator) {
return this.defaultKeybindings.get(id) === accelerator
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/sideBar/config.js | src/renderer/prefComponents/sideBar/config.js | import GeneralIcon from '@/assets/icons/pref_general.svg'
import EditorIcon from '@/assets/icons/pref_editor.svg'
import MarkdownIcon from '@/assets/icons/pref_markdown.svg'
import ThemeIcon from '@/assets/icons/pref_theme.svg'
import ImageIcon from '@/assets/icons/pref_image.svg'
import SpellIcon from '@/assets/icons/pref_spellcheck.svg'
import KeyBindingIcon from '@/assets/icons/pref_key_binding.svg'
import preferences from '../../../main/preferences/schema'
export const category = [{
name: 'General',
label: 'general',
icon: GeneralIcon,
path: '/preference/general'
}, {
name: 'Editor',
label: 'editor',
icon: EditorIcon,
path: '/preference/editor'
}, {
name: 'Markdown',
label: 'markdown',
icon: MarkdownIcon,
path: '/preference/markdown'
}, {
name: 'Spelling',
label: 'spelling',
icon: SpellIcon,
path: '/preference/spelling'
}, {
name: 'Theme',
label: 'theme',
icon: ThemeIcon,
path: '/preference/theme'
}, {
name: 'Image',
label: 'image',
icon: ImageIcon,
path: '/preference/image'
}, {
name: 'Key Bindings',
label: 'keybindings',
icon: KeyBindingIcon,
path: '/preference/keybindings'
}]
export const searchContent = Object.keys(preferences).map(k => {
const { description, enum: emums } = preferences[k]
let [category, preference] = description.split('--')
if (Array.isArray(emums)) {
preference += ` optional values: ${emums.join(', ')}`
}
return {
category,
preference
}
})
.filter(({ category: ca }) => category.some(c => c.label === ca.toLowerCase()))
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/markdown/config.js | src/renderer/prefComponents/markdown/config.js | export const bulletListMarkerOptions = [{
label: '*',
value: '*'
}, {
label: '-',
value: '-'
}, {
label: '+',
value: '+'
}]
export const orderListDelimiterOptions = [{
label: '.',
value: '.'
}, {
label: ')',
value: ')'
}]
export const preferHeadingStyleOptions = [{
label: 'ATX heading',
value: 'atx'
}, {
label: 'Setext heading',
value: 'setext'
}]
export const listIndentationOptions = [{
label: 'DocFX style',
value: 'dfm'
}, {
label: 'True tab character',
value: 'tab'
}, {
label: 'Single space character',
value: 1
}, {
label: 'Two space characters',
value: 2
}, {
label: 'Three space characters',
value: 3
}, {
label: 'Four space characters',
value: 4
}]
export const frontmatterTypeOptions = [{
label: 'YAML',
value: '-'
}, {
label: 'TOML',
value: '+'
}, {
label: 'JSON (;;;)',
value: ';'
}, {
label: 'JSON ({})',
value: '{'
}]
export const sequenceThemeOptions = [{
label: 'Hand drawn',
value: 'hand'
}, {
label: 'Simple',
value: 'simple'
}]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/components/exportSettings/exportOptions.js | src/renderer/components/exportSettings/exportOptions.js | export const pageSizeList = [
{
label: 'A3 (297mm x 420mm)',
value: 'A3'
}, {
label: 'A4 (210mm x 297mm)',
value: 'A4'
}, {
label: 'A5 (148mm x 210mm)',
value: 'A5'
}, {
label: 'US Legal (8.5" x 13")',
value: 'Legal'
}, {
label: 'US Letter (8.5" x 11")',
value: 'Letter'
}, {
label: 'Tabloid (17" x 11")',
value: 'Tabloid'
}, {
label: 'Custom',
value: 'custom'
}
]
export const headerFooterTypes = [
{
label: 'None',
value: 0
}, {
label: 'Single cell',
value: 1
}, {
label: 'Three cells',
value: 2
}
]
export const headerFooterStyles = [
{
label: 'Default',
value: 0
}, {
label: 'Simple',
value: 1
}, {
label: 'Styled',
value: 2
}
]
export const exportThemeList = [{
label: 'Academic',
value: 'academic'
}, {
label: 'GitHub (Default)',
value: 'default'
}, {
label: 'Liber',
value: 'liber'
}]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/components/sideBar/help.js | src/renderer/components/sideBar/help.js | import FilesIcon from '@/assets/icons/files.svg'
import SearchIcon from '@/assets/icons/search.svg'
import TocIcon from '@/assets/icons/toc.svg'
import SettingIcon from '@/assets/icons/setting.svg'
export const sideBarIcons = [
{
name: 'files',
icon: FilesIcon
}, {
name: 'search',
icon: SearchIcon
}, {
name: 'toc',
icon: TocIcon
}
]
export const sideBarBottomIcons = [
{
name: 'settings',
icon: SettingIcon
}
]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/axios/index.js | src/renderer/axios/index.js | import axios from 'axios'
import adapter from 'axios/lib/adapters/http'
axios.defaults.adapter = adapter
const http = axios.create({
adapter
})
export default http
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/assets/window-controls.js | src/renderer/assets/window-controls.js | /*
Copyright (c) GitHub, Inc.
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.
*/
// These paths are all drawn to a 10x10 view box and replicate the symbols
// seen on Windows 10 window controls.
export const closePath =
'M 0,0 0,0.7 4.3,5 0,9.3 0,10 0.7,10 5,5.7 9.3,10 10,10 10,9.3 5.7,5 10,0.7 10,0 9.3,0 5,4.3 0.7,0 Z'
export const restorePath =
'm 2,1e-5 0,2 -2,0 0,8 8,0 0,-2 2,0 0,-8 z m 1,1 6,0 0,6 -1,0 0,-5 -5,0 z m -2,2 6,0 0,6 -6,0 z'
export const maximizePath = 'M 0,0 0,10 10,10 10,0 Z M 1,1 9,1 9,9 1,9 Z'
export const minimizePath = 'M 0,5 10,5 10,6 0,6 Z'
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/assets/symbolIcon/index.js | src/renderer/assets/symbolIcon/index.js | (function(window){var svgSprite='<svg><symbol id="icon-info" viewBox="0 0 1024 1024"><path d="M512 35.776C249.024 35.776 35.776 249.024 35.776 512S249.024 988.224 512 988.224 988.224 774.976 988.224 512 774.976 35.776 512 35.776zM563.776 748.224l-96 0 0-288 96 0L563.776 748.224zM515.776 388.224c-39.744 0-72-32.256-72-72s32.256-72 72-72S587.776 276.48 587.776 316.224 555.52 388.224 515.776 388.224z" ></path></symbol><symbol id="icon-findreplace" viewBox="0 0 1024 1024"><path d="M469.333333 256c58.88 0 112.213333 23.893333 150.826667 62.506667l-108.16 108.16 256 0 0-256-87.466667 87.466667c-53.973333-53.973333-128.64-87.466667-211.2-87.466667-150.4 0-274.56 111.36-295.253333 256l86.186667 0c19.84-97.28 105.813333-170.666667 209.066667-170.666667zM709.973333 645.76c28.373333-38.613333 47.573333-84.266667 54.613333-133.76l-86.186667 0c-19.84 97.28-105.813333 170.666667-209.066667 170.666667-58.88 0-112.213333-23.893333-150.826667-62.506667l108.16-108.16-256 0 0 256 87.466667-87.466667c53.973333 53.973333 128.64 87.466667 211.2 87.466667 66.133333 0 127.146667-21.76 176.64-58.24l207.36 207.146667 63.573333-63.573333-206.933333-207.573333z" ></path></symbol><symbol id="icon-collected" viewBox="0 0 1024 1024"><path d="M695.984 103.984l-400.16 0c-53.008 0-96 42.992-96 96l0 288c0 1.04 0.128 2.048 0.16 3.088l0 423.184 297.904-133.328 294.096 133.328L791.984 487.984l0-64 0-224C791.984 146.976 748.992 103.984 695.984 103.984zM589.68 596.8l-99.76-52.576-98.128 55.568 19.568-110.432-83.568-75.456 111.84-15.68 46.48-102.192 49.584 100.752 112.288 12.288-81.216 77.952L589.68 596.8z" ></path></symbol><symbol id="icon-warn" viewBox="0 0 1024 1024"><path d="M512.000512 31.565926c-265.345344 0-480.434074 215.09794-480.434074 480.434074 0 265.325901 215.08873 480.434074 480.434074 480.434074 265.346367 0 480.434074-215.108173 480.434074-480.434074C992.434585 246.662843 777.345856 31.565926 512.000512 31.565926zM559.809377 774.364453l-95.618754 0 0-92.154863 95.618754 0L559.809377 774.364453zM559.802214 627.249861l-95.598288 0.002047-0.014326-386.999055 95.618754 0.026606L559.802214 627.249861z" ></path></symbol><symbol id="icon-list" viewBox="0 0 1024 1024"><path d="M128.952442 162.509211c-35.902698 0-64.99734 28.940123-64.99734 64.617693 0 35.677571 29.094642 64.60746 64.99734 64.60746s65.00041-28.92989 65.00041-64.60746C193.951829 191.450357 164.85514 162.509211 128.952442 162.509211L128.952442 162.509211zM933.280324 158.802796 294.242999 158.802796c-14.795984 0-26.761504 11.916401-26.761504 26.601868l0 73.653487c0 14.700817 11.961426 26.601868 26.761504 26.601868l639.038348 0c14.781658 0 26.762527-11.900028 26.762527-26.601868l0-73.653487C960.043874 170.718173 948.063005 158.802796 933.280324 158.802796L933.280324 158.802796zM933.280324 440.756399 294.242999 440.756399c-14.795984 0-26.761504 11.906168-26.761504 26.612101l0 73.646324c0 14.691607 11.961426 26.601868 26.761504 26.601868l639.038348 0c14.781658 0 26.762527-11.910261 26.762527-26.601868L960.043874 467.367477C960.043874 452.661543 948.063005 440.756399 933.280324 440.756399L933.280324 440.756399zM933.280324 722.707956 294.242999 722.707956c-14.795984 0-26.761504 11.905144-26.761504 26.590612l0 73.658603c0 14.685467 11.961426 26.611078 26.761504 26.611078l639.038348 0c14.781658 0 26.762527-11.92561 26.762527-26.611078l0-73.658603C960.043874 734.6131 948.063005 722.707956 933.280324 722.707956L933.280324 722.707956zM128.952442 444.462814c-35.902698 0-64.99734 28.930913-64.99734 64.617693 0 35.671431 29.094642 64.602344 64.99734 64.602344s65.00041-28.92989 65.00041-64.602344C193.951829 473.393727 164.85514 444.462814 128.952442 444.462814L128.952442 444.462814zM128.952442 726.418464c-35.902698 0-64.99734 28.92989-64.99734 64.608483s29.094642 64.60439 64.99734 64.60439 65.00041-28.92682 65.00041-64.60439S164.85514 726.418464 128.952442 726.418464L128.952442 726.418464zM128.952442 726.418464" ></path></symbol><symbol id="icon-header" viewBox="0 0 1024 1024"><path d="M905 896q-22 0-66.25-1.75t-66.75-1.75q-22 0-66 1.75t-66 1.75q-12 0-18.5-10.25t-6.5-22.75q0-15.5 8.5-23t19.5-8.5 25.5-3.5 22.5-7.5q16.5-10.5 16.5-70l-0.5-195.5q0-10.5-0.5-15.5-6.5-2-25-2l-337.5 0q-19 0-25.5 2-0.5 5-0.5 15.5l-0.5 185.5q0 71 18.5 82 8 5 24 6.5t28.5 1.75 22.5 7.5 10 22.75q0 13-6.25 24t-18.25 11q-23.5 0-69.75-1.75t-69.25-1.75q-21.5 0-64 1.75t-63.5 1.75q-11.5 0-17.75-10.5t-6.25-22.5q0-15 7.75-22.5t18-8.75 23.75-3.75 21-7.5q16.5-11.5 16.5-71.5l-0.5-28.5 0-406.5q0-1.5 2.5-13t0-18.25-0.75-19.25-1.75-21-3.25-18.25-5.5-15.75-8-9q-7.5-5-22.5-6t-26.5-1-20.5-7-9-22.5q0-13 6-24t18-11q23 0 69.25 1.75t69.25 1.75q21 0 63.25-1.75t63.25-1.75q12.5 0 18.75 11t6.25 24q0 15-8.5 21.75t-19.25 7.25-24.75 2-21.5 6.5q-17.5 10.5-17.5 80l0.5 160q0 10.5 0.5 16 6.5 1.5 19.5 1.5l349.5 0q12.5 0 19-1.5 0.5-5.5 0.5-16l0.5-160q0-69.5-17.5-80-9-5.5-29.25-6.25t-33-6.5-12.75-24.75q0-13 6.25-24t18.75-11q22 0 66 1.75t66 1.75q21.5 0 64.5-1.75t64.5-1.75q12.5 0 18.75 11t6.25 24q0 15-8.75 22t-20 7.25-25.75 1.5-22 6.25q-17.5 11.5-17.5 80.5l0.5 471.5q0 59.5 17 70 8 5 23 6.75t26.75 2.25 20.75 7.75 9 22.25q0 13-6 24t-18 11z" ></path></symbol><symbol id="icon-close-small" viewBox="0 0 1024 1024"><path d="M851.456 755.419429q0 22.820571-16.018286 38.838857l-77.677714 77.677714q-16.018286 16.018286-38.838857 16.018286t-38.838857-16.018286l-168.009143-168.009143-168.009143 168.009143q-16.018286 16.018286-38.838857 16.018286t-38.838857-16.018286l-77.677714-77.677714q-16.018286-16.018286-16.018286-38.838857t16.018286-38.838857l168.009143-168.009143-168.009143-168.009143q-16.018286-16.018286-16.018286-38.838857t16.018286-38.838857l77.677714-77.677714q16.018286-16.018286 38.838857-16.018286t38.838857 16.018286l168.009143 168.009143 168.009143-168.009143q16.018286-16.018286 38.838857-16.018286t38.838857 16.018286l77.677714 77.677714q16.018286 16.018286 16.018286 38.838857t-16.018286 38.838857l-168.009143 168.009143 168.009143 168.009143q16.018286 16.018286 16.018286 38.838857z" ></path></symbol><symbol id="icon-twitter" viewBox="0 0 1024 1024"><path d="M962.267429 233.179429q-38.253714 56.027429-92.598857 95.451429 0.585143 7.972571 0.585143 23.990857 0 74.313143-21.723429 148.260571t-65.974857 141.970286-105.398857 120.32-147.456 83.456-184.539429 31.158857q-154.843429 0-283.428571-82.870857 19.968 2.267429 44.544 2.267429 128.585143 0 229.156571-78.848-59.977143-1.170286-107.446857-36.864t-65.170286-91.136q18.870857 2.852571 34.889143 2.852571 24.576 0 48.566857-6.290286-64-13.165714-105.984-63.707429t-41.984-117.394286l0-2.267429q38.838857 21.723429 83.456 23.405714-37.741714-25.161143-59.977143-65.682286t-22.308571-87.990857q0-50.322286 25.161143-93.110857 69.12 85.138286 168.301714 136.265143t212.260571 56.832q-4.534857-21.723429-4.534857-42.276571 0-76.580571 53.979429-130.56t130.56-53.979429q80.018286 0 134.875429 58.294857 62.317714-11.995429 117.174857-44.544-21.138286 65.682286-81.115429 101.741714 53.174857-5.705143 106.276571-28.598857z" ></path></symbol><symbol id="icon-table" viewBox="0 0 1024 1024"><path d="M329.124352 786.300928l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm0-219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm292.552704 219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm-292.552704-438.829056l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm292.552704 219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm292.552704 219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm-292.552704-438.829056l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm292.552704 219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm0-219.414528l0-109.707264q0-7.999488-5.142528-13.142016t-13.142016-5.142528l-182.84544 0q-7.999488 0-13.142016 5.142528t-5.142528 13.142016l0 109.707264q0 7.999488 5.142528 13.142016t13.142016 5.142528l182.84544 0q7.999488 0 13.142016-5.142528t5.142528-13.142016zm73.138176-182.84544l0 621.674496q0 37.711872-26.855424 64.567296t-64.567296 26.855424l-767.950848 0q-37.711872 0-64.567296-26.855424t-26.855424-64.567296l0-621.674496q0-37.711872 26.855424-64.567296t64.567296-26.855424l767.950848 0q37.711872 0 64.567296 26.855424t26.855424 64.567296z" ></path></symbol><symbol id="icon-folder-close" viewBox="0 0 1024 1024"><path d="M928.229 752.132c0 61.534-50.527 112.062-112.062 112.062L207.833 864.194c-61.534 0-112.062-50.527-112.062-112.062L95.771 271.868c0-61.534 50.528-112.062 112.062-112.062l160.088 0c61.534 0 112.062 50.528 112.062 112.062l0 16.009 336.185 0c61.534 0 112.062 50.528 112.062 112.062L928.23 752.132z" ></path></symbol><symbol id="icon-lineheight" viewBox="0 0 1024 1024"><path d="M158.185 167.101c3.261 1.398 88.526 2.33 98.311 2.33 41.001 0 82.003-1.864 123.004-1.864 33.547 0 66.628 0.466 100.174 0.466l136.517 0c18.638 0 29.354 4.193 41.934-13.512l19.569-0.466c4.193 0 8.853 0.466 13.046 0.466 0.932 52.184 0.932 104.368 0.932 156.552 0 16.307 0.466 34.479-2.33 50.786-10.25 3.727-20.967 6.989-31.683 8.387-10.716-18.637-18.171-39.138-25.16-59.639-3.262-9.319-14.443-72.219-15.376-73.151-9.784-12.114-20.5-9.785-34.944-9.785-42.399 0-86.663-1.863-128.596 3.262-2.33 20.501-4.193 42.399-3.728 63.366 0.466 130.925 1.864 261.85 1.864 392.776 0 35.877-5.591 73.616 4.66 108.095 35.41 18.172 77.344 20.967 113.686 37.274 0.933 7.455 2.33 15.376 2.33 23.297 0 4.193-0.466 8.853-1.397 13.512l-15.842 0.466c-66.162 1.863-131.392-8.387-198.02-8.387-47.059 0-94.117 8.387-141.176 8.387-0.466-7.921-1.398-16.308-1.398-24.229l0-4.193c17.705-28.421 81.537-28.887 110.891-46.127 10.25-22.83 8.853-149.096 8.853-178.449 0-94.117-2.795-188.234-2.795-282.352l0-54.514c0-8.387 1.864-41.934-3.728-48.457-6.523-6.989-67.56-5.591-75.48-5.591-17.239 0-67.094 7.92-80.605 17.705-22.365 15.375-22.365 108.561-50.32 110.425-8.387-5.125-20.035-12.58-26.092-20.501l0-178.45 37.74-0.466L158.185 167.101zM922.306 779.795l-58.707 75.48c-12.58 16.307-33.08 16.307-45.66 0l-58.707-75.48c-12.58-16.308-6.058-29.354 14.443-29.354l37.274 0L810.949 273.333l-37.274 0c-20.501 0-27.023-13.046-14.443-29.354l58.707-75.48c12.58-16.308 33.08-16.308 45.66 0l58.707 75.48c12.58 16.308 6.058 29.354-14.443 29.354l-37.274 0 0 477.109 37.274 0C928.363 750.441 934.886 763.487 922.306 779.795z" ></path></symbol><symbol id="icon-search" viewBox="0 0 1024 1024"><path d="M922.666667 876.373333 702.677333 648.405333C805.290667 511.701333 796.245333 314.133333 675.008 188.501333 609.344 120.448 523.264 86.421333 437.205333 86.421333 351.146667 86.421333 265.066667 120.448 199.402667 188.501333 68.074667 324.608 68.074667 545.258667 199.402667 681.344 265.066667 749.397333 351.146667 783.424 437.205333 783.424 510.058667 783.424 582.762667 758.762667 643.221333 710.016L863.210667 937.984 922.666667 876.373333ZM258.858667 619.733333C160.512 517.824 160.512 352.021333 258.858667 250.112 306.496 200.746667 369.834667 173.546667 437.205333 173.546667 504.576 173.546667 567.914667 200.746667 615.552 250.112 713.898667 352.021333 713.898667 517.824 615.552 619.733333 567.914667 669.098667 504.576 696.298667 437.205333 696.298667 369.834667 696.298667 306.496 669.098667 258.858667 619.733333Z" ></path></symbol><symbol id="icon-font" viewBox="0 0 1024 1024"><path d="M680.021333 790.016l89.984 0-217.984-555.989333-80 0-217.984 555.989333 89.984 0 48-128 240 0zM854.016 86.016q34.005333 0 59.008 25.002667t25.002667 59.008l0 683.989333q0 34.005333-25.002667 59.008t-59.008 25.002667l-683.989333 0q-34.005333 0-59.008-25.002667t-25.002667-59.008l0-683.989333q0-34.005333 25.002667-59.008t59.008-25.002667l683.989333 0zM424.021333 576l88.021333-235.989333 88.021333 235.989333-176 0z" ></path></symbol><symbol id="icon-shuffle" viewBox="0 0 1024 1024"><path d="M632.021333 571.989333l134.016 134.016 88.021333-88.021333 0 235.989333-235.989333 0 88.021333-88.021333-134.016-134.016zM617.984 169.984l235.989333 0 0 235.989333-88.021333-88.021333-536.021333 536.021333-59.989333-59.989333 536.021333-536.021333zM452.010667 392.021333l-59.989333 59.989333-221.994667-221.994667 59.989333-59.989333z" ></path></symbol><symbol id="icon-case" viewBox="0 0 1024 1024"><path d="M430.72 721.92l-24.64-64.768L196.544 657.152l-24.64 66.112c-9.6 25.792-17.792 43.264-24.576 52.224-6.784 9.024-17.92 13.568-33.408 13.568-13.12 0-24.704-4.8-34.752-14.464C69.056 765.056 64 754.176 64 742.016c0-7.04 1.152-14.336 3.52-21.824s6.208-17.92 11.648-31.296l131.84-334.784c3.776-9.536 8.256-21.12 13.504-34.56C229.76 305.984 235.456 294.784 241.408 285.952c5.952-9.024 13.824-16.192 23.616-21.696C274.688 258.816 286.656 256 300.992 256 315.52 256 327.616 258.816 337.344 264.256c9.728 5.504 17.6 12.608 23.616 21.312 5.952 8.64 11.008 17.984 15.04 27.968s9.344 23.296 15.68 39.872l134.656 332.672c10.624 25.344 15.872 43.776 15.872 55.232 0 11.968-4.992 22.848-14.976 32.832-9.92 9.984-21.952 14.976-35.968 14.976-8.256 0-15.232-1.472-21.12-4.352-5.888-2.944-10.752-6.912-14.72-12.032s-8.256-12.8-12.864-23.232C438.016 739.136 434.048 729.92 430.72 721.92zM224 578.816l153.984 0L300.288 366.08 224 578.816zM854.848 734.912c-23.232 18.048-45.696 31.616-67.392 40.64-21.632 9.024-46.016 13.568-72.96 13.568-24.64 0-46.272-4.864-64.96-14.656-18.624-9.664-33.024-22.848-43.072-39.552-10.048-16.64-15.104-34.688-15.104-54.144 0-26.24 8.32-48.64 25.024-67.136 16.64-18.56 39.424-30.976 68.544-37.312 6.144-1.408 21.248-4.544 45.376-9.472s44.8-9.408 62.08-13.568c17.216-4.032 35.968-9.088 56.064-14.912C847.36 513.088 842.24 494.528 833.28 482.624c-9.088-11.84-27.776-17.664-56.128-17.664-24.384 0-42.752 3.392-54.976 10.112-12.288 6.784-22.848 17.024-31.68 30.656-8.832 13.568-14.912 22.592-18.624 26.88-3.648 4.352-11.456 6.528-23.36 6.528-10.816 0-20.096-3.456-27.968-10.368C612.608 521.792 608.704 512.96 608.704 502.144c0-16.896 6.016-33.28 17.92-49.216 12.032-15.936 30.656-29.056 55.872-39.36 25.344-10.304 56.896-15.488 94.656-15.488 42.24 0 75.392 4.992 99.52 14.912 24.192 9.984 41.28 25.728 51.2 47.296s14.912 50.176 14.912 85.824c0 22.528-0.064 41.6-0.128 57.344-0.128 15.68-0.384 33.152-0.576 52.416 0 17.984 2.944 36.8 8.96 56.384S960 744.448 960 750.08c0 9.792-4.608 18.816-13.888 26.944-9.28 8.064-19.776 12.096-31.488 12.096-9.856 0-19.584-4.672-29.184-13.888C875.84 765.952 865.6 752.512 854.848 734.912zM848.512 595.968c-14.08 5.184-34.496 10.688-61.376 16.384-26.816 5.76-45.376 9.984-55.744 12.672-10.24 2.688-20.096 8-29.504 15.808-9.344 7.872-14.08 18.816-14.08 32.896 0 14.528 5.504 26.944 16.576 37.12 11.008 10.176 25.344 15.296 43.264 15.296 19.008 0 36.48-4.16 52.48-12.48 16.128-8.32 27.904-19.072 35.392-32.192 8.704-14.528 12.992-38.464 12.992-71.68L848.512 595.968z" ></path></symbol><symbol id="icon-fontsize" viewBox="0 0 1024 1024"><path d="M954.368 794.24l-34.816 0L754.56 391.808c0 0-4.736-6.656-14.656-7.744-9.92-1.024-25.28 5.184-25.28 5.184l-176 404.992L531.328 794.24C516.544 794.24 512 800.64 512 814.4 512 828.032 519.936 832 534.72 832l102.72 0c14.656 0 26.816-4.096 26.816-17.6 0-13.76-12.096-20.096-26.816-20.096L610.944 794.304l37.056-87.296 191.104 0 37.632 87.296-42.432 0c-14.784 0-26.88 6.4-26.88 20.096 0 13.696 12.032 17.6 26.88 17.6l120.064 0c14.848 0 26.816-3.968 26.816-17.6C981.184 800.64 969.28 794.24 954.368 794.24zM665.216 669.248 746.56 486.4l77.312 182.848L665.216 669.248zM261.056 772.608l-41.6 0 58.112-137.088 252.928 0 60.928-138.368L445.248 140.288c0 0-7.616-10.496-23.104-12.096C406.592 126.592 382.336 136.256 382.336 136.256l-276.544 636.352L94.464 772.608C71.104 772.608 64 782.656 64 804.224 64 825.728 76.544 832 99.776 832l161.344 0c23.296 0 42.176-6.4 42.176-27.776C303.232 782.656 284.352 772.608 261.056 772.608zM432.576 288.896l121.408 287.36L304.64 576.256 432.576 288.896z" ></path></symbol><symbol id="icon-replace" viewBox="0 0 1024 1024"><path d="M357.312 438.656 337.6 386.944 169.984 386.944 150.336 439.808c-7.68 20.608-14.272 34.56-19.712 41.728C125.184 488.832 116.224 492.352 103.872 492.352c-10.496 0-19.776-3.84-27.84-11.52S64 464.512 64 454.72c0-5.632 0.896-11.456 2.752-17.472 1.856-5.952 4.992-14.336 9.344-25.024l105.408-267.776c3.008-7.68 6.656-16.96 10.88-27.712 4.16-10.816 8.704-19.776 13.504-26.88C210.624 82.816 216.96 77.056 224.704 72.64c7.808-4.352 17.344-6.656 28.8-6.656 11.648 0 21.376 2.24 29.12 6.656C290.432 77.056 296.704 82.752 301.504 89.6 306.24 96.64 310.336 104.064 313.536 112c3.328 8 7.424 18.624 12.544 31.936l107.712 266.048C442.24 430.272 446.528 444.992 446.528 454.144c0 9.6-3.968 18.368-12.032 26.304-7.936 8-17.536 11.968-28.8 11.968-6.592 0-12.16-1.152-16.896-3.52C384.128 486.592 380.16 483.392 377.024 479.296c-3.2-3.968-6.656-10.176-10.24-18.56C363.072 452.416 359.936 445.056 357.312 438.656zM191.936 324.224l123.2 0L252.992 154.048 191.936 324.224zM821.504 960l-126.016 0c-18.176 0-31.168-4.032-38.912-12.224-7.808-8.128-11.712-21.12-11.712-38.912L644.864 598.848c0-18.176 3.968-31.232 11.968-39.232 8-7.936 20.864-11.968 38.656-11.968l133.568 0c19.776 0 36.736 1.28 51.264 3.712 14.4 2.432 27.328 7.104 38.72 14.016 9.728 5.888 18.368 13.184 25.856 22.144 7.488 8.896 13.248 18.752 17.216 29.504 3.968 10.816 5.952 22.208 5.952 34.176 0 41.28-20.672 71.424-61.888 90.56 54.144 17.28 81.28 50.816 81.28 100.672 0 23.04-5.888 43.84-17.728 62.336-11.776 18.432-27.776 32.128-47.744 40.896-12.608 5.312-27.008 9.024-43.392 11.136C862.336 958.912 843.264 960 821.504 960zM728.448 610.368l0 106.624 76.48 0c20.736 0 36.864-1.984 48.192-5.888 11.392-3.968 19.968-11.456 26.048-22.528 4.608-7.872 6.976-16.704 6.976-26.496 0-20.736-7.424-34.624-22.272-41.408-14.784-6.848-37.376-10.304-67.776-10.304L728.448 610.368zM815.296 776.896l-86.848 0 0 120.384 89.664 0c56.448 0 84.672-20.288 84.672-60.992 0-20.8-7.36-35.904-22.016-45.248S844.352 776.896 815.296 776.896zM928.32 213.184l-141.376-141.376c-10.24-10.368-27.008-10.368-37.376 0-10.368 10.432-10.368 27.2 0 37.568l84.416 84.416c-3.776-0.064-6.848-0.32-10.816-0.32-23.552 0.192-51.2 2.304-80.256 9.344-28.928 6.976-59.648 19.52-84.928 40C645.056 252.8 634.56 264.832 624.96 277.952 617.344 289.28 608.704 304.064 603.904 317.44c-10.816 27.072-14.656 53.824-14.72 76.352C588.928 439.04 599.552 467.008 599.552 467.008s-6.4-29.44 0.128-72.32c3.136-21.312 10.432-45.44 23.488-67.968 6.464-11.712 13.568-20.8 23.68-32.128 8.96-8.896 19.008-18.048 30.4-24.512 22.528-13.696 48.64-20.672 73.536-23.296 25.088-2.688 49.088-1.344 69.376 1.152 11.776 1.408 21.888 3.264 30.912 5.248L749.568 354.56c-10.368 10.368-10.368 27.136 0 37.568 5.12 5.184 11.904 7.744 18.624 7.744s13.632-2.56 18.752-7.744l141.376-141.376C938.688 240.384 938.688 223.488 928.32 213.184zM527.808 773.376 386.432 632c-5.12-5.248-12.032-7.744-18.752-7.744S354.176 626.752 349.056 632c-10.368 10.368-10.368 27.136 0 37.504l99.008 99.008c-11.264 1.6-23.808 3.2-38.912 4.416-47.616 3.584-115.008 4.864-170.688-22.016-13.696-6.848-25.728-15.808-36.48-26.112-10.624-11.712-20.288-23.616-27.776-36.48-15.744-25.792-25.728-53.312-32.064-77.376C129.408 562.496 129.472 528.256 129.472 528.256s-4.48 33.728 1.92 84.736c3.328 25.408 9.856 55.232 23.232 85.504 6.592 15.488 15.68 30.464 25.664 44.608 11.712 14.272 25.472 27.008 41.088 37.12 63.616 39.552 136.96 44.992 188.928 47.232 9.408 0.32 17.536 0.192 25.792 0.128l-87.104 87.104c-10.368 10.368-10.368 27.136 0 37.504s27.136 10.368 37.376 0l141.376-141.376C538.176 800.64 538.176 783.744 527.808 773.376z" ></path></symbol><symbol id="icon-table-3d" viewBox="0 0 1024 1024"><path d="M262.08 254.848c0 0-0.768 81.984-14.016 105.472C234.816 383.936 166.08 425.152 166.08 425.152S105.792 464.512 85.12 463.68C64.832 462.912 68.672 374.912 68.8 372.096c0-2.752-1.024-86.528 19.776-112.384 21.12-26.24 81.344-60.288 81.344-60.288s68.8-42.752 81.536-35.072C264.064 172.032 262.08 254.848 262.08 254.848zM482.56 23.296c-12.672-7.68-81.472 35.072-81.472 35.072s-60.16 34.048-81.28 60.288c-20.8 25.792-19.84 109.632-19.776 112.32-0.128 2.88-4.032 90.88 16.256 91.648 20.672 0.832 81.024-38.592 81.024-38.592s68.736-41.216 81.984-64.768 13.888-105.472 13.888-105.472S495.296 30.976 482.56 23.296zM246.912 429.248c-12.736-7.68-81.472 35.072-81.472 35.072s-60.16 34.048-81.344 60.288C63.296 550.528 64.32 634.24 64.384 636.992c-0.128 2.816-3.968 90.88 16.256 91.648 20.736 0.768 81.024-38.592 81.024-38.592s68.8-41.28 81.984-64.768c13.248-23.552 13.952-105.472 13.952-105.472S259.648 436.992 246.912 429.248zM478.144 288.256C465.408 280.512 396.608 323.264 396.608 323.264s-60.16 34.112-81.344 60.288C294.592 409.344 295.552 493.184 295.552 495.936c-0.064 2.816-3.968 90.88 16.32 91.648 20.672 0.768 80.96-38.656 80.96-38.656s68.736-41.216 81.984-64.768c13.312-23.488 13.952-105.408 13.952-105.408S490.816 295.936 478.144 288.256zM761.92 254.848c0 0 0.768 81.984 13.952 105.472 13.248 23.552 82.048 64.768 82.048 64.768s60.224 39.36 80.96 38.592c20.288-0.768 16.448-88.768 16.32-91.584 0-2.752 1.088-86.528-19.776-112.384-21.12-26.24-81.344-60.288-81.344-60.288s-68.8-42.752-81.472-35.072C759.872 172.032 761.92 254.848 761.92 254.848zM541.44 23.296c12.672-7.68 81.472 35.072 81.472 35.072s60.16 34.048 81.344 60.288c20.736 25.792 19.776 109.632 19.776 112.32 0.064 2.88 3.968 90.88-16.32 91.648-20.672 0.832-80.96-38.592-80.96-38.592S557.952 242.88 544.768 219.328C531.456 195.776 530.752 113.792 530.752 113.792S528.704 30.976 541.44 23.296zM777.088 429.248c12.736-7.68 81.472 35.072 81.472 35.072s60.16 34.048 81.344 60.288c20.8 25.856 19.84 109.632 19.776 112.384 0.128 2.816 3.968 90.88-16.256 91.648-20.736 0.768-81.024-38.592-81.024-38.592s-68.8-41.28-81.984-64.768c-13.248-23.552-14.016-105.472-14.016-105.472S764.352 436.992 777.088 429.248zM545.856 288.256c12.672-7.744 81.472 35.008 81.472 35.008s60.16 34.112 81.344 60.288c20.672 25.792 19.712 109.632 19.712 112.384 0.064 2.816 3.968 90.88-16.32 91.648-20.608 0.768-80.96-38.656-80.96-38.656S562.432 507.776 549.184 484.16c-13.248-23.488-14.08-105.408-14.08-105.408S533.184 295.936 545.856 288.256zM415.616 703.744c0 0 71.872 39.488 98.816 39.488 27.072 0 96.64-39.808 96.64-39.808s63.872-33.28 73.344-51.648c9.344-18.112-69.376-57.792-71.872-59.136C610.112 591.296 537.536 549.44 504.896 554.88c-33.28 5.568-92.416 41.344-92.416 41.344s-70.976 39.04-70.528 53.888C342.464 665.024 415.616 703.744 415.616 703.744zM105.728 782.656c-0.512-14.848 70.528-53.888 70.528-53.888s59.2-35.84 92.352-41.344c32.768-5.44 105.28 36.48 107.648 37.824 2.496 1.344 81.216 41.024 71.936 59.072-9.472 18.432-73.344 51.712-73.344 51.712s-69.632 39.808-96.64 39.808c-27.072 0-98.816-39.488-98.816-39.488S106.24 797.504 105.728 782.656zM575.04 776c-0.448-14.848 70.592-53.888 70.592-53.888s59.2-35.904 92.352-41.344c32.704-5.504 105.28 36.416 107.584 37.824 2.624 1.28 81.28 41.024 71.936 59.072-9.408 18.368-73.344 51.648-73.344 51.648s-69.568 39.872-96.64 39.872c-26.944 0-98.816-39.488-98.816-39.488S575.552 790.784 575.04 776zM338.88 908.48c-0.512-14.848 70.464-53.952 70.464-53.952s59.264-35.776 92.48-41.344c32.704-5.504 105.216 36.416 107.584 37.76 2.56 1.344 81.216 41.088 71.936 59.136C671.872 928.576 608 961.792 608 961.792S538.368 1001.6 511.36 1001.6s-98.816-39.488-98.816-39.488S339.392 923.392 338.88 908.48z" ></path></symbol><symbol id="icon-save-all" viewBox="0 0 1024 1024"><path d="M725.333333 298.666667 725.333333 128 298.666667 128 298.666667 298.666667 725.333333 298.666667M597.333333 725.333333C668.16 725.333333 725.333333 668.16 725.333333 597.333333 725.333333 526.506667 668.16 469.333333 597.333333 469.333333 526.506667 469.333333 469.333333 526.506667 469.333333 597.333333 469.333333 668.16 526.506667 725.333333 597.333333 725.333333M810.666667 42.666667 981.333333 213.333333 981.333333 725.333333C981.333333 772.266667 942.933333 810.666667 896 810.666667L298.666667 810.666667C251.306667 810.666667 213.333333 772.266667 213.333333 725.333333L213.333333 128C213.333333 81.066667 251.733333 42.666667 298.666667 42.666667L810.666667 42.666667M42.666667 298.666667 128 298.666667 128 896 725.333333 896 725.333333 981.333333 128 981.333333C81.066667 981.333333 42.666667 942.933333 42.666667 896L42.666667 298.666667Z" ></path></symbol><symbol id="icon-markdown" viewBox="0 0 1024 1024"><path d="M85.333333 682.666667 85.333333 341.333333 170.666667 341.333333 298.666667 469.333333 426.666667 341.333333 512 341.333333 512 682.666667 426.666667 682.666667 426.666667 462.08 298.666667 590.08 170.666667 462.08 170.666667 682.666667 85.333333 682.666667M682.666667 341.333333 810.666667 341.333333 810.666667 512 917.333333 512 746.666667 704 576 512 682.666667 512 682.666667 341.333333Z" ></path></symbol><symbol id="icon-gou" viewBox="0 0 1397 1024"><path d="M1396.363636 121.018182c0 0-223.418182 74.472727-484.072727 372.363636-242.036364 269.963636-297.890909 381.672727-390.981818 530.618182C512 1014.690909 372.363636 744.727273 0 549.236364l195.490909-186.181818c0 0 176.872727 121.018182 297.890909 344.436364 0 0 307.2-474.763636 902.981818-707.490909L1396.363636 121.018182 1396.363636 121.018182zM1396.363636 121.018182" ></path></symbol><symbol id="icon-tree" viewBox="0 0 1024 1024"><path d="M222.090191 544.207539l579.803245 0 0 64.420195 64.424288 0L866.317725 479.779158 544.212656 479.779158l0-64.412009-64.425312 0 0 64.412009L157.678182 479.779158l0 128.848577 64.412009 0L222.090191 544.207539 222.090191 544.207539zM93.253894 866.321818l193.260585 0L286.514479 673.056116 93.253894 673.056116 93.253894 866.321818 93.253894 866.321818zM415.359986 866.321818l193.268772 0L608.628758 673.056116 415.359986 673.056116 415.359986 866.321818 415.359986 866.321818zM737.473241 673.056116l0 193.265702 193.272865 0L930.746106 673.056116 737.473241 673.056116 737.473241 673.056116zM608.628758 157.678182 415.359986 157.678182l0 193.260585 193.268772 0L608.628758 157.678182 608.628758 157.678182zM608.628758 157.678182" ></path></symbol><symbol id="icon-ok" viewBox="0 0 1024 1024"><path d="M510.998695 63.451124c-246.784616 0-447.533756 200.797235-447.533756 447.581852 0 246.734474 200.74914 447.485661 447.533756 447.485661 246.782569 0 447.533756-200.751187 447.533756-447.485661C958.532451 264.24836 757.781264 63.451124 510.998695 63.451124zM510.998695 815.214836c-167.752632 0-304.232003-136.453788-304.232003-304.181861 0-167.777191 136.479371-304.280098 304.232003-304.280098S815.230698 343.255785 815.230698 511.032976C815.230698 678.761048 678.751327 815.214836 510.998695 815.214836z" ></path></symbol><symbol id="icon-github" viewBox="0 0 1024 1024"><path d="M498.894518 100.608396c-211.824383 0-409.482115 189.041494-409.482115 422.192601 0 186.567139 127.312594 344.783581 295.065226 400.602887 21.13025 3.916193 32.039717-9.17701 32.039717-20.307512 0-10.101055 1.176802-43.343157 1.019213-78.596056-117.448946 25.564235-141.394311-49.835012-141.394311-49.835012-19.225877-48.805566-46.503127-61.793368-46.503127-61.793368-38.293141-26.233478 3.13848-25.611308 3.13848-25.611308 42.361807 2.933819 64.779376 43.443441 64.779376 43.443441 37.669948 64.574714 98.842169 45.865607 122.912377 35.094286 3.815909-27.262924 14.764262-45.918819 26.823925-56.431244-93.796246-10.665921-192.323237-46.90017-192.323237-208.673623 0-46.071292 16.498766-83.747379 43.449581-113.332185-4.379751-10.665921-18.805298-53.544497 4.076852-111.732757 0 0 35.46063-11.336186 116.16265 43.296085 33.653471-9.330506 69.783343-14.022365 105.654318-14.174837 35.869952 0.153496 72.046896 4.844332 105.753579 14.174837 80.606853-54.631248 116.00813-43.296085 116.00813-43.296085 22.935362 58.18826 8.559956 101.120049 4.180206 111.732757 27.052123 29.584806 43.443441 67.260893 43.443441 113.332185 0 162.137751-98.798167 197.850114-192.799074 208.262254 15.151072 13.088086 28.65155 38.804794 28.65155 78.17957 0 56.484456-0.459464 101.94381-0.459464 115.854635 0 11.235902 7.573489 24.381293 29.014824 20.2543C825.753867 867.330798 933.822165 709.10924 933.822165 522.700713c0-233.155201-224.12657-422.192601-434.927647-422.192601L498.894518 100.608396z" ></path></symbol><symbol id="icon-close" viewBox="0 0 1024 1024"><path d="M4.43392 97.36192l90.5088-90.5088 923.18976 923.18976-90.5088 90.5088-923.18976-923.18976ZM930.04288 4.43392l90.5088 90.5088-923.18976 923.18976-90.5088-90.5088 923.18976-923.18976Z" ></path></symbol><symbol id="icon-arrow" viewBox="0 0 1024 1024"><path d="M369.4 826.2l4.2-3.6 313-272c10.6-9.2 17.2-23 17.2-38.4 0-15.4-6.8-29.2-17.2-38.4L374.2 202l-5.2-4.6C364 194 358 192 351.6 192c-17.4 0-31.6 14.8-31.6 33.2l0 0 0 573.6 0 0c0 18.4 14.2 33.2 31.6 33.2C358.2 832 364.4 829.8 369.4 826.2z" ></path></symbol><symbol id="icon-arrow-up" viewBox="0 0 1024 1024"><path d="M93.334 700.269c0-14.331 5.512-27.677 15.529-37.657l365.99-365.34c1.306-1.337 2.417-2.38 3.607-3.234l2.723-2.16c10.703-10.653 23.296-15.888 36.627-15.888 13.571 0 26.26 5.351 35.73 15.053l363.953 367.853c9.813 9.951 15.222 23.238 15.222 37.401 0 13.848-5.25 26.931-14.769 36.832-9.549 9.841-22.867 15.507-36.518 15.506-13.484 0-26.259-5.365-35.969-15.134l-328.283-331.846-336.964 336.081c-9.666 9.607-22.296 14.915-35.619 14.915-13.958 0-27.055-5.673-36.876-15.937-9.271-9.768-14.381-22.734-14.381-36.444z" ></path></symbol><symbol id="icon-files" viewBox="0 0 1024 1024"><path d="M917.824 357.056c-22.208-30.272-53.184-65.728-87.168-99.712s-69.44-64.96-99.712-87.168C679.36 132.352 654.336 128 640 128H272C227.904 128 192 163.904 192 208v736c0 44.096 35.904 80 80 80h608c44.096 0 80-35.904 80-80V448c0-14.336-4.352-39.36-42.176-90.944z m-132.48-54.4c30.72 30.72 54.784 58.368 72.576 81.344h-153.984V230.08c22.976 17.792 50.688 41.856 81.344 72.576zM896 944c0 8.704-7.296 16-16 16h-608a16.192 16.192 0 0 1-16-16V208c0-8.64 7.296-16 16-16H640v224a32 32 0 0 0 32 32H896v496z" fill="" ></path><path d="M602.944 42.176C551.36 4.352 526.336 0 512 0H144C99.904 0 64 35.904 64 80v736c0 38.656 27.52 70.976 64 78.4V80c0-8.64 7.36-16 16-16h486.848A669.12 669.12 0 0 0 602.88 42.176z" fill="" ></path></symbol><symbol id="icon-arrowdown" viewBox="0 0 1024 1024"><path d="M930.666 323.731c0 14.331-5.512 27.677-15.529 37.657l-365.99 365.34c-1.306 1.336-2.417 2.379-3.607 3.234l-2.723 2.16c-10.703 10.653-23.296 15.887-36.627 15.887-13.571 0-26.26-5.351-35.729-15.053l-363.953-367.853c-9.813-9.951-15.222-23.238-15.222-37.401 0-13.849 5.25-26.931 14.769-36.832 9.549-9.841 22.867-15.506 36.518-15.506 13.484 0 26.259 5.365 35.969 15.134l328.283 331.846 336.964-336.081c9.666-9.607 22.296-14.915 35.619-14.915 13.958 0 27.055 5.673 36.876 15.937 9.271 9.768 14.381 22.734 14.381 36.444z" ></path></symbol><symbol id="icon-collect" viewBox="0 0 1024 1024"><path d="M512 134.608l121.136 248.451 270.871 39.867L708.005 616.305l46.265 273.088L512 760.464 269.73 889.393l46.266-273.088L119.993 422.926l270.873-39.867L512 134.608M512 77.923c-21.302 0-40.771 12.251-50.204 31.583l-108.12 221.763-241.724 35.547c-21.109 3.118-38.637 18.047-45.227 38.583-6.563 20.535-1.094 43.066 14.165 58.106l174.921 172.598L214.549 879.82c-3.609 21.274 5.032 42.767 22.286 55.43 9.762 7.163 21.301 10.827 32.896 10.827 8.914 0 17.882-2.16 26.087-6.509L512 824.505l216.239 115.063c8.176 4.349 17.117 6.509 26.03 6.509 11.622 0 23.188-3.664 32.923-10.827 17.256-12.69 25.896-34.181 22.287-55.43l-41.29-243.718L943.11 463.504c15.256-15.04 20.727-37.571 14.164-58.106-6.589-20.536-24.118-35.465-45.228-38.583l-241.722-35.547L562.229 109.533C552.797 90.174 533.328 77.923 5 | javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | true |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/spellchecker/languageMap.js | src/renderer/spellchecker/languageMap.js | import langMap from 'iso-639-1'
/**
* Return the native language name by language code.
*
* @param {string} langCode The ISO two or four-letter language code (e.g. en, en-US) or BCP-47 code.
*/
export const getLanguageName = languageCode => {
if (!languageCode || languageCode.length < 2) {
return null
}
let language = ''
// First try to get an exact language via 4-letter ISO code.
if (languageCode.length === 5) {
language = getHunspellLanguageName(languageCode)
if (language) {
return language
}
}
language = langMap.getNativeName(languageCode.substr(0, 2))
if (language) {
// Add language code to distinguish between native name (en-US, en-GB, ...).
return `${language} (${languageCode})`
}
return `Unknown (${languageCode})`
}
/**
* Return the native language name by language code for supported Hunspell languages.
*
* @param {string} langCode The ISO 4-letter language code.
*/
const getHunspellLanguageName = langCode => {
const item = HUNSPELL_DICTIONARY_LANGUAGE_MAP.find(item => item.value === langCode)
if (!item) {
return null
}
return item.label
}
// All available Hunspell dictionary languages.
const HUNSPELL_DICTIONARY_LANGUAGE_MAP = Object.freeze([{
label: 'Afrikaans', // Afrikaans
value: 'af-ZA'
}, {
label: 'български език', // Bulgarian
value: 'bg-BG'
}, {
label: 'Català', // Catalan
value: 'ca-ES'
}, {
label: 'Česky', // Czech
value: 'cs-CZ'
}, {
label: 'Dansk', // Danish
value: 'da-DK'
}, {
label: 'Deutsch', // German
value: 'de-DE'
}, {
label: 'Ελληνικά', // Greek
value: 'el-GR'
}, {
label: 'English (en-AU)', // English
value: 'en-AU'
}, {
label: 'English (en-CA)', // English
value: 'en-CA'
}, {
label: 'English (en-GB)', // English
value: 'en-GB'
}, {
label: 'English (en-US)', // English
value: 'en-US'
}, {
label: 'Español', // Spanish
value: 'es-ES'
}, {
label: 'Eesti', // Estonian
value: 'et-EE'
}, {
label: 'Føroyskt', // Faroese
value: 'fo-FO'
}, {
label: 'Français', // French
value: 'fr-FR'
}, {
label: 'עברית', // Hebrew (modern)
value: 'he-IL'
}, {
label: 'हिन्दी', // Hindi
value: 'hi-IN'
}, {
label: 'Hhrvatski', // Croatian
value: 'hr-HR'
}, {
label: 'Magyar', // Hungarian
value: 'hu-HU'
}, {
label: 'Bahasa Indonesia', // Indonesian
value: 'id-ID'
}, {
label: 'Italiano', // Italian
value: 'it-IT'
}, {
label: '한국어', // Korean
value: 'ko'
}, {
label: 'Lietuvių', // Lithuanian
value: 'lt-LT'
}, {
label: 'Latviešu', // Latvian
value: 'lv-LV'
}, {
label: 'Norsk', // Norwegian
value: 'nb-NO'
}, {
label: 'Nederlands', // Dutch
value: 'nl-NL'
}, {
label: 'Polski', // Polish
value: 'pl-PL'
}, {
label: 'Português (pt-BR)', // Portuguese
value: 'pt-BR'
}, {
label: 'Português (pt-PT)', // Portuguese
value: 'pt-PT'
}, {
label: 'Română', // Romanian
value: 'ro-RO'
}, {
label: 'Pусский', // Russian
value: 'ru-RU'
}, {
label: 'Cрпски језик (Latin)', // Serbian (Latin)
value: 'sh' // aka sr-Latn
}, {
label: 'Slovenčina (sk-SK)', // Slovak
value: 'sk-SK'
}, {
label: 'Slovenščina (sl-SI)', // Slovene
value: 'sl-SI'
}, {
label: 'Shqip', // Albanian
value: 'sq'
}, {
label: 'Cрпски језик', // Serbian
value: 'sr'
}, {
label: 'Svenska', // Swedish
value: 'sv-SE'
}, {
label: 'தமிழ்', // Tamil
value: 'ta-IN'
}, {
label: 'тоҷикӣ', // Tajik
value: 'tg-TG'
}, {
label: 'Türkçe', // Turkish
value: 'tr-TR'
}, {
label: 'українська', // Ukrainian
value: 'uk-UA'
}, {
label: 'Tiếng Việt', // Vietnamese
value: 'vi-VN'
}])
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/spellchecker/index.js | src/renderer/spellchecker/index.js | import { ipcRenderer } from 'electron'
import { isOsx } from '@/util'
/**
* High level spell checker API based on Chromium built-in spell checker.
*/
export class SpellChecker {
/**
* ctor
*
* @param {boolean} enabled Whether spell checking is enabled in settings.
*/
constructor (enabled = true, lang) {
this.enabled = enabled
this.currentSpellcheckerLanguage = lang
// Helper to forbid the usage of the spell checker (e.g. failed to create native spell checker),
// even if spell checker is enabled in settings.
this.isProviderAvailable = true
}
/**
* Whether the spell checker is available and enabled.
*/
get isEnabled () {
return this.isProviderAvailable && this.enabled
}
/**
* Enable the spell checker and sets `lang` or tries to find a fallback.
*
* @param {string} lang The language to set.
* @returns {Promise<boolean>}
*/
async activateSpellchecker (lang) {
try {
this.enabled = true
this.isProviderAvailable = true
if (isOsx) {
// No language string needed on macOS.
return await ipcRenderer.invoke('mt::spellchecker-set-enabled', true)
}
return await this.switchLanguage(lang || this.currentSpellcheckerLanguage)
} catch (error) {
this.deactivateSpellchecker()
throw error
}
}
/**
* Disables the native spell checker.
*/
deactivateSpellchecker () {
this.enabled = false
this.isProviderAvailable = false
ipcRenderer.invoke('mt::spellchecker-set-enabled', false)
}
/**
* Return the current language.
*/
get lang () {
if (this.isEnabled) {
return this.currentSpellcheckerLanguage
}
return ''
}
set lang (lang) {
this.currentSpellcheckerLanguage = lang
}
/**
* Explicitly switch the language to a specific language.
*
* NOTE: This function can throw an exception.
*
* @param {string} lang The language code
* @returns {Promise<boolean>} Return the language on success or null.
*/
async switchLanguage (lang) {
if (isOsx) {
// NB: On macOS the OS spell checker is used and will detect the language automatically.
return true
} else if (!lang) {
throw new Error('Expected non-empty language for spell checker.')
} else if (this.isEnabled) {
await ipcRenderer.invoke('mt::spellchecker-switch-language', lang)
this.lang = lang
return true
}
return false
}
/**
* Returns a list of available dictionaries.
* @returns {Promise<string[]>} Available dictionary languages.
*/
static async getAvailableDictionaries () {
if (isOsx) {
// NB: On macOS the OS spell checker is used and will detect the language automatically.
return []
}
return ipcRenderer.invoke('mt::spellchecker-get-available-dictionaries')
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/codeMirror/loadmode.js | src/renderer/codeMirror/loadmode.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
const loadMore = CodeMirror => {
if (!CodeMirror.modeURL) {
CodeMirror.modeURL = '../../mode/%N/%N.js'
}
const loading = {}
function splitCallback (cont, n) {
let countDown = n
return function () { if (--countDown === 0) cont() }
}
function ensureDeps (mode, cont) {
const deps = CodeMirror.modes[mode].dependencies
if (!deps) return cont()
const missing = []
for (let i = 0; i < deps.length; ++i) {
if (!CodeMirror.modes.hasOwnProperty(deps[i])) {
missing.push(deps[i])
}
}
if (!missing.length) return cont()
const split = splitCallback(cont, missing.length)
for (let i = 0; i < missing.length; ++i) {
CodeMirror.requireMode(missing[i], split)
}
}
CodeMirror.requireMode = function (mode, cont) {
if (typeof mode !== 'string') {
mode = mode.name
}
if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont)
if (loading.hasOwnProperty(mode)) return loading[mode].push(cont)
const file = CodeMirror.modeURL.replace(/%N/g, mode)
const script = document.createElement('script')
script.src = file
const others = document.getElementsByTagName('script')[0]
const list = loading[mode] = [cont]
CodeMirror.on(script, 'load', function () {
ensureDeps(mode, function () {
for (let i = 0; i < list.length; ++i) {
list[i]()
}
})
})
others.parentNode.insertBefore(script, others)
}
CodeMirror.autoLoadMode = function (instance, mode) {
if (!CodeMirror.modes.hasOwnProperty(mode)) {
CodeMirror.requireMode(mode, function () {
instance.setOption('mode', instance.getOption('mode'))
})
}
}
}
export default loadMore
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/codeMirror/index.js | src/renderer/codeMirror/index.js | import { filter } from 'fuzzaldrin'
import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/edit/closetag'
import 'codemirror/addon/selection/active-line'
import 'codemirror/mode/meta'
import codeMirror from 'codemirror/lib/codemirror'
import loadmode from './loadmode'
import overlayMode from './overlayMode'
import multiplexMode from './mltiplexMode'
import languages from './modes'
import 'codemirror/lib/codemirror.css'
import './index.css'
import 'codemirror/theme/railscasts.css'
loadmode(codeMirror)
overlayMode(codeMirror)
multiplexMode(codeMirror)
window.CodeMirror = codeMirror
const modes = codeMirror.modeInfo
codeMirror.modeURL = './codemirror/mode/%N/%N.js'
const getModeFromName = name => {
let result = null
const lang = languages.filter(lang => lang.name === name)[0]
if (lang) {
const { name, mode, mime } = lang
const matched = modes.filter(m => {
if (m.mime) {
if (Array.isArray(m.mime) && m.mime.indexOf(mime) > -1 && m.mode === mode) {
return true
} else if (typeof m.mime === 'string' && m.mime === mime && m.mode === mode) {
return true
}
}
if (Array.isArray(m.mimes) && m.mimes.indexOf(mime) > -1 && m.mode === mode) {
return true
}
return false
})
if (matched.length && typeof matched[0] === 'object') {
result = {
name,
mode: matched[0]
}
}
}
return result
}
export const search = text => {
const matchedLangs = filter(languages, text, { key: 'name' })
return matchedLangs
.map(({ name }) => getModeFromName(name))
.filter(lang => !!lang)
}
/**
* set cursor at the end of last line.
*/
export const setCursorAtLastLine = cm => {
const lastLine = cm.lastLine()
const lineHandle = cm.getLineHandle(lastLine)
cm.focus()
cm.setCursor(lastLine, lineHandle.text.length)
}
// if cursor at firstLine return true
export const isCursorAtFirstLine = cm => {
const cursor = cm.getCursor()
const { line, ch, outside } = cursor
return line === 0 && ch === 0 && outside
}
export const isCursorAtLastLine = cm => {
const lastLine = cm.lastLine()
const cursor = cm.getCursor()
const { line, outside, sticky } = cursor
return line === lastLine && (outside || !sticky)
}
export const isCursorAtBegin = cm => {
const cursor = cm.getCursor()
const { line, ch, hitSide } = cursor
return line === 0 && ch === 0 && !!hitSide
}
export const onlyHaveOneLine = cm => {
return cm.lineCount() === 1
}
export const isCursorAtEnd = cm => {
const lastLine = cm.lastLine()
const lastLineHandle = cm.getLineHandle(lastLine)
const cursor = cm.getCursor()
const { line, ch, hitSide } = cursor
return line === lastLine && ch === lastLineHandle.text.length && !!hitSide
}
export const getBeginPosition = () => {
return {
anchor: { line: 0, ch: 0 },
head: { line: 0, ch: 0 }
}
}
export const getEndPosition = cm => {
const lastLine = cm.lastLine()
const lastLineHandle = cm.getLineHandle(lastLine)
const line = lastLine
const ch = lastLineHandle.text.length
return { anchor: { line, ch }, head: { line, ch } }
}
export const setCursorAtFirstLine = cm => {
cm.focus()
cm.setCursor(0, 0)
}
export const setMode = (doc, text) => {
const m = getModeFromName(text)
if (!m) {
const errMsg = !text
? 'You\'d better provided a language mode when you create code block'
: `${text} is not a valid language mode!`
return Promise.reject(errMsg) // eslint-disable-line prefer-promise-reject-errors
}
const { mode, mime } = m.mode
return new Promise(resolve => {
codeMirror.requireMode(mode, () => {
doc.setOption('mode', mime || mode)
codeMirror.autoLoadMode(doc, mode)
resolve(m)
})
})
}
export const setTextDirection = (cm, textDirection) => {
cm.setOption('direction', textDirection)
}
export default codeMirror
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/codeMirror/overlayMode.js | src/renderer/codeMirror/overlayMode.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// Utility function that allows modes to be combined. The mode given
// as the base argument takes care of most of the normal mode
// functionality, but a second (typically simple) mode is used, which
// can override the style of text. Both modes get to parse all of the
// text, but when both assign a non-null style to a piece of code, the
// overlay wins, unless the combine argument was true and not overridden,
// or state.overlay.combineTokens was true, in which case the styles are
// combined.
const overlayMode = CodeMirror => {
CodeMirror.overlayMode = function (base, overlay, combine) {
return {
startState () {
return {
base: CodeMirror.startState(base),
overlay: CodeMirror.startState(overlay),
basePos: 0,
baseCur: null,
overlayPos: 0,
overlayCur: null,
streamSeen: null
}
},
copyState (state) {
return {
base: CodeMirror.copyState(base, state.base),
overlay: CodeMirror.copyState(overlay, state.overlay),
basePos: state.basePos,
baseCur: null,
overlayPos: state.overlayPos,
overlayCur: null
}
},
token (stream, state) {
if (stream !== state.streamSeen ||
Math.min(state.basePos, state.overlayPos) < stream.start) {
state.streamSeen = stream
state.basePos = state.overlayPos = stream.start
}
if (stream.start === state.basePos) {
state.baseCur = base.token(stream, state.base)
state.basePos = stream.pos
}
if (stream.start === state.overlayPos) {
stream.pos = stream.start
state.overlayCur = overlay.token(stream, state.overlay)
state.overlayPos = stream.pos
}
stream.pos = Math.min(state.basePos, state.overlayPos)
// state.overlay.combineTokens always takes precedence over combine,
// unless set to null
if (state.overlayCur === null) {
return state.baseCur
} else if (
(state.baseCur !== null &&
state.overlay.combineTokens) ||
(combine && state.overlay.combineTokens === null)
) {
return state.baseCur + ' ' + state.overlayCur
} else return state.overlayCur
},
indent: base.indent && function (state, textAfter) {
return base.indent(state.base, textAfter)
},
electricChars: base.electricChars,
innerMode (state) {
return {
state: state.base,
mode: base
}
},
blankLine (state) {
let baseToken
let overlayToken
if (base.blankLine) baseToken = base.blankLine(state.base)
if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay)
return overlayToken == null
? baseToken
: (combine && baseToken != null ? baseToken + ' ' + overlayToken : overlayToken)
}
}
}
}
export default overlayMode
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/codeMirror/modes.js | src/renderer/codeMirror/modes.js | const languages = [{
name: 'objectivec',
mode: 'clike',
mime: 'text/x-objectivec'
}, {
name: 'swift',
mode: 'swift',
mime: 'text/x-swift'
}, {
name: 'c_cpp',
mode: 'clike',
mime: 'text/x-csrc'
}, {
name: 'c',
mode: 'clike',
mime: 'text/x-csrc'
}, {
name: 'c++',
mode: 'clike',
mime: 'text/x-c++src'
}, {
name: 'cmake',
mode: 'cmake',
mime: 'text/x-cmake'
}, {
name: 'lisp',
mode: 'commonlisp',
mime: 'text/x-common-lisp'
}, {
name: 'pascal',
mode: 'pascal',
mime: 'text/x-pascal'
}, {
name: 'eiffel',
mode: 'eiffel',
mime: 'text/x-eiffel'
}, {
name: 'yaml',
mode: 'yaml',
mime: 'text/x-yaml'
}, {
name: 'xml',
mode: 'xml',
mime: 'application/xml'
}, {
name: 'django',
mode: 'django',
mime: 'text/x-django'
}, {
name: 'clojure',
mode: 'clojure',
mime: 'text/x-clojure'
}, {
name: 'crystal',
mode: 'crystal',
mime: 'text/x-crystal'
}, {
name: 'ruby',
mode: 'ruby',
mime: 'text/x-ruby'
}, {
name: 'python',
mode: 'python',
mime: 'text/x-python'
}, {
name: 'sh',
mode: 'shell',
mime: 'text/x-sh'
}, { /* alias */
name: 'shell',
mode: 'shell',
mime: 'text/x-sh'
}, {
name: 'less',
mode: 'css',
mime: 'text/css'
}, {
name: 'php',
mode: 'php',
mime: 'application/x-httpd-php'
}, {
name: 'json',
mode: 'javascript',
mime: 'application/json'
}, {
name: 'smarty',
mode: 'smarty',
mime: 'text/x-smarty'
}, {
name: 'cobol',
mode: 'cobol',
mime: 'text/x-cobol'
}, {
name: 'go',
mode: 'go',
mime: 'text/x-go'
}, { /* alias */
name: 'golang',
mode: 'go',
mime: 'text/x-go'
}, {
name: 'makefile',
mode: 'shell', /* makefile syntax is not supported by CodeMirror */
mime: 'text/x-sh'
}, {
name: 'ocaml',
mode: 'mllike',
mime: 'text/x-ocaml'
}, {
name: 'textile',
mode: 'textile',
mime: 'text/x-textile'
}, {
name: 'd',
mode: 'd',
mime: 'text/x-d'
}, {
name: 'jade',
mode: 'pug',
mime: 'text/x-pug'
}, {
name: 'lua',
mode: 'lua',
mime: 'text/x-lua'
}, {
name: 'coffee',
mode: 'coffeescript',
mime: 'text/x-coffeescript'
}, {
name: 'html',
mode: 'htmlmixed',
mime: 'text/html'
}, {
name: 'pgsql',
mode: 'sql',
mime: 'text/x-sql'
}, {
name: 'haskell',
mode: 'haskell',
mime: 'text/x-haskell'
}, {
name: 'jsp',
mode: 'htmlembedded',
mime: 'application/x-jsp'
}, {
name: 'tcl',
mode: 'tcl',
mime: 'text/x-tcl'
}, {
name: 'ini',
mode: 'properties',
mime: 'text/x-properties'
}, {
name: 'jsoniq',
mode: 'javascript',
mime: 'application/json'
}, {
name: 'vhdl',
mode: 'vhdl',
mime: 'text/x-vhdl'
}, {
name: 'verilog',
mode: 'verilog',
mime: 'text/x-systemverilog'
}, {
name: 'csharp',
mode: 'clike',
mime: 'text/x-csharp'
}, {
name: 'cs',
mode: 'clike',
mime: 'text/x-csharp'
}, {
name: 'rust',
mode: 'rust',
mime: 'text/x-rustsrc'
}, {
name: 'livescript',
mode: 'livescript',
mime: 'text/x-livescript'
}, {
name: 'jsx',
mode: 'jsx',
mime: 'text/jsx'
}, {
name: 'protobuf',
mode: 'protobuf',
mime: 'text/x-protobuf'
}, {
name: 'markdown',
mode: 'gfm',
mime: 'text/x-gfm'
}, {
name: 'rst',
mode: 'rst',
mime: 'text/x-rst'
}, {
name: 'LaTeX',
mode: 'stex',
mime: 'text/x-latex'
}, {
name: 'java',
mode: 'clike',
mime: 'text/x-java'
}, {
name: 'kotlin',
mode: 'clike',
mime: 'text/x-kotlin'
}, {
name: 'javascript',
mode: 'javascript',
mime: 'text/javascript'
}, {
name: 'erlang',
mode: 'erlang',
mime: 'text/x-erlang'
}, {
name: 'scheme',
mode: 'scheme',
mime: 'text/x-scheme'
}, {
name: 'sass',
mode: 'sass',
mime: 'text/x-sass'
}, {
name: 'groovy',
mode: 'groovy',
mime: 'text/x-groovy'
}, {
name: 'julia',
mode: 'julia',
mime: 'text/x-julia'
}, {
name: 'haml',
mode: 'haml',
mime: 'text/x-haml'
}, {
name: 'powershell',
mode: 'powershell',
mime: 'application/x-powershell'
}, {
name: 'typescript',
mode: 'javascript',
mime: 'application/typescript'
}, {
name: 'dart',
mode: 'dart',
mime: 'application/dart'
}, {
name: 'xquery',
mode: 'xquery',
mime: 'application/xquery'
}, {
name: 'elm',
mode: 'elm',
mime: 'text/x-elm'
}, {
name: 'plsql',
mode: 'sql',
mime: 'text/x-plsql'
}, {
name: 'forth',
mode: 'forth',
mime: 'text/x-forth'
}, {
name: 'scala',
mode: 'clike',
mime: 'text/x-scala'
}, {
name: 'perl',
mode: 'perl',
mime: 'text/x-perl'
}, {
name: 'haxe',
mode: 'haxe',
mime: 'text/x-haxe'
}, {
name: 'rhtml',
mode: 'htmlembedded',
mime: 'application/x-erb'
}, {
name: 'scss',
mode: 'css',
mime: 'text/x-scss'
}, {
name: 'sql',
mode: 'sql',
mime: 'text/x-sql'
}, {
name: 'css',
mode: 'css',
mime: 'text/css'
}, {
name: 'tex',
mode: 'stex',
mime: 'text/x-stex'
}, {
name: 'r',
mode: 'r',
mime: 'text/x-rsrc'
}, {
name: 'diff',
mode: 'diff',
mime: 'text/x-diff'
}, {
name: 'twig',
mode: 'twig',
mime: 'text/x-twig'
}, {
name: 'matlab',
mode: 'octave',
mime: 'text/x-octave'
}, {
name: 'soy_template',
mode: 'soy',
mime: 'text/x-soy'
}, {
name: 'dockerfile',
mode: 'dockerfile',
mime: 'text/x-dockerfile'
}, {
name: 'toml',
mode: 'toml',
mime: 'text/x-toml'
}, {
name: 'pgp',
mode: 'asciiarmor',
mime: 'application/pgp'
}, {
name: 'Nginx',
mode: 'nginx',
mime: 'text/x-nginx-conf'
}]
export default languages
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/codeMirror/mltiplexMode.js | src/renderer/codeMirror/mltiplexMode.js | // CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
const multiplexMode = CodeMirror => {
CodeMirror.multiplexingMode = function (outer /*, others */) {
// Others should be {open, close, mode [, delimStyle] [, innerStyle]} objects
const others = Array.prototype.slice.call(arguments, 1)
function indexOf (string, pattern, from, returnEnd) {
if (typeof pattern === 'string') {
const found = string.indexOf(pattern, from)
return returnEnd && found > -1 ? found + pattern.length : found
}
const m = pattern.exec(from ? string.slice(from) : string)
return m ? m.index + from + (returnEnd ? m[0].length : 0) : -1
}
return {
startState () {
return {
outer: CodeMirror.startState(outer),
innerActive: null,
inner: null
}
},
copyState (state) {
return {
outer: CodeMirror.copyState(outer, state.outer),
innerActive: state.innerActive,
inner: state.innerActive && CodeMirror.copyState(state.innerActive.mode, state.inner)
}
},
token (stream, state) {
if (!state.innerActive) {
let cutOff = Infinity
const oldContent = stream.string
for (let i = 0; i < others.length; ++i) {
const other = others[i]
const found = indexOf(oldContent, other.open, stream.pos)
if (found === stream.pos) {
if (!other.parseDelimiters) stream.match(other.open)
state.innerActive = other
// Get the outer indent, making sure to handle CodeMirror.Pass
let outerIndent = 0
if (outer.indent) {
const possibleOuterIndent = outer.indent(state.outer, '')
if (possibleOuterIndent !== CodeMirror.Pass) outerIndent = possibleOuterIndent
}
state.inner = CodeMirror.startState(other.mode, outerIndent)
return other.delimStyle && (other.delimStyle + ' ' + other.delimStyle + '-open')
} else if (found !== -1 && found < cutOff) {
cutOff = found
}
}
if (cutOff !== Infinity) stream.string = oldContent.slice(0, cutOff)
const outerToken = outer.token(stream, state.outer)
if (cutOff !== Infinity) stream.string = oldContent
return outerToken
} else {
const curInner = state.innerActive
const oldContent = stream.string
if (!curInner.close && stream.sol()) {
state.innerActive = state.inner = null
return this.token(stream, state)
}
const found = curInner.close ? indexOf(oldContent, curInner.close, stream.pos, curInner.parseDelimiters) : -1
if (found === stream.pos && !curInner.parseDelimiters) {
stream.match(curInner.close)
state.innerActive = state.inner = null
return curInner.delimStyle && (curInner.delimStyle + ' ' + curInner.delimStyle + '-close')
}
if (found > -1) stream.string = oldContent.slice(0, found)
let innerToken = curInner.mode.token(stream, state.inner)
if (found > -1) stream.string = oldContent
if (found === stream.pos && curInner.parseDelimiters) {
state.innerActive = state.inner = null
}
if (curInner.innerStyle) {
if (innerToken) innerToken = innerToken + ' ' + curInner.innerStyle
else innerToken = curInner.innerStyle
}
return innerToken
}
},
indent (state, textAfter) {
const mode = state.innerActive ? state.innerActive.mode : outer
if (!mode.indent) return CodeMirror.Pass
return mode.indent(state.innerActive ? state.inner : state.outer, textAfter)
},
blankLine (state) {
const mode = state.innerActive ? state.innerActive.mode : outer
if (mode.blankLine) {
mode.blankLine(state.innerActive ? state.inner : state.outer)
}
if (!state.innerActive) {
for (let i = 0; i < others.length; ++i) {
const other = others[i]
if (other.open === '\n') {
state.innerActive = other
state.inner = CodeMirror.startState(other.mode, mode.indent ? mode.indent(state.outer, '') : 0)
}
}
} else if (state.innerActive.close === '\n') {
state.innerActive = state.inner = null
}
},
electricChars: outer.electricChars,
innerMode (state) {
return state.inner ? { state: state.inner, mode: state.innerActive.mode } : { state: state.outer, mode: outer }
}
}
}
}
export default multiplexMode
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/bus/index.js | src/renderer/bus/index.js | import Vue from 'vue'
export default new Vue()
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/router/index.js | src/renderer/router/index.js | import App from '@/pages/app'
import Preference from '@/pages/preference'
import General from '@/prefComponents/general'
import Editor from '@/prefComponents/editor'
import Markdown from '@/prefComponents/markdown'
import SpellChecker from '@/prefComponents/spellchecker'
import Theme from '@/prefComponents/theme'
import Image from '@/prefComponents/image'
import Keybindings from '@/prefComponents/keybindings'
const parseSettingsPage = type => {
let pageUrl = '/preference'
if (/\/spelling$/.test(type)) {
pageUrl += '/spelling'
}
return pageUrl
}
const routes = type => ([{
path: '/', redirect: type === 'editor' ? '/editor' : parseSettingsPage(type)
}, {
path: '/editor', component: App
}, {
path: '/preference',
component: Preference,
children: [{
path: '', component: General
}, {
path: 'general', component: General, name: 'general'
}, {
path: 'editor', component: Editor, name: 'editor'
}, {
path: 'markdown', component: Markdown, name: 'markdown'
}, {
path: 'spelling', component: SpellChecker, name: 'spelling'
}, {
path: 'theme', component: Theme, name: 'theme'
}, {
path: 'image', component: Image, name: 'image'
}, {
path: 'keybindings', component: Keybindings, name: 'keybindings'
}]
}])
export default routes
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/mixins/index.js | src/renderer/mixins/index.js | import { ipcRenderer } from 'electron'
import { isSamePathSync } from 'common/filesystem/paths'
import bus from '../bus'
export const tabsMixins = {
methods: {
selectFile (file) {
if (file.id !== this.currentFile.id) {
this.$store.dispatch('UPDATE_CURRENT_FILE', file)
}
},
removeFileInTab (file) {
const { isSaved } = file
if (isSaved) {
this.$store.dispatch('FORCE_CLOSE_TAB', file)
} else {
this.$store.dispatch('CLOSE_UNSAVED_TAB', file)
}
}
}
}
export const loadingPageMixins = {
methods: {
hideLoadingPage () {
const loadingPage = document.querySelector('#loading-page')
if (loadingPage) {
loadingPage.remove()
}
}
}
}
export const fileMixins = {
methods: {
handleSearchResultClick (searchMatch) {
const { range } = searchMatch
const { filePath } = this.searchResult
const openedTab = this.tabs.find(file => isSamePathSync(file.pathname, filePath))
const cursor = {
isCollapsed: range[0][0] !== range[1][0],
anchor: {
line: range[0][0],
ch: range[0][1]
},
focus: {
line: range[1][0],
ch: range[1][1]
}
}
if (openedTab) {
openedTab.cursor = cursor
if (this.currentFile !== openedTab) {
this.$store.dispatch('UPDATE_CURRENT_FILE', openedTab)
} else {
const { id, markdown, cursor, history } = this.currentFile
bus.$emit('file-changed', { id, markdown, cursor, renderCursor: true, history })
}
} else {
ipcRenderer.send('mt::open-file', filePath, {
cursor
})
}
},
handleFileClick () {
const { isMarkdown, pathname } = this.file
if (!isMarkdown) return
const openedTab = this.tabs.find(file => isSamePathSync(file.pathname, pathname))
if (openedTab) {
if (this.currentFile === openedTab) {
return
}
this.$store.dispatch('UPDATE_CURRENT_FILE', openedTab)
} else {
ipcRenderer.send('mt::open-file', pathname, {})
}
}
}
}
export const createFileOrDirectoryMixins = {
methods: {
handleInputFocus () {
this.$nextTick(() => {
if (this.$refs.input) {
this.$refs.input.focus()
this.createName = ''
if (this.folder) {
this.folder.isCollapsed = false
}
}
})
},
handleInputEnter () {
const { createName } = this
this.$store.dispatch('CREATE_FILE_DIRECTORY', createName)
}
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/webpack.config.js | src/muya/webpack.config.js | 'use strict'
process.env.BABEL_ENV = 'renderer'
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const postcssPresetEnv = require('postcss-preset-env')
/** @type {import('webpack').Configuration} */
module.exports = {
mode: 'production',
devtool: 'hidden-nosources-source-map',
optimization: {
emitOnErrors: false,
minimize: true
},
entry: {
renderer: path.join(__dirname, './lib/index.js')
},
module: {
rules: [
{
test: require.resolve(path.join(__dirname, './lib/assets/libs/snap.svg-min.js')),
use: 'imports-loader?this=>window,fix=>module.exports=0'
},
{
test: /(theme\-chalk(?:\/|\\)index|exportStyle|katex|github\-markdown|prism[\-a-z]*|\.theme|headerFooterStyle)\.css$/,
use: [
'to-string-loader',
'css-loader'
]
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.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: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
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]'
}
}
]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'index.min.css'
})
],
output: {
filename: 'index.min.js',
libraryTarget: 'umd',
library: 'Muya',
path: path.join(__dirname, './dist')
},
resolve: {
alias: {
snapsvg: path.join(__dirname, './lib/assets/libs/snap.svg-min.js')
},
extensions: ['.js', '.vue', '.json', '.css', '.node'],
fallback: {
fs: false,
path: require.resolve('path-browserify')
}
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/index.js | src/muya/lib/index.js | import ContentState from './contentState'
import EventCenter from './eventHandler/event'
import MouseEvent from './eventHandler/mouseEvent'
import Clipboard from './eventHandler/clipboard'
import Keyboard from './eventHandler/keyboard'
import DragDrop from './eventHandler/dragDrop'
import Resize from './eventHandler/resize'
import ClickEvent from './eventHandler/clickEvent'
import { CLASS_OR_ID, MUYA_DEFAULT_OPTION } from './config'
import { wordCount } from './utils'
import ExportMarkdown from './utils/exportMarkdown'
import ExportHtml from './utils/exportHtml'
import ToolTip from './ui/tooltip'
import './assets/styles/index.css'
class Muya {
static plugins = []
static use (plugin, options = {}) {
this.plugins.push({
plugin,
options
})
}
constructor (container, options) {
this.options = Object.assign({}, MUYA_DEFAULT_OPTION, options)
const { markdown } = this.options
this.markdown = markdown
this.container = getContainer(container, this.options)
this.eventCenter = new EventCenter()
this.tooltip = new ToolTip(this)
// UI plugins
if (Muya.plugins.length) {
for (const { plugin: Plugin, options: opts } of Muya.plugins) {
this[Plugin.pluginName] = new Plugin(this, opts)
}
}
this.contentState = new ContentState(this, this.options)
this.clipboard = new Clipboard(this)
this.clickEvent = new ClickEvent(this)
this.keyboard = new Keyboard(this)
this.dragdrop = new DragDrop(this)
this.resize = new Resize(this)
this.mouseEvent = new MouseEvent(this)
this.init()
}
init () {
const { container, contentState, eventCenter } = this
contentState.stateRender.setContainer(container.children[0])
eventCenter.subscribe('stateChange', this.dispatchChange)
const { markdown } = this
const { focusMode } = this.options
this.setMarkdown(markdown)
this.setFocusMode(focusMode)
this.mutationObserver()
eventCenter.attachDOMEvent(container, 'focus', () => {
eventCenter.dispatch('focus')
})
eventCenter.attachDOMEvent(container, 'blur', () => {
eventCenter.dispatch('blur')
})
}
mutationObserver () {
// Select the node that will be observed for mutations
const { container, eventCenter } = this
// Options for the observer (which mutations to observe)
const config = { childList: true, subtree: true }
// Callback function to execute when mutations are observed
const callback = (mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
const { removedNodes, target } = mutation
// If the code executes any of the following `if` statements, the editor has gone wrong.
// need to report bugs.
if (removedNodes && removedNodes.length) {
const hasTable = Array.from(removedNodes).some(node => node.nodeType === 1 && node.closest('table.ag-paragraph'))
if (hasTable) {
eventCenter.dispatch('crashed')
console.warn('There was a problem with the table deletion.')
}
}
if (target.getAttribute('id') === 'ag-editor-id' && target.childElementCount === 0) {
// TODO: the editor can not be input any more. report bugs and recovery...
eventCenter.dispatch('crashed')
console.warn('editor crashed, and can not be input any more.')
}
}
}
}
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback)
// Start observing the target node for configured mutations
observer.observe(container, config)
}
dispatchChange = () => {
const { eventCenter } = this
const markdown = this.markdown = this.getMarkdown()
const wordCount = this.getWordCount(markdown)
const cursor = this.getCursor()
const history = this.getHistory()
const toc = this.getTOC()
eventCenter.dispatch('change', { markdown, wordCount, cursor, history, toc })
}
dispatchSelectionChange = () => {
const selectionChanges = this.contentState.selectionChange()
this.eventCenter.dispatch('selectionChange', selectionChanges)
}
dispatchSelectionFormats = () => {
const { formats } = this.contentState.selectionFormats()
this.eventCenter.dispatch('selectionFormats', formats)
}
getMarkdown () {
const blocks = this.contentState.getBlocks()
const { isGitlabCompatibilityEnabled, listIndentation } = this.contentState
return new ExportMarkdown(blocks, listIndentation, isGitlabCompatibilityEnabled).generate()
}
getHistory () {
return this.contentState.getHistory()
}
getTOC () {
return this.contentState.getTOC()
}
setHistory (history) {
return this.contentState.setHistory(history)
}
clearHistory () {
return this.contentState.history.clearHistory()
}
exportStyledHTML (options) {
const { markdown } = this
return new ExportHtml(markdown, this).generate(options)
}
exportHtml () {
const { markdown } = this
return new ExportHtml(markdown, this).renderHtml()
}
getWordCount (markdown) {
return wordCount(markdown)
}
getCursor () {
return this.contentState.getCodeMirrorCursor()
}
setMarkdown (markdown, cursor, isRenderCursor = true) {
let newMarkdown = markdown
let isValid = false
if (cursor && cursor.anchor && cursor.focus) {
const cursorInfo = this.contentState.addCursorToMarkdown(markdown, cursor)
newMarkdown = cursorInfo.markdown
isValid = cursorInfo.isValid
}
this.contentState.importMarkdown(newMarkdown)
this.contentState.importCursor(cursor && isValid)
this.contentState.render(isRenderCursor)
setTimeout(() => {
this.dispatchChange()
}, 0)
}
setCursor (cursor) {
const markdown = this.getMarkdown()
const isRenderCursor = true
return this.setMarkdown(markdown, cursor, isRenderCursor)
}
createTable (tableChecker) {
return this.contentState.createTable(tableChecker)
}
getSelection () {
return this.contentState.selectionChange()
}
setFocusMode (bool) {
const { container } = this
const { focusMode } = this.options
if (bool && !focusMode) {
container.classList.add(CLASS_OR_ID.AG_FOCUS_MODE)
} else {
container.classList.remove(CLASS_OR_ID.AG_FOCUS_MODE)
}
this.options.focusMode = bool
}
setFont ({ fontSize, lineHeight }) {
if (fontSize) {
this.options.fontSize = parseInt(fontSize, 10)
}
if (lineHeight) {
this.options.lineHeight = lineHeight
}
this.contentState.render(false)
}
setTabSize (tabSize) {
if (!tabSize || typeof tabSize !== 'number') {
tabSize = 4
} else if (tabSize < 1) {
tabSize = 1
} else if (tabSize > 4) {
tabSize = 4
}
this.contentState.tabSize = tabSize
}
setListIndentation (listIndentation) {
if (typeof listIndentation === 'number') {
if (listIndentation < 1 || listIndentation > 4) {
listIndentation = 1
}
} else if (listIndentation !== 'dfm') {
listIndentation = 1
}
this.contentState.listIndentation = listIndentation
}
updateParagraph (type) {
this.contentState.updateParagraph(type)
}
duplicate () {
this.contentState.duplicate()
}
deleteParagraph () {
this.contentState.deleteParagraph()
}
insertParagraph (location/* before or after */, text = '', outMost = false) {
this.contentState.insertParagraph(location, text, outMost)
}
editTable (data) {
this.contentState.editTable(data)
}
hasFocus () {
return document.activeElement === this.container
}
focus () {
this.contentState.setCursor()
this.container.focus()
}
blur (isRemoveAllRange = false, unSelect = false) {
if (isRemoveAllRange) {
const selection = document.getSelection()
selection.removeAllRanges()
}
if (unSelect) {
this.contentState.selectedImage = null
this.contentState.selectedTableCells = null
}
this.hideAllFloatTools()
this.container.blur()
}
format (type) {
this.contentState.format(type)
}
insertImage (imageInfo) {
this.contentState.insertImage(imageInfo)
}
search (value, opt) {
const { selectHighlight } = opt
this.contentState.search(value, opt)
this.contentState.render(!!selectHighlight)
return this.contentState.searchMatches
}
replace (value, opt) {
this.contentState.replace(value, opt)
this.contentState.render(false)
return this.contentState.searchMatches
}
find (action/* pre or next */) {
this.contentState.find(action)
this.contentState.render(false)
return this.contentState.searchMatches
}
on (event, listener) {
this.eventCenter.subscribe(event, listener)
}
off (event, listener) {
this.eventCenter.unsubscribe(event, listener)
}
once (event, listener) {
this.eventCenter.subscribeOnce(event, listener)
}
invalidateImageCache () {
this.contentState.stateRender.invalidateImageCache()
this.contentState.render(true)
}
undo () {
this.contentState.history.undo()
this.dispatchSelectionChange()
this.dispatchSelectionFormats()
this.dispatchChange()
}
redo () {
this.contentState.history.redo()
this.dispatchSelectionChange()
this.dispatchSelectionFormats()
this.dispatchChange()
}
selectAll () {
if (!this.hasFocus() && !this.contentState.selectedTableCells) {
return
}
this.contentState.selectAll()
}
/**
* Get all images' src from the given markdown.
* @param {string} markdown you want to extract images from this markdown.
*/
extractImages (markdown = this.markdown) {
return this.contentState.extractImages(markdown)
}
copyAsMarkdown () {
this.clipboard.copyAsMarkdown()
}
copyAsHtml () {
this.clipboard.copyAsHtml()
}
pasteAsPlainText () {
this.clipboard.pasteAsPlainText()
}
/**
* Copy the anchor block contains the block with `info`. like copy as markdown.
* @param {string|object} key the block key or block
*/
copy (info) {
return this.clipboard.copy('copyBlock', info)
}
setOptions (options, needRender = false) {
// FIXME: Just to be sure, disabled due to #1648.
if (options.codeBlockLineNumbers) {
options.codeBlockLineNumbers = false
}
Object.assign(this.options, options)
if (needRender) {
this.contentState.render(false, true)
}
// Set quick insert hint visibility
const hideQuickInsertHint = options.hideQuickInsertHint
if (typeof hideQuickInsertHint !== 'undefined') {
const hasClass = this.container.classList.contains('ag-show-quick-insert-hint')
if (hideQuickInsertHint && hasClass) {
this.container.classList.remove('ag-show-quick-insert-hint')
} else if (!hideQuickInsertHint && !hasClass) {
this.container.classList.add('ag-show-quick-insert-hint')
}
}
// Set spellcheck container attribute
const spellcheckEnabled = options.spellcheckEnabled
if (typeof spellcheckEnabled !== 'undefined') {
this.container.setAttribute('spellcheck', !!spellcheckEnabled)
}
if (options.bulletListMarker) {
this.contentState.turndownConfig.bulletListMarker = options.bulletListMarker
}
}
hideAllFloatTools () {
return this.keyboard.hideAllFloatTools()
}
/**
* Replace the word range with the given replacement.
*
* @param {*} line A line block reference of the line that contains the word to
* replace - must be a valid reference!
* @param {*} wordCursor The range of the word to replace (line: "abc >foo< abc"
* whereas `>`/`<` is start and end of `wordCursor`). This
* range is replaced by `replacement`.
* @param {string} replacement The replacement.
* @param {boolean} setCursor Shoud we update the editor cursor?
*/
replaceWordInline (line, wordCursor, replacement, setCursor = false) {
this.contentState.replaceWordInline(line, wordCursor, replacement, setCursor)
}
/**
* Replace the current selected word with the given replacement.
*
* NOTE: Unsafe method because exacly one word have to be selected. This
* is currently used to replace a misspelled word in MarkText that was selected
* by Chromium.
*
* @param {string} word The old word that should be replaced. The whole word must be selected.
* @param {string} replacement The word to replace the selecte one.
* @returns {boolean} True on success.
*/
_replaceCurrentWordInlineUnsafe (word, replacement) { // __MARKTEXT_PATCH__
return this.contentState._replaceCurrentWordInlineUnsafe(word, replacement)
}
destroy () {
this.contentState.clear()
this.quickInsert.destroy()
this.codePicker.destroy()
this.tablePicker.destroy()
this.emojiPicker.destroy()
this.imagePathPicker.destroy()
this.eventCenter.detachAllDomEvents()
}
}
/**
* [ensureContainerDiv ensure container element is div]
*/
function getContainer (originContainer, options) {
const { hideQuickInsertHint, spellcheckEnabled } = options
const container = document.createElement('div')
const rootDom = document.createElement('div')
const attrs = originContainer.attributes
// copy attrs from origin container to new div element
Array.from(attrs).forEach(attr => {
container.setAttribute(attr.name, attr.value)
})
if (!hideQuickInsertHint) {
container.classList.add('ag-show-quick-insert-hint')
}
container.setAttribute('contenteditable', true)
container.setAttribute('autocorrect', false)
container.setAttribute('autocomplete', 'off')
// NOTE: The browser is not able to correct misspelled words words without
// a custom implementation like in MarkText.
container.setAttribute('spellcheck', !!spellcheckEnabled)
container.appendChild(rootDom)
originContainer.replaceWith(container)
return container
}
export default Muya
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/searchCtrl.js | src/muya/lib/contentState/searchCtrl.js | import execAll from 'execall'
import { defaultSearchOption } from '../config'
const matchString = (text, value, options) => {
const { isCaseSensitive, isWholeWord, isRegexp } = options
/* eslint-disable no-useless-escape */
const SPECIAL_CHAR_REG = /[\[\]\\^$.\|\?\*\+\(\)\/]{1}/g
/* eslint-enable no-useless-escape */
let SEARCH_REG = null
let regStr = value
let flag = 'g'
if (!isCaseSensitive) {
flag += 'i'
}
if (!isRegexp) {
regStr = value.replace(SPECIAL_CHAR_REG, (p) => {
return p === '\\' ? '\\\\' : `\\${p}`
})
}
if (isWholeWord) {
regStr = `\\b${regStr}\\b`
}
try {
// Add try catch expression because not all string can generate a valid RegExp. for example `\`.
SEARCH_REG = new RegExp(regStr, flag)
return execAll(SEARCH_REG, text)
} catch (err) {
return []
}
}
const searchCtrl = ContentState => {
ContentState.prototype.buildRegexValue = function (match, value) {
const groups = value.match(/(?<!\\)\$\d/g)
if (Array.isArray(groups) && groups.length) {
for (const group of groups) {
const index = parseInt(group.replace(/^\$/, ''))
if (index === 0) {
value = value.replace(group, match.match)
} else if (index > 0 && index <= match.subMatches.length) {
value = value.replace(group, match.subMatches[index - 1])
}
}
}
return value
}
ContentState.prototype.replaceOne = function (match, value) {
const { start, end, key } = match
const block = this.getBlock(key)
const { text } = block
block.text = text.substring(0, start) + value + text.substring(end)
}
ContentState.prototype.replace = function (replaceValue, opt = { isSingle: true }) {
const { isSingle, isRegexp } = opt
delete opt.isSingle
const searchOptions = Object.assign({}, defaultSearchOption, opt)
const { matches, value, index } = this.searchMatches
if (matches.length) {
if (isRegexp) {
replaceValue = this.buildRegexValue(matches[index], replaceValue)
}
if (isSingle) {
// replace single
this.replaceOne(matches[index], replaceValue)
} else {
// replace all
for (const match of matches) {
this.replaceOne(match, replaceValue)
}
}
const highlightIndex = index < matches.length - 1 ? index : index - 1
this.search(value, { ...searchOptions, highlightIndex: isSingle ? highlightIndex : -1 })
}
}
ContentState.prototype.setCursorToHighlight = function () {
const { matches, index } = this.searchMatches
const match = matches[index]
if (!match) return
const { key, start, end } = match
this.cursor = {
noHistory: true,
start: {
key,
offset: start
},
end: {
key,
offset: end
}
}
}
ContentState.prototype.find = function (action/* prev next */) {
let { matches, index } = this.searchMatches
const len = matches.length
if (!len) return
index = action === 'next' ? index + 1 : index - 1
if (index < 0) index = len - 1
if (index >= len) index = 0
this.searchMatches.index = index
this.setCursorToHighlight()
}
ContentState.prototype.search = function (value, opt = {}) {
const matches = []
const options = Object.assign({}, defaultSearchOption, opt)
const { highlightIndex } = options
const { blocks } = this
const travel = blocks => {
for (const block of blocks) {
let { text, key } = block
if (text && typeof text === 'string') {
const strMatches = matchString(text, value, options)
matches.push(...strMatches.map(({ index, match, subMatches }) => {
return {
key,
start: index,
end: index + match.length,
match,
subMatches
}
}))
}
if (block.children.length) {
travel(block.children)
}
}
}
if (value) travel(blocks)
let index = -1
if (highlightIndex !== -1) {
index = highlightIndex // If set the highlight index, then highlight the highlighIndex
} else if (matches.length) {
index = 0 // highlight the first word that matches.
}
Object.assign(this.searchMatches, { value, matches, index })
if (value) {
this.setCursorToHighlight()
}
return matches
}
}
export default searchCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/paragraphCtrl.js | src/muya/lib/contentState/paragraphCtrl.js | import selection from '../selection'
import { PARAGRAPH_TYPES, DEFAULT_TURNDOWN_CONFIG } from '../config'
import ExportMarkdown from '../utils/exportMarkdown'
// get header level
// eg: h1 => 1
// h2 => 2
const getCurrentLevel = type => {
if (/\d/.test(type)) {
return Number(/\d/.exec(type)[0])
} else {
return 0
}
}
const paragraphCtrl = ContentState => {
ContentState.prototype.selectionChange = function (cursor) {
const { start, end } = cursor || selection.getCursorRange()
if (!start || !end) {
// TODO: Throw an exception and try to fix this later (GH#848).
throw new Error('selectionChange: expected cursor but cursor is null.')
}
const cursorCoords = selection.getCursorCoords()
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const startParents = this.getParents(startBlock)
const endParents = this.getParents(endBlock)
const affiliation = startParents
.filter(p => endParents.includes(p))
.filter(p => PARAGRAPH_TYPES.includes(p.type))
start.type = startBlock.type
start.block = startBlock
end.type = endBlock.type
end.block = endBlock
return {
start,
end,
affiliation,
cursorCoords
}
}
ContentState.prototype.getCommonParent = function () {
const { start, end, affiliation } = this.selectionChange()
const parent = affiliation.length ? affiliation[0] : null
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const startParentKeys = this.getParents(startBlock).map(b => b.key)
const endParentKeys = this.getParents(endBlock).map(b => b.key)
const children = parent ? parent.children : this.blocks
let startIndex
let endIndex
for (const child of children) {
if (startParentKeys.includes(child.key)) {
startIndex = children.indexOf(child)
}
if (endParentKeys.includes(child.key)) {
endIndex = children.indexOf(child)
}
}
return { parent, startIndex, endIndex }
}
ContentState.prototype.handleFrontMatter = function () {
const firstBlock = this.blocks[0]
if (firstBlock.type === 'pre' && firstBlock.functionType === 'frontmatter') return
const { frontmatterType } = this.muya.options
let lang
let style
switch (frontmatterType) {
case '+':
lang = 'toml'
style = '+'
break
case ';':
lang = 'json'
style = ';'
break
case '{':
lang = 'json'
style = '{'
break
default:
lang = 'yaml'
style = '-'
break
}
const frontMatter = this.createBlock('pre', {
functionType: 'frontmatter',
lang,
style
})
const codeBlock = this.createBlock('code', {
lang
})
const emptyCodeContent = this.createBlock('span', {
functionType: 'codeContent',
lang
})
this.appendChild(codeBlock, emptyCodeContent)
this.appendChild(frontMatter, codeBlock)
this.insertBefore(frontMatter, firstBlock)
const { key } = emptyCodeContent
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
// TODO: New created nestled list items missing "listType" key and value.
ContentState.prototype.handleListMenu = function (paraType, insertMode) {
const { start, end, affiliation } = this.selectionChange(this.cursor)
const { orderListDelimiter, bulletListMarker, preferLooseListItem } = this.muya.options
const [blockType, listType] = paraType.split('-')
const isListed = affiliation.slice(0, 3).filter(b => /ul|ol/.test(b.type))
if (isListed.length && !insertMode) {
const listBlock = isListed[0]
if (listType === listBlock.listType) {
const listItems = listBlock.children
listItems.forEach(listItem => {
listItem.children.forEach(itemParagraph => {
if (itemParagraph.type !== 'input') {
this.insertBefore(itemParagraph, listBlock)
}
})
})
this.removeBlock(listBlock)
return
}
// if the old list block is task list, remove checkbox
if (listBlock.listType === 'task') {
const listItems = listBlock.children
listItems.forEach(item => {
const inputBlock = item.children[0]
inputBlock && this.removeBlock(inputBlock)
})
}
const oldListType = listBlock.listType
listBlock.type = blockType
listBlock.listType = listType
listBlock.children.forEach(b => (b.listItemType = listType))
if (listType === 'order') {
listBlock.start = listBlock.start || 1
listBlock.children.forEach(b => (b.bulletMarkerOrDelimiter = orderListDelimiter))
}
if (
(listType === 'bullet' && oldListType === 'order') ||
(listType === 'task' && oldListType === 'order')
) {
delete listBlock.start
listBlock.children.forEach(b => (b.bulletMarkerOrDelimiter = bulletListMarker))
}
// if the new block is task list, add checkbox
if (listType === 'task') {
const listItems = listBlock.children
listItems.forEach(item => {
const checkbox = this.createBlock('input')
checkbox.checked = false
this.insertBefore(checkbox, item.children[0])
})
}
} else {
if (start.key === end.key || (start.block.parent && start.block.parent === end.block.parent)) {
const block = this.getBlock(start.key)
const paragraph = this.getBlock(block.parent)
if (listType === 'task') {
// 1. first update the block to bullet list
const listItemParagraph = this.updateList(paragraph, 'bullet', undefined, block)
// 2. second update bullet list to task list
setTimeout(() => {
this.updateTaskListItem(listItemParagraph, listType)
this.partialRender()
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
this.muya.dispatchChange()
})
return false
} else {
this.updateList(paragraph, listType, undefined, block)
}
} else {
const { parent, startIndex, endIndex } = this.getCommonParent()
const children = parent ? parent.children : this.blocks
const referBlock = children[endIndex]
const listWrapper = this.createBlock(listType === 'order' ? 'ol' : 'ul')
listWrapper.listType = listType
if (listType === 'order') listWrapper.start = 1
children.slice(startIndex, endIndex + 1).forEach(child => {
if (child !== referBlock) {
this.removeBlock(child, children)
} else {
this.insertAfter(listWrapper, child)
this.removeBlock(child, children)
}
const listItem = this.createBlock('li')
listItem.listItemType = listType
listItem.isLooseListItem = preferLooseListItem
this.appendChild(listWrapper, listItem)
if (listType === 'task') {
const checkbox = this.createBlock('input')
checkbox.checked = false
this.appendChild(listItem, checkbox)
}
this.appendChild(listItem, child)
})
}
}
return true
}
ContentState.prototype.handleLooseListItem = function () {
const { affiliation } = this.selectionChange(this.cursor)
let listContainer = []
if (affiliation.length >= 1 && /ul|ol/.test(affiliation[0].type)) {
listContainer = affiliation[0].children
} else if (affiliation.length >= 3 && affiliation[1].type === 'li') {
listContainer = affiliation[2].children
}
if (listContainer.length > 0) {
for (const block of listContainer) {
block.isLooseListItem = !block.isLooseListItem
}
this.partialRender()
}
}
ContentState.prototype.handleCodeBlockMenu = function () {
const { start, end, affiliation } = this.selectionChange(this.cursor)
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const startParents = this.getParents(startBlock)
const endParents = this.getParents(endBlock)
const hasFencedCodeBlockParent = () => {
return [...startParents, ...endParents].some(b => b.type === 'pre' && /code/.test(b.functionType))
}
// change fenced code block to p paragraph
if (affiliation.length && affiliation[0].type === 'pre' && /code/.test(affiliation[0].functionType)) {
const codeBlock = affiliation[0]
const codeContent = codeBlock.children[1].children[0].text
const states = this.markdownToState(codeContent)
for (const state of states) {
this.insertBefore(state, codeBlock)
}
this.removeBlock(codeBlock)
const cursorBlock = this.firstInDescendant(states[0])
const { key, text } = cursorBlock
const offset = text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
} else {
if (start.key === end.key) {
if (startBlock.type === 'span') {
const anchorBlock = this.getParent(startBlock)
const lang = ''
const preBlock = this.createBlock('pre', {
functionType: 'fencecode',
lang
})
const codeBlock = this.createBlock('code', {
lang
})
const inputBlock = this.createBlock('span', {
functionType: 'languageInput'
})
const codeContent = this.createBlock('span', {
text: startBlock.text,
lang,
functionType: 'codeContent'
})
this.appendChild(codeBlock, codeContent)
this.appendChild(preBlock, inputBlock)
this.appendChild(preBlock, codeBlock)
this.insertBefore(preBlock, anchorBlock)
this.removeBlock(anchorBlock)
const { key } = inputBlock
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
} else {
this.cursor = {
start: this.cursor.start,
end: this.cursor.end
}
}
} else if (!hasFencedCodeBlockParent()) {
const { parent, startIndex, endIndex } = this.getCommonParent()
const children = parent ? parent.children : this.blocks
const referBlock = children[endIndex]
const lang = ''
const preBlock = this.createBlock('pre', {
functionType: 'fencecode',
lang
})
const codeBlock = this.createBlock('code', {
lang
})
const { isGitlabCompatibilityEnabled, listIndentation } = this
const markdown = new ExportMarkdown(
children.slice(startIndex, endIndex + 1),
listIndentation,
isGitlabCompatibilityEnabled
).generate()
const codeContent = this.createBlock('span', {
text: markdown,
lang,
functionType: 'codeContent'
})
const inputBlock = this.createBlock('span', {
functionType: 'languageInput'
})
this.appendChild(codeBlock, codeContent)
this.appendChild(preBlock, inputBlock)
this.appendChild(preBlock, codeBlock)
this.insertAfter(preBlock, referBlock)
let i
const removeCache = []
for (i = startIndex; i <= endIndex; i++) {
const child = children[i]
removeCache.push(child)
}
removeCache.forEach(b => this.removeBlock(b))
const key = inputBlock.key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
}
}
ContentState.prototype.handleQuoteMenu = function (insertMode) {
const { start, end, affiliation } = this.selectionChange(this.cursor)
let startBlock = this.getBlock(start.key)
const isBlockQuote = affiliation.slice(0, 2).filter(b => /blockquote/.test(b.type))
// change blockquote to paragraph
if (isBlockQuote.length && !insertMode) {
const quoteBlock = isBlockQuote[0]
const children = quoteBlock.children
for (const child of children) {
this.insertBefore(child, quoteBlock)
}
this.removeBlock(quoteBlock)
// change paragraph to blockquote
} else {
if (start.key === end.key) {
if (startBlock.type === 'span') {
startBlock = this.getParent(startBlock)
}
const quoteBlock = this.createBlock('blockquote')
this.insertAfter(quoteBlock, startBlock)
this.removeBlock(startBlock)
this.appendChild(quoteBlock, startBlock)
} else {
const { parent, startIndex, endIndex } = this.getCommonParent()
const children = parent ? parent.children : this.blocks
const referBlock = children[endIndex]
const quoteBlock = this.createBlock('blockquote')
children.slice(startIndex, endIndex + 1).forEach(child => {
if (child !== referBlock) {
this.removeBlock(child, children)
} else {
this.insertAfter(quoteBlock, child)
this.removeBlock(child, children)
}
this.appendChild(quoteBlock, child)
})
}
}
}
ContentState.prototype.insertContainerBlock = function (functionType, block) {
const anchor = this.getAnchor(block)
if (!anchor) {
console.error('Can not find the anchor paragraph to insert paragraph')
return
}
const value = anchor.type === 'p'
? anchor.children.map(child => child.text).join('\n').trim()
: ''
const containerBlock = this.createContainerBlock(functionType, value)
this.insertAfter(containerBlock, anchor)
if (anchor.type === 'p') {
this.removeBlock(anchor)
}
const cursorBlock = containerBlock.children[0].children[0].children[0]
const { key } = cursorBlock
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
ContentState.prototype.showTablePicker = function () {
const { eventCenter } = this.muya
const reference = this.getPositionReference()
const handler = (rows, columns) => {
this.createTable({ rows: rows + 1, columns: columns + 1 })
}
eventCenter.dispatch('muya-table-picker', { row: -1, column: -1 }, reference, handler.bind(this))
}
ContentState.prototype.insertHtmlBlock = function (block) {
if (block.type === 'span') {
block = this.getParent(block)
}
const preBlock = this.initHtmlBlock(block)
const cursorBlock = this.firstInDescendant(preBlock)
const { key, text } = cursorBlock
const match = /^[^\n]+\n[^\n]*/.exec(text)
const offset = match && match[0] ? match[0].length : 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
ContentState.prototype.updateParagraph = function (paraType, insertMode = false) {
const { start, end } = this.cursor
const block = this.getBlock(start.key)
const { text, type } = block
let needDispatchChange = true
// Only allow valid transformations.
if (!this.isAllowedTransformation(block, paraType, start.key !== end.key)) {
return
}
// Convert back to paragraph.
if (paraType === 'reset-to-paragraph') {
const blockType = this.getTypeFromBlock(block)
if (!blockType) {
return
}
if (blockType === 'table') {
return
} else if (/heading|hr/.test(blockType)) {
paraType = 'paragraph'
} else {
paraType = blockType
}
}
switch (paraType) {
case 'front-matter': {
this.handleFrontMatter()
break
}
case 'ul-bullet':
case 'ul-task':
case 'ol-order': {
needDispatchChange = this.handleListMenu(paraType, insertMode)
break
}
case 'loose-list-item': {
this.handleLooseListItem()
break
}
case 'pre': {
this.handleCodeBlockMenu()
break
}
case 'blockquote': {
this.handleQuoteMenu(insertMode)
break
}
case 'mathblock': {
this.insertContainerBlock('multiplemath', block)
break
}
case 'table': {
this.showTablePicker()
break
}
case 'html': {
this.insertHtmlBlock(block)
break
}
case 'flowchart':
case 'sequence':
case 'plantuml':
case 'mermaid':
case 'vega-lite':
this.insertContainerBlock(paraType, block)
break
case 'heading 1':
case 'heading 2':
case 'heading 3':
case 'heading 4':
case 'heading 5':
case 'heading 6':
case 'upgrade heading':
case 'degrade heading':
case 'paragraph': {
if (start.key !== end.key) {
return
}
const headingStyle = DEFAULT_TURNDOWN_CONFIG.headingStyle
const parent = this.getParent(block)
// \u00A0 is
const [, hash, partText] = /(^ {0,3}#*[ \u00A0]*)([\s\S]*)/.exec(text)
let newLevel = 0 // 1, 2, 3, 4, 5, 6
let newType = 'p'
let key
if (/\d/.test(paraType)) {
newLevel = Number(paraType.split(/\s/)[1])
newType = `h${newLevel}`
} else if (paraType === 'upgrade heading' || paraType === 'degrade heading') {
const currentLevel = getCurrentLevel(parent.type)
newLevel = currentLevel
if (paraType === 'upgrade heading' && currentLevel !== 1) {
if (currentLevel === 0) newLevel = 6
else newLevel = currentLevel - 1
} else if (paraType === 'degrade heading' && currentLevel !== 0) {
if (currentLevel === 6) newLevel = 0
else newLevel = currentLevel + 1
}
newType = newLevel === 0 ? 'p' : `h${newLevel}`
}
const startOffset = newLevel > 0
? start.offset + newLevel - hash.length + 1
: start.offset - hash.length // no need to add `1`, because we didn't add `String.fromCharCode(160)` to text paragraph
const endOffset = newLevel > 0
? end.offset + newLevel - hash.length + 1
: end.offset - hash.length
let newText = newLevel > 0
? '#'.repeat(newLevel) + `${String.fromCharCode(160)}${partText}` // code: 160
: partText
// Remove <hr> content when converting to paragraph.
if (type === 'span' && block.functionType === 'thematicBreakLine') {
newText = ''
}
// No change
if (newType === 'p' && parent.type === newType) {
return
}
// No change
if (newType !== 'p' && parent.type === newType && parent.headingStyle === headingStyle) {
return
}
if (newType !== 'p') {
const header = this.createBlock(newType, {
headingStyle
})
const headerContent = this.createBlock('span', {
text: headingStyle === 'atx' ? newText.replace(/\n/g, ' ') : newText,
functionType: headingStyle === 'atx' ? 'atxLine' : 'paragraphContent'
})
this.appendChild(header, headerContent)
key = headerContent.key
this.insertBefore(header, parent)
this.removeBlock(parent)
} else {
const pBlock = this.createBlockP(newText)
key = pBlock.children[0].key
this.insertAfter(pBlock, parent)
this.removeBlock(parent)
}
this.cursor = {
start: { key, offset: startOffset },
end: { key, offset: endOffset }
}
break
}
case 'hr': {
const pBlock = this.createBlockP()
const archor = block.type === 'span' ? this.getParent(block) : block
const hrBlock = this.createBlock('hr')
const thematicContent = this.createBlock('span', {
functionType: 'thematicBreakLine',
text: '---'
})
this.appendChild(hrBlock, thematicContent)
this.insertAfter(hrBlock, archor)
this.insertAfter(pBlock, hrBlock)
if (!text) {
if (block.type === 'span' && this.isOnlyChild(block)) {
this.removeBlock(archor)
} else {
this.removeBlock(block)
}
}
const { key } = pBlock.children[0]
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
break
}
}
if (paraType === 'front-matter' || paraType === 'pre') {
this.render()
} else {
this.partialRender()
}
if (needDispatchChange) {
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
this.muya.dispatchChange()
}
}
ContentState.prototype.insertParagraph = function (location, text = '', outMost = false) {
const { start, end } = this.cursor
// if cursor is not in one line or paragraph, can not insert paragraph
if (start.key !== end.key) return
const block = this.getBlock(start.key)
let anchor = null
if (outMost) {
anchor = this.findOutMostBlock(block)
} else {
anchor = this.getAnchor(block)
}
// You can not insert paragraph before frontmatter
if (!anchor || anchor && anchor.functionType === 'frontmatter' && location === 'before') {
return
}
const newBlock = this.createBlockP(text)
if (location === 'before') {
this.insertBefore(newBlock, anchor)
} else {
this.insertAfter(newBlock, anchor)
}
const { key } = newBlock.children[0]
const offset = text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
this.muya.eventCenter.dispatch('stateChange')
}
// make a dulication of the current block
ContentState.prototype.duplicate = function () {
const { start, end } = this.cursor
const startOutmostBlock = this.findOutMostBlock(this.getBlock(start.key))
const endOutmostBlock = this.findOutMostBlock(this.getBlock(end.key))
if (startOutmostBlock !== endOutmostBlock) {
// if the cursor is not in one paragraph, just return
return
}
// if copied block has pre block: html, multiplemath, vega-light, mermaid, flowchart, sequence, plantuml...
const copiedBlock = this.copyBlock(startOutmostBlock)
this.insertAfter(copiedBlock, startOutmostBlock)
const cursorBlock = this.firstInDescendant(copiedBlock)
// set cursor at the end of the first descendant of the duplicated block.
const { key, text } = cursorBlock
const offset = text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
return this.muya.eventCenter.dispatch('stateChange')
}
// delete current paragraph
ContentState.prototype.deleteParagraph = function (blockKey) {
let startOutmostBlock
if (blockKey) {
const block = this.getBlock(blockKey)
const firstEditableBlock = this.firstInDescendant(block)
startOutmostBlock = this.getAnchor(firstEditableBlock)
} else {
const { start, end } = this.cursor
startOutmostBlock = this.findOutMostBlock(this.getBlock(start.key))
const endOutmostBlock = this.findOutMostBlock(this.getBlock(end.key))
if (startOutmostBlock !== endOutmostBlock) {
// if the cursor is not in one paragraph, just return
return
}
}
const preBlock = this.getBlock(startOutmostBlock.preSibling)
const nextBlock = this.getBlock(startOutmostBlock.nextSibling)
let cursorBlock = null
if (nextBlock) {
cursorBlock = this.firstInDescendant(nextBlock)
} else if (preBlock) {
cursorBlock = this.lastInDescendant(preBlock)
} else {
const newBlock = this.createBlockP()
this.insertAfter(newBlock, startOutmostBlock)
cursorBlock = this.firstInDescendant(newBlock)
}
this.removeBlock(startOutmostBlock)
const { key, text } = cursorBlock
const offset = text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
return this.muya.eventCenter.dispatch('stateChange')
}
ContentState.prototype.isSelectAll = function () {
const firstTextBlock = this.getFirstBlock()
const lastTextBlock = this.getLastBlock()
const { start, end } = this.cursor
return firstTextBlock.key === start.key &&
start.offset === 0 &&
lastTextBlock.key === end.key &&
end.offset === lastTextBlock.text.length &&
!this.muya.keyboard.isComposed
}
ContentState.prototype.selectAllContent = function () {
const firstTextBlock = this.getFirstBlock()
const lastTextBlock = this.getLastBlock()
this.cursor = {
start: {
key: firstTextBlock.key,
offset: 0
},
end: {
key: lastTextBlock.key,
offset: lastTextBlock.text.length
}
}
return this.render()
}
ContentState.prototype.selectAll = function () {
const mayBeCell = this.isSingleCellSelected()
const mayBeTable = this.isWholeTableSelected()
if (mayBeTable) {
this.selectedTableCells = null
return this.selectAllContent()
}
// Select whole table if already select one cell.
if (mayBeCell) {
const table = this.closest(mayBeCell, 'table')
if (table) {
return this.selectTable(table)
}
}
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
// handle selectAll in table.
if (startBlock.functionType === 'cellContent' && endBlock.functionType === 'cellContent') {
if (start.key === end.key) {
const table = this.closest(startBlock, 'table')
const cellBlock = this.closest(startBlock, /th|td/)
this.selectedTableCells = {
tableId: table.key,
row: 1,
column: 1,
cells: [{
key: cellBlock.key,
text: cellBlock.children[0].text,
top: true,
right: true,
bottom: true,
left: true
}]
}
this.singleRender(table, false)
return this.muya.eventCenter.dispatch('muya-format-picker', { reference: null })
} else {
const startTable = this.closest(startBlock, 'table')
const endTable = this.closest(endBlock, 'table')
// Check whether both blocks are in the same table.
if (!startTable || !endTable) {
console.error('No table found or invalid type.')
return
} else if (startTable.key !== endTable.key) {
// Select entire document
return
}
return this.selectTable(startTable)
}
}
// Handler selectAll in code block. only select all the code block conent.
// `code block` here is Math, HTML, BLOCK CODE, Mermaid, vega-lite, flowchart, front-matter etc...
if (startBlock.type === 'span' && startBlock.functionType === 'codeContent') {
const { key } = startBlock
this.cursor = {
start: {
key,
offset: 0
},
end: {
key,
offset: startBlock.text.length
}
}
return this.partialRender()
}
// Handler language input, only select language info only...
if (startBlock.type === 'span' && startBlock.functionType === 'languageInput') {
this.cursor = {
start: {
key: startBlock.key,
offset: 0
},
end: {
key: startBlock.key,
offset: startBlock.text.length
}
}
return this.partialRender()
}
return this.selectAllContent()
}
// Test whether the paragraph transformation is valid.
ContentState.prototype.isAllowedTransformation = function (block, toType, isMultilineSelection) {
const fromType = this.getTypeFromBlock(block)
if (toType === 'front-matter') {
// Front matter block is added at the beginning.
return true
} else if (!fromType) {
return false
} else if (isMultilineSelection && /heading|table/.test(toType)) {
return false
} else if (fromType === toType || toType === 'reset-to-paragraph') {
// Convert back to paragraph.
return true
}
switch (fromType) {
case 'ul-bullet':
case 'ul-task':
case 'ol-order':
case 'blockquote':
case 'paragraph': {
// Only allow line and table with an empty paragraph.
if (/hr|table/.test(toType) && block.text) {
return false
}
return true
}
case 'heading 1':
case 'heading 2':
case 'heading 3':
case 'heading 4':
case 'heading 5':
case 'heading 6':
return /paragraph|heading/.test(toType)
default:
// Tables and all code blocks are not allowed.
return false
}
}
// Translate block type into internal name.
ContentState.prototype.getTypeFromBlock = function (block) {
const { type } = block
let internalType = ''
const headingMatch = type.match(/^h([1-6]{1})$/)
if (headingMatch && headingMatch[1]) {
internalType = `heading ${headingMatch[1]}`
}
switch (type) {
case 'span': {
if (block.functionType === 'atxLine') {
internalType = 'heading 1' // loose match
} else if (block.functionType === 'languageInput') {
internalType = 'pre'
} else if (block.functionType === 'codeContent') {
if (block.lang === 'markup') {
internalType = 'html'
} else if (block.lang === 'latex') {
internalType = 'mathblock'
}
// We cannot easy distinguish between diagram and code blocks.
const rootBlock = this.getAnchor(block)
if (rootBlock && rootBlock.functionType !== 'fencecode') {
// Block seems to be a diagram block.
internalType = rootBlock.functionType
} else {
internalType = 'pre'
}
} else if (block.functionType === 'cellContent') {
internalType = 'table'
} else if (block.functionType === 'thematicBreakLine') {
internalType = 'hr'
}
// List and quote content is also a problem because it's shown as paragraph.
const { affiliation } = this.selectionChange(this.cursor)
const listTypes = affiliation
.slice(0, 3) // the third entry should be the ul/ol
.filter(b => /ul|ol/.test(b.type))
.map(b => b.listType)
// Prefer list or blockquote over paragraph.
if (listTypes && listTypes.length === 1) {
const listType = listTypes[0]
if (listType === 'bullet') {
internalType = 'ul-bullet'
} else if (listType === 'task') {
internalType = 'ul-task'
} if (listType === 'order') {
internalType = 'ol-order'
}
} else if (affiliation.length === 2 && affiliation[1].type === 'blockquote') {
internalType = 'blockquote'
} else if (block.functionType === 'paragraphContent') {
internalType = 'paragraph'
}
break
}
case 'div': {
// Preview for math formulas or diagramms.
return ''
}
case 'figure': {
if (block.functionType === 'multiplemath') {
internalType = 'mathblock'
} else {
internalType = block.functionType
}
break
}
case 'pre': {
if (block.functionType === 'multiplemath') {
internalType = 'mathblock'
} else if (block.functionType === 'fencecode' || block.functionType === 'indentcode') {
internalType = 'pre'
} else if (block.functionType === 'frontmatter') {
internalType = 'front-matter'
} else {
internalType = block.functionType
}
break
}
case 'ul': {
if (block.listType === 'task') {
internalType = 'ul-task'
} else {
internalType = 'ul-bullet'
}
break
}
case 'ol': {
internalType = 'ol-order'
break
}
case 'li': {
if (block.listItemType === 'order') {
internalType = 'ol-order'
} else if (block.listItemType === 'bullet') {
internalType = 'ul-bullet'
} else if (block.listItemType === 'task') {
internalType = 'ul-task'
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | true |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/core.js | src/muya/lib/contentState/core.js | const coreApi = ContentState => {
/**
* Replace the word range with the given replacement.
*
* @param {*} line A line block reference of the line that contain the word to
* replace - must be a valid reference.
* @param {*} wordCursor The range of the word to replace (line: "abc >foo< abc"
* where `>`/`<` is start and end of `wordCursor`). This
* range is replaced by `replacement`.
* @param {string} replacement The replacement.
* @param {boolean} setCursor Whether the editor cursor should be updated.
*/
ContentState.prototype.replaceWordInline = function (line, wordCursor, replacement, setCursor = false) {
const { start: lineStart, end: lineEnd } = line
const { start: wordStart, end: wordEnd } = wordCursor
// Validate cursor ranges.
if (wordStart.key !== wordEnd.key) {
throw new Error('Expect a single line word cursor: "start.key" is not equal to "end.key".')
} else if (lineStart.key !== lineEnd.key) {
throw new Error('Expect a single line line cursor: "start.key" is not equal to "end.key".')
} else if (wordStart.offset > wordEnd.offset) {
throw new Error(`Invalid word cursor offset: ${wordStart.offset} should be less ${wordEnd.offset}.`)
} else if (lineStart.key !== wordEnd.key) {
throw new Error(`Cursor mismatch: Expect the same line but got ${lineStart.key} and ${wordEnd.key}.`)
} else if (lineStart.block.text.length < wordEnd.offset) {
throw new Error('Invalid cursor: Replacement length is larger than line length.')
}
const { block } = lineStart
const { offset: left } = wordStart
const { offset: right } = wordEnd
// Replace word range with replacement.
block.text = block.text.substr(0, left) + replacement + block.text.substr(right)
// Update cursor
if (setCursor) {
const cursor = Object.assign({}, wordStart, {
offset: left + replacement.length
})
line.start = cursor
line.end = cursor
this.cursor = {
start: cursor,
end: cursor
}
}
this.partialRender()
this.muya.dispatchSelectionChange()
this.muya.dispatchChange()
}
}
export default coreApi
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/formatCtrl.js | src/muya/lib/contentState/formatCtrl.js | import selection from '../selection'
import { tokenizer, generator } from '../parser/'
import { FORMAT_MARKER_MAP, FORMAT_TYPES } from '../config'
import { getImageInfo } from '../utils/getImageInfo'
const getOffset = (offset, { range: { start, end }, type, tag, anchor, alt }) => {
const dis = offset - start
const len = end - start
switch (type) {
case 'strong':
case 'del':
case 'em':
case 'inline_code':
case 'inline_math': {
const MARKER_LEN = (type === 'strong' || type === 'del') ? 2 : 1
if (dis < 0) return 0
if (dis >= 0 && dis < MARKER_LEN) return -dis
if (dis >= MARKER_LEN && dis <= len - MARKER_LEN) return -MARKER_LEN
if (dis > len - MARKER_LEN && dis <= len) return len - dis - 2 * MARKER_LEN
if (dis > len) return -2 * MARKER_LEN
break
}
case 'html_tag': { // handle underline, sup, sub
const OPEN_MARKER_LEN = FORMAT_MARKER_MAP[tag].open.length
const CLOSE_MARKER_LEN = FORMAT_MARKER_MAP[tag].close.length
if (dis < 0) return 0
if (dis >= 0 && dis < OPEN_MARKER_LEN) return -dis
if (dis >= OPEN_MARKER_LEN && dis <= len - CLOSE_MARKER_LEN) return -OPEN_MARKER_LEN
if (dis > len - CLOSE_MARKER_LEN && dis <= len) return len - dis - OPEN_MARKER_LEN - CLOSE_MARKER_LEN
if (dis > len) return -OPEN_MARKER_LEN - CLOSE_MARKER_LEN
break
}
case 'link': {
const MARKER_LEN = 1
if (dis < MARKER_LEN) return 0
if (dis >= MARKER_LEN && dis <= MARKER_LEN + anchor.length) return -1
if (dis > MARKER_LEN + anchor.length) return anchor.length - dis
break
}
case 'image': {
const MARKER_LEN = 1
if (dis < MARKER_LEN) return 0
if (dis >= MARKER_LEN && dis < MARKER_LEN * 2) return -1
if (dis >= MARKER_LEN * 2 && dis <= MARKER_LEN * 2 + alt.length) return -2
if (dis > MARKER_LEN * 2 + alt.length) return alt.length - dis
break
}
}
}
const clearFormat = (token, { start, end }) => {
if (start) {
const deltaStart = getOffset(start.offset, token)
start.delata += deltaStart
}
if (end) {
const delataEnd = getOffset(end.offset, token)
end.delata += delataEnd
}
switch (token.type) {
case 'strong':
case 'del':
case 'em':
case 'link':
case 'html_tag': { // underline, sub, sup
const { parent } = token
const index = parent.indexOf(token)
parent.splice(index, 1, ...token.children)
break
}
case 'image': {
token.type = 'text'
token.raw = token.alt
delete token.marker
delete token.src
break
}
case 'inline_math':
case 'inline_code': {
token.type = 'text'
token.raw = token.content
delete token.marker
break
}
}
}
const addFormat = (type, block, { start, end }) => {
if (
block.type !== 'span' ||
(block.type === 'span' && !/paragraphContent|cellContent|atxLine/.test(block.functionType))
) {
return false
}
switch (type) {
case 'em':
case 'del':
case 'inline_code':
case 'strong':
case 'inline_math': {
const MARKER = FORMAT_MARKER_MAP[type]
const oldText = block.text
block.text = oldText.substring(0, start.offset) +
MARKER + oldText.substring(start.offset, end.offset) +
MARKER + oldText.substring(end.offset)
start.offset += MARKER.length
end.offset += MARKER.length
break
}
case 'sub':
case 'sup':
case 'mark':
case 'u': {
const MARKER = FORMAT_MARKER_MAP[type]
const oldText = block.text
block.text = oldText.substring(0, start.offset) +
MARKER.open + oldText.substring(start.offset, end.offset) +
MARKER.close + oldText.substring(end.offset)
start.offset += MARKER.open.length
end.offset += MARKER.open.length
break
}
case 'link':
case 'image': {
const oldText = block.text
const anchorTextLen = end.offset - start.offset
block.text = oldText.substring(0, start.offset) +
(type === 'link' ? '[' : '![') +
oldText.substring(start.offset, end.offset) + ']()' +
oldText.substring(end.offset)
// put cursor between `()`
start.offset += type === 'link' ? 3 + anchorTextLen : 4 + anchorTextLen
end.offset = start.offset
break
}
}
}
const checkTokenIsInlineFormat = token => {
const { type, tag } = token
if (FORMAT_TYPES.includes(type)) return true
if (type === 'html_tag' && /^(?:u|sub|sup|mark)$/i.test(tag)) return true
return false
}
const formatCtrl = ContentState => {
ContentState.prototype.selectionFormats = function ({ start, end } = selection.getCursorRange()) {
if (!start || !end) {
return { formats: [], tokens: [], neighbors: [] }
}
const startBlock = this.getBlock(start.key)
const formats = []
const neighbors = []
let tokens = []
if (start.key === end.key) {
const { text } = startBlock
tokens = tokenizer(text, {
options: this.muya.options
})
;(function iterator (tks) {
for (const token of tks) {
if (
checkTokenIsInlineFormat(token) &&
start.offset >= token.range.start &&
end.offset <= token.range.end
) {
formats.push(token)
}
if (
checkTokenIsInlineFormat(token) &&
((start.offset >= token.range.start && start.offset <= token.range.end) ||
(end.offset >= token.range.start && end.offset <= token.range.end) ||
(start.offset <= token.range.start && token.range.end <= end.offset))
) {
neighbors.push(token)
}
if (token.children && token.children.length) {
iterator(token.children)
}
}
})(tokens)
}
return { formats, tokens, neighbors }
}
ContentState.prototype.clearBlockFormat = function (block, { start, end } = selection.getCursorRange(), type) {
if (!start || !end) {
return
}
if (block.type === 'pre') return false
const { key } = block
let tokens
let neighbors
if (start.key === end.key && start.key === key) {
({ tokens, neighbors } = this.selectionFormats({ start, end }))
} else if (start.key !== end.key && start.key === key) {
({ tokens, neighbors } = this.selectionFormats({ start, end: { key: start.key, offset: block.text.length } }))
} else if (start.key !== end.key && end.key === key) {
({ tokens, neighbors } = this.selectionFormats({
start: {
key: end.key,
offset: 0
},
end
}))
} else {
({ tokens, neighbors } = this.selectionFormats({
start: {
key,
offset: 0
},
end: {
key,
offset: block.text.length
}
}))
}
neighbors = type
? neighbors.filter(n => {
return n.type === type ||
n.type === 'html_tag' && n.tag === type
})
: neighbors
for (const neighbor of neighbors) {
clearFormat(neighbor, { start, end })
}
start.offset += start.delata
end.offset += end.delata
block.text = generator(tokens)
}
ContentState.prototype.format = function (type) {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
start.delata = end.delata = 0
if (start.key === end.key) {
const { formats, tokens, neighbors } = this.selectionFormats()
const currentFormats = formats.filter(format => {
return format.type === type ||
format.type === 'html_tag' && format.tag === type
}).reverse()
const currentNeightbors = neighbors.filter(format => {
return format.type === type ||
format.type === 'html_tag' && format.tag === type
}).reverse()
// cache delata
if (type === 'clear') {
for (const neighbor of neighbors) {
clearFormat(neighbor, { start, end })
}
start.offset += start.delata
end.offset += end.delata
startBlock.text = generator(tokens)
} else if (currentFormats.length) {
for (const token of currentFormats) {
clearFormat(token, { start, end })
}
start.offset += start.delata
end.offset += end.delata
startBlock.text = generator(tokens)
} else {
if (currentNeightbors.length) {
for (const neighbor of currentNeightbors) {
clearFormat(neighbor, { start, end })
}
}
start.offset += start.delata
end.offset += end.delata
startBlock.text = generator(tokens)
addFormat(type, startBlock, { start, end })
if (type === 'image') {
// Show image selector when create a inline image by menu/shortcut/or just input `![]()`
requestAnimationFrame(() => {
const startNode = selection.getSelectionStart()
if (startNode) {
const imageWrapper = startNode.closest('.ag-inline-image')
if (imageWrapper && imageWrapper.classList.contains('ag-empty-image')) {
const imageInfo = getImageInfo(imageWrapper)
this.muya.eventCenter.dispatch('muya-image-selector', {
reference: imageWrapper,
imageInfo,
cb: () => {}
})
}
}
})
}
}
this.cursor = { start, end }
this.partialRender()
} else {
let nextBlock = startBlock
const formatType = type !== 'clear' ? type : undefined
while (nextBlock && nextBlock !== endBlock) {
this.clearBlockFormat(nextBlock, { start, end }, formatType)
nextBlock = this.findNextBlockInLocation(nextBlock)
}
this.clearBlockFormat(endBlock, { start, end }, formatType)
if (type !== 'clear') {
addFormat(type, startBlock, {
start,
end: { offset: startBlock.text.length }
})
nextBlock = this.findNextBlockInLocation(startBlock)
while (nextBlock && nextBlock !== endBlock) {
addFormat(type, nextBlock, {
start: { offset: 0 },
end: { offset: nextBlock.text.length }
})
nextBlock = this.findNextBlockInLocation(nextBlock)
}
addFormat(type, endBlock, {
start: { offset: 0 },
end
})
}
this.cursor = { start, end }
this.partialRender()
}
}
}
export default formatCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/tabCtrl.js | src/muya/lib/contentState/tabCtrl.js | import selection from '../selection'
import { HTML_TAGS, VOID_HTML_TAGS, HAS_TEXT_BLOCK_REG } from '../config'
import { tokenizer } from '../parser'
/**
* parseSelector
* div#id.className => {tag: 'div', id: 'id', className: 'className', isVoid: false}
*/
const parseSelector = (str = '') => {
const REG_EXP = /(#|\.)([^#.]+)/
let tag = ''
let id = ''
let className = ''
let isVoid = false
let cap
for (const tagName of HTML_TAGS) {
if (str.startsWith(tagName) && (!str[tagName.length] || /#|\./.test(str[tagName.length]))) {
tag = tagName
if (VOID_HTML_TAGS.indexOf(tagName) > -1) isVoid = true
str = str.substring(tagName.length)
}
}
if (tag !== '') {
cap = REG_EXP.exec(str)
while (cap && str.length) {
if (cap[1] === '#') {
id = cap[2]
} else {
className = cap[2]
}
str = str.substring(cap[0].length)
cap = REG_EXP.exec(str)
}
}
return { tag, id, className, isVoid }
}
const BOTH_SIDES_FORMATS = ['strong', 'em', 'inline_code', 'image', 'link', 'reference_image', 'reference_link', 'emoji', 'del', 'html_tag', 'inline_math']
const tabCtrl = ContentState => {
ContentState.prototype.findNextCell = function (block) {
if (block.functionType !== 'cellContent') {
throw new Error('only th and td can have next cell')
}
const cellBlock = this.getParent(block)
const nextSibling = this.getBlock(cellBlock.nextSibling)
const rowBlock = this.getBlock(cellBlock.parent)
const tbOrTh = this.getBlock(rowBlock.parent)
if (nextSibling) {
return this.firstInDescendant(nextSibling)
} else {
if (rowBlock.nextSibling) {
const nextRow = this.getBlock(rowBlock.nextSibling)
return this.firstInDescendant(nextRow)
} else if (tbOrTh.type === 'thead') {
const tBody = this.getBlock(tbOrTh.nextSibling)
if (tBody && tBody.children.length) {
return this.firstInDescendant(tBody)
}
}
}
return false
}
ContentState.prototype.findPreviousCell = function (block) {
if (block.functionType !== 'cellContent') {
throw new Error('only th and td can have previous cell')
}
const cellBlock = this.getParent(block)
const previousSibling = this.getBlock(cellBlock.preSibling)
const rowBlock = this.getBlock(cellBlock.parent)
const tbOrTh = this.getBlock(rowBlock.parent)
if (previousSibling) {
return this.firstInDescendant(previousSibling)
} else {
if (rowBlock.preSibling) {
const previousRow = this.getBlock(rowBlock.preSibling)
return this.lastInDescendant(previousRow)
} else if (tbOrTh.type === 'tbody') {
const tHead = this.getBlock(tbOrTh.preSibling)
if (tHead && tHead.children.length) {
return this.lastInDescendant(tHead)
}
}
}
return block
}
ContentState.prototype.isUnindentableListItem = function (block) {
const parent = this.getParent(block)
const listItem = this.getParent(parent)
const list = this.getParent(listItem)
const listParent = this.getParent(list)
if (!this.isCollapse()) return false
if (listParent && listParent.type === 'li') {
return !list.preSibling ? 'REPLACEMENT' : 'INDENT'
}
return false
}
ContentState.prototype.isIndentableListItem = function () {
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const parent = this.getParent(startBlock)
if (parent.type !== 'p' || !parent.parent) {
return false
}
const listItem = this.getParent(parent)
if (listItem.type !== 'li' || start.key !== end.key || start.offset !== end.offset) {
return false
}
// Now we know it's a list item. Check whether we can indent the list item.
const list = this.getParent(listItem)
return list && /ol|ul/.test(list.type) && listItem.preSibling
}
ContentState.prototype.unindentListItem = function (block, type) {
const pBlock = this.getParent(block)
const listItem = this.getParent(pBlock)
const list = this.getParent(listItem)
const listParent = this.getParent(list)
if (type === 'REPLACEMENT') {
this.insertBefore(pBlock, list)
if (this.isOnlyChild(listItem)) {
this.removeBlock(list)
} else {
this.removeBlock(listItem)
}
} else if (type === 'INDENT') {
if (list.children.length === 1) {
this.removeBlock(list)
} else {
const newList = this.createBlock(list.type)
let target = this.getNextSibling(listItem)
while (target) {
this.appendChild(newList, target)
const temp = target
target = this.getNextSibling(target)
this.removeBlock(temp, list)
}
if (newList.children.length) this.appendChild(listItem, newList)
this.removeBlock(listItem, list)
if (!list.children.length) {
this.removeBlock(list)
}
}
this.insertAfter(listItem, listParent)
let target = this.getNextSibling(list)
while (target) {
this.appendChild(listItem, target)
this.removeBlock(target, listParent)
target = this.getNextSibling(target)
}
}
return this.partialRender()
}
ContentState.prototype.indentListItem = function () {
const { start } = this.cursor
const startBlock = this.getBlock(start.key)
const parent = this.getParent(startBlock)
const listItem = this.getParent(parent)
const list = this.getParent(listItem)
const prevListItem = this.getPreSibling(listItem)
this.removeBlock(listItem)
// Search for a list in previous block
let newList = this.getLastChild(prevListItem)
if (!newList || !/ol|ul/.test(newList.type)) {
newList = this.createBlock(list.type)
this.appendChild(prevListItem, newList)
}
// Update item type only if we insert into an existing list
if (newList.children.length !== 0) {
listItem.isLooseListItem = newList.children[0].isLooseListItem
}
this.appendChild(newList, listItem)
return this.partialRender()
}
ContentState.prototype.insertTab = function () {
const tabSize = this.tabSize
const tabCharacter = String.fromCharCode(160).repeat(tabSize)
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
if (start.key === end.key && start.offset === end.offset) {
startBlock.text = startBlock.text.substring(0, start.offset) +
tabCharacter + endBlock.text.substring(end.offset)
const key = start.key
const offset = start.offset + tabCharacter.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
}
ContentState.prototype.checkCursorAtEndFormat = function (text, offset) {
const { labels } = this.stateRender
const tokens = tokenizer(text, {
hasBeginRules: false,
labels,
options: this.muya.options
})
let result = null
const walkTokens = tkns => {
for (const token of tkns) {
const { marker, type, range, children, srcAndTitle, hrefAndTitle, backlash, closeTag, isFullLink, label } = token
const { start, end } = range
if (BOTH_SIDES_FORMATS.includes(type) && offset > start && offset < end) {
switch (type) {
case 'strong':
case 'em':
case 'inline_code':
case 'emoji':
case 'del':
case 'inline_math': {
if (marker && offset === end - marker.length) {
result = {
offset: marker.length
}
return
}
break
}
case 'image':
case 'link': {
const linkTitleLen = (srcAndTitle || hrefAndTitle).length
const secondLashLen = backlash && backlash.second ? backlash.second.length : 0
if (offset === end - 3 - (linkTitleLen + secondLashLen)) {
result = {
offset: 2
}
return
} else if (offset === end - 1) {
result = {
offset: 1
}
return
}
break
}
case 'reference_image':
case 'reference_link': {
const labelLen = label ? label.length : 0
const secondLashLen = backlash && backlash.second ? backlash.second.length : 0
if (isFullLink) {
if (offset === end - 3 - labelLen - secondLashLen) {
result = {
offset: 2
}
return
} else if (offset === end - 1) {
result = {
offset: 1
}
return
}
} else if (offset === end - 1) {
result = {
offset: 1
}
return
}
break
}
case 'html_tag': {
if (closeTag && offset === end - closeTag.length) {
result = {
offset: closeTag.length
}
return
}
break
}
default:
break
}
}
if (children && children.length) {
walkTokens(children)
}
}
}
walkTokens(tokens)
return result
}
ContentState.prototype.tabHandler = function (event) {
// disable tab focus
event.preventDefault()
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
if (event.shiftKey && startBlock.functionType !== 'cellContent') {
const unindentType = this.isUnindentableListItem(startBlock)
if (unindentType) {
this.unindentListItem(startBlock, unindentType)
}
return
}
// Handle `tab` to jump to the end of format when the cursor is at the end of format content.
if (
start.key === end.key &&
start.offset === end.offset &&
HAS_TEXT_BLOCK_REG.test(startBlock.type) &&
startBlock.functionType !== 'codeContent' && // code content has no inline syntax
startBlock.functionType !== 'languageInput' // language input textarea has no inline syntax
) {
const { text, key } = startBlock
const { offset } = start
const atEnd = this.checkCursorAtEndFormat(text, offset)
if (atEnd) {
this.cursor = {
start: { key, offset: offset + atEnd.offset },
end: { key, offset: offset + atEnd.offset }
}
return this.partialRender()
}
}
// Auto-complete of inline html tag and html block and `html` code block.
if (
start.key === end.key &&
start.offset === end.offset &&
startBlock.type === 'span' &&
(!startBlock.functionType || startBlock.functionType === 'codeContent' && /markup|html|xml|svg|mathml/.test(startBlock.lang))
) {
const { text } = startBlock
const lastWordBeforeCursor = text.substring(0, start.offset).split(/\s+/).pop()
const { tag, isVoid, id, className } = parseSelector(lastWordBeforeCursor)
if (tag) {
const preText = text.substring(0, start.offset - lastWordBeforeCursor.length)
const postText = text.substring(end.offset)
if (!tag) return
let html = `<${tag}`
const key = startBlock.key
let startOffset = 0
let endOffset = 0
switch (tag) {
case 'img':
html += ' alt="" src=""'
startOffset = endOffset = html.length - 1
break
case 'input':
html += ' type="text"'
startOffset = html.length - 5
endOffset = html.length - 1
break
case 'a':
html += ' href=""'
startOffset = endOffset = html.length - 1
break
case 'link':
html += ' rel="stylesheet" href=""'
startOffset = endOffset = html.length - 1
break
}
if (id) {
html += ` id="${id}"`
}
if (className) {
html += ` class="${className}"`
}
html += '>'
if (startOffset === 0 && endOffset === 0) {
startOffset = endOffset = html.length
}
if (!isVoid) {
html += `</${tag}>`
}
startBlock.text = preText + html + postText
this.cursor = {
start: { key, offset: startOffset + preText.length },
end: { key, offset: endOffset + preText.length }
}
return this.partialRender()
}
}
// Handle `tab` key in table cell.
let nextCell
if (start.key === end.key && startBlock.functionType === 'cellContent') {
nextCell = event.shiftKey
? this.findPreviousCell(startBlock)
: this.findNextCell(startBlock)
} else if (endBlock.functionType === 'cellContent') {
nextCell = endBlock
}
if (nextCell) {
const { key } = nextCell
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
const figure = this.closest(nextCell, 'figure')
return this.singleRender(figure)
}
if (this.isIndentableListItem()) {
return this.indentListItem()
}
return this.insertTab()
}
}
export default tabCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/history.js | src/muya/lib/contentState/history.js | import { deepCopy } from '../utils'
import { UNDO_DEPTH } from '../config'
class History {
constructor (contentState) {
this.stack = []
this.index = -1
this.contentState = contentState
this.pending = null
}
undo () {
this.commitPending()
if (this.index > 0) {
this.index = this.index - 1
const state = deepCopy(this.stack[this.index])
const { blocks, cursor, renderRange } = state
cursor.noHistory = true
this.contentState.blocks = blocks
this.contentState.renderRange = renderRange
this.contentState.cursor = cursor
this.contentState.render()
}
}
redo () {
this.pending = null
const { index, stack } = this
const len = stack.length
if (index < len - 1) {
this.index = index + 1
const state = deepCopy(stack[this.index])
const { blocks, cursor, renderRange } = state
cursor.noHistory = true
this.contentState.blocks = blocks
this.contentState.renderRange = renderRange
this.contentState.cursor = cursor
this.contentState.render()
}
}
push (state) {
this.pending = null
this.stack.splice(this.index + 1)
const copyState = deepCopy(state)
this.stack.push(copyState)
if (this.stack.length > UNDO_DEPTH) {
this.stack.shift()
this.index = this.index - 1
}
this.index = this.index + 1
}
pushPending (state) {
this.pending = state
}
commitPending () {
if (this.pending) {
this.push(this.pending)
}
}
clearHistory () {
this.stack = []
this.index = -1
this.pending = null
}
}
export default History
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/linkCtrl.js | src/muya/lib/contentState/linkCtrl.js | const linkCtrl = ContentState => {
/**
* Change a link into text.
*/
ContentState.prototype.unlink = function (linkInfo) {
const { key, token } = linkInfo
const block = this.getBlock(key)
const { text } = block
let anchor
switch (token.type) {
case 'html_tag':
anchor = token.content
break
case 'link':
anchor = token.href
break
case 'text': {
const match = /^\[(.+?)\]/.exec(token.raw)
if (match && match[1]) {
anchor = match[1]
}
break
}
}
if (!anchor) {
console.error('Can not find anchor when unlink')
return
}
block.text = text.substring(0, token.range.start) + anchor + text.substring(token.range.end)
this.cursor = {
start: {
key,
offset: token.range.start
},
end: {
key,
offset: +token.range.start + anchor.length
}
}
this.singleRender(block)
return this.muya.dispatchChange()
}
}
export default linkCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/footnoteCtrl.js | src/muya/lib/contentState/footnoteCtrl.js | /* eslint-disable no-useless-escape */
const FOOTNOTE_REG = /^\[\^([^\^\[\]\s]+?)(?<!\\)\]: /
/* eslint-enable no-useless-escape */
const footnoteCtrl = ContentState => {
ContentState.prototype.updateFootnote = function (block, line) {
const { start, end } = this.cursor
const { text } = line
const match = FOOTNOTE_REG.exec(text)
const footnoteIdentifer = match[1]
const sectionWrapper = this.createBlock('figure', {
functionType: 'footnote'
})
const footnoteInput = this.createBlock('span', {
text: footnoteIdentifer,
functionType: 'footnoteInput'
})
const pBlock = this.createBlockP(text.substring(match[0].length))
this.appendChild(sectionWrapper, footnoteInput)
this.appendChild(sectionWrapper, pBlock)
this.insertBefore(sectionWrapper, block)
this.removeBlock(block)
const { key } = pBlock.children[0]
this.cursor = {
start: {
key,
offset: Math.max(0, start.offset - footnoteIdentifer.length)
},
end: {
key,
offset: Math.max(0, end.offset - footnoteIdentifer.length)
}
}
if (this.isCollapse()) {
this.checkInlineUpdate(pBlock.children[0])
}
this.render()
return sectionWrapper
}
ContentState.prototype.createFootnote = function (identifier) {
const { blocks } = this
const lastBlock = blocks[blocks.length - 1]
const newBlock = this.createBlockP(`[^${identifier}]: `)
this.insertAfter(newBlock, lastBlock)
const key = newBlock.children[0].key
const offset = newBlock.children[0].text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
const sectionWrapper = this.updateFootnote(newBlock, newBlock.children[0])
const id = sectionWrapper.key
const footnoteEle = document.querySelector(`#${id}`)
if (footnoteEle) {
footnoteEle.scrollIntoView({ behavior: 'smooth' })
}
}
}
export default footnoteCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/index.js | src/muya/lib/contentState/index.js | import { HAS_TEXT_BLOCK_REG, DEFAULT_TURNDOWN_CONFIG } from '../config'
import { getUniqueId, deepCopy } from '../utils'
import selection from '../selection'
import StateRender from '../parser/render'
import enterCtrl from './enterCtrl'
import updateCtrl from './updateCtrl'
import backspaceCtrl from './backspaceCtrl'
import deleteCtrl from './deleteCtrl'
import codeBlockCtrl from './codeBlockCtrl'
import tableBlockCtrl from './tableBlockCtrl'
import tableDragBarCtrl from './tableDragBarCtrl'
import tableSelectCellsCtrl from './tableSelectCellsCtrl'
import coreApi from './core'
import marktextApi from './marktext'
import History from './history'
import arrowCtrl from './arrowCtrl'
import pasteCtrl from './pasteCtrl'
import copyCutCtrl from './copyCutCtrl'
import paragraphCtrl from './paragraphCtrl'
import tabCtrl from './tabCtrl'
import formatCtrl from './formatCtrl'
import searchCtrl from './searchCtrl'
import containerCtrl from './containerCtrl'
import htmlBlockCtrl from './htmlBlock'
import clickCtrl from './clickCtrl'
import inputCtrl from './inputCtrl'
import tocCtrl from './tocCtrl'
import emojiCtrl from './emojiCtrl'
import imageCtrl from './imageCtrl'
import linkCtrl from './linkCtrl'
import dragDropCtrl from './dragDropCtrl'
import footnoteCtrl from './footnoteCtrl'
import importMarkdown from '../utils/importMarkdown'
import Cursor from '../selection/cursor'
import escapeCharactersMap, { escapeCharacters } from '../parser/escapeCharacter'
const prototypes = [
coreApi,
marktextApi,
tabCtrl,
enterCtrl,
updateCtrl,
backspaceCtrl,
deleteCtrl,
codeBlockCtrl,
arrowCtrl,
pasteCtrl,
copyCutCtrl,
tableBlockCtrl,
tableDragBarCtrl,
tableSelectCellsCtrl,
paragraphCtrl,
formatCtrl,
searchCtrl,
containerCtrl,
htmlBlockCtrl,
clickCtrl,
inputCtrl,
tocCtrl,
emojiCtrl,
imageCtrl,
linkCtrl,
dragDropCtrl,
footnoteCtrl,
importMarkdown
]
class ContentState {
constructor (muya, options) {
const { bulletListMarker } = options
this.muya = muya
Object.assign(this, options)
// Use to cache the keys which you don't want to remove.
this.exemption = new Set()
this.blocks = [this.createBlockP()]
this.stateRender = new StateRender(muya)
this.renderRange = [null, null]
this.currentCursor = null
// you'll select the outmost block of current cursor when you click the front icon.
this.selectedBlock = null
this._selectedImage = null
this.dropAnchor = null
this.prevCursor = null
this.historyTimer = null
this.history = new History(this)
this.turndownConfig = Object.assign({}, DEFAULT_TURNDOWN_CONFIG, { bulletListMarker })
// table drag bar
this.dragInfo = null
this.isDragTableBar = false
this.dragEventIds = []
// table cell select
this.cellSelectInfo = null
this._selectedTableCells = null
this.cellSelectEventIds = []
this.init()
}
set selectedTableCells (info) {
const oldSelectedTableCells = this._selectedTableCells
if (!info && !!oldSelectedTableCells) {
const selectedCells = this.muya.container.querySelectorAll('.ag-cell-selected')
for (const cell of Array.from(selectedCells)) {
cell.classList.remove('ag-cell-selected')
cell.classList.remove('ag-cell-border-top')
cell.classList.remove('ag-cell-border-right')
cell.classList.remove('ag-cell-border-bottom')
cell.classList.remove('ag-cell-border-left')
}
}
this._selectedTableCells = info
}
get selectedTableCells () {
return this._selectedTableCells
}
set selectedImage (image) {
const oldSelectedImage = this._selectedImage
// if there is no selected image, remove selected status of current selected image.
if (!image && oldSelectedImage) {
const selectedImages = this.muya.container.querySelectorAll('.ag-inline-image-selected')
for (const img of selectedImages) {
img.classList.remove('ag-inline-image-selected')
}
}
this._selectedImage = image
}
get selectedImage () {
return this._selectedImage
}
set cursor (cursor) {
if (!(cursor instanceof Cursor)) {
cursor = new Cursor(cursor)
}
this.prevCursor = this.currentCursor
this.currentCursor = cursor
const getHistoryState = () => {
const { blocks, renderRange, currentCursor } = this
return {
blocks,
renderRange,
cursor: currentCursor
}
}
if (!cursor.noHistory) {
if (
this.prevCursor &&
(
this.prevCursor.start.key !== cursor.start.key ||
this.prevCursor.end.key !== cursor.end.key
)
) {
// Push history immediately
this.history.push(getHistoryState())
} else {
// WORKAROUND: The current engine doesn't support a smart history and we
// need to store the whole state. Therefore, we push history only when the
// user stops typing. Pushing one pending entry allows us to commit the
// change before an undo action is triggered to partially solve #1321.
if (this.historyTimer) clearTimeout(this.historyTimer)
this.history.pushPending(getHistoryState())
this.historyTimer = setTimeout(() => {
this.history.commitPending()
}, 2000)
}
}
}
get cursor () {
return this.currentCursor
}
init () {
const lastBlock = this.getLastBlock()
const { key, text } = lastBlock
const offset = text.length
this.searchMatches = {
value: '', // the search value
matches: [], // matches
index: -1 // active match
}
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
getHistory () {
const { stack, index } = this.history
return { stack, index }
}
setHistory ({ stack, index }) {
Object.assign(this.history, { stack, index })
}
setCursor () {
selection.setCursorRange(this.cursor)
}
setNextRenderRange () {
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const startOutMostBlock = this.findOutMostBlock(startBlock)
const endOutMostBlock = this.findOutMostBlock(endBlock)
this.renderRange = [startOutMostBlock.preSibling, endOutMostBlock.nextSibling]
}
postRender () {
this.resizeLineNumber()
}
render (isRenderCursor = true, clearCache = false) {
const { blocks, searchMatches: { matches, index } } = this
const activeBlocks = this.getActiveBlocks()
if (clearCache) {
this.stateRender.tokenCache.clear()
}
matches.forEach((m, i) => {
m.active = i === index
})
this.setNextRenderRange()
this.stateRender.collectLabels(blocks)
this.stateRender.render(blocks, activeBlocks, matches)
if (isRenderCursor) {
this.setCursor()
} else {
this.muya.blur()
}
this.postRender()
}
partialRender (isRenderCursor = true) {
const { blocks, searchMatches: { matches, index } } = this
const activeBlocks = this.getActiveBlocks()
const [startKey, endKey] = this.renderRange
matches.forEach((m, i) => {
m.active = i === index
})
// The `endKey` may already be removed from blocks if range was selected via keyboard (GH#1854).
let startIndex = startKey ? blocks.findIndex(block => block.key === startKey) : 0
if (startIndex === -1) {
startIndex = 0
}
let endIndex = blocks.length
if (endKey) {
const tmpEndIndex = blocks.findIndex(block => block.key === endKey)
if (tmpEndIndex >= 0) {
endIndex = tmpEndIndex + 1
}
}
const blocksToRender = blocks.slice(startIndex, endIndex)
this.setNextRenderRange()
this.stateRender.collectLabels(blocks)
this.stateRender.partialRender(blocksToRender, activeBlocks, matches, startKey, endKey)
if (isRenderCursor) {
this.setCursor()
} else {
this.muya.blur()
}
this.postRender()
}
singleRender (block, isRenderCursor = true) {
const { blocks, searchMatches: { matches, index } } = this
const activeBlocks = this.getActiveBlocks()
matches.forEach((m, i) => {
m.active = i === index
})
this.setNextRenderRange()
this.stateRender.collectLabels(blocks)
this.stateRender.singleRender(block, activeBlocks, matches)
if (isRenderCursor) {
this.setCursor()
} else {
this.muya.blur()
}
this.postRender()
}
/**
* A block in MarkText present a paragraph(block syntax in GFM) or a line in paragraph.
* a `span` block must in a `p block` or `pre block` and `p block`'s children must be `span` blocks.
*/
createBlock (type = 'span', extras = {}) {
const key = getUniqueId()
const blockData = {
key,
text: '',
type,
editable: true,
parent: null,
preSibling: null,
nextSibling: null,
children: []
}
// give span block a default functionType `paragraphContent`
if (type === 'span' && !extras.functionType) {
blockData.functionType = 'paragraphContent'
}
if (extras.functionType === 'codeContent' && extras.text) {
const CHAR_REG = new RegExp(`(${escapeCharacters.join('|')})`, 'gi')
extras.text = extras.text.replace(CHAR_REG, (_, p) => {
return escapeCharactersMap[p]
})
}
Object.assign(blockData, extras)
return blockData
}
createBlockP (text = '') {
const pBlock = this.createBlock('p')
const contentBlock = this.createBlock('span', { text })
this.appendChild(pBlock, contentBlock)
return pBlock
}
isCollapse (cursor = this.cursor) {
const { start, end } = cursor
return start.key === end.key && start.offset === end.offset
}
// getBlocks
getBlocks () {
return this.blocks
}
getCursor () {
return this.cursor
}
getBlock (key) {
if (!key) return null
let result = null
const travel = blocks => {
for (const block of blocks) {
if (block.key === key) {
result = block
return
}
const { children } = block
if (children.length) {
travel(children)
}
}
}
travel(this.blocks)
return result
}
copyBlock (origin) {
const copiedBlock = deepCopy(origin)
const travel = (block, parent, preBlock, nextBlock) => {
const key = getUniqueId()
block.key = key
block.parent = parent ? parent.key : null
block.preSibling = preBlock ? preBlock.key : null
block.nextSibling = nextBlock ? nextBlock.key : null
const { children } = block
const len = children.length
if (children && len) {
let i
for (i = 0; i < len; i++) {
const b = children[i]
const preB = i >= 1 ? children[i - 1] : null
const nextB = i < len - 1 ? children[i + 1] : null
travel(b, block, preB, nextB)
}
}
}
travel(copiedBlock, null, null, null)
return copiedBlock
}
getParent (block) {
if (block && block.parent) {
return this.getBlock(block.parent)
}
return null
}
// return block and its parents
getParents (block) {
const result = []
result.push(block)
let parent = this.getParent(block)
while (parent) {
result.push(parent)
parent = this.getParent(parent)
}
return result
}
getPreSibling (block) {
return block.preSibling ? this.getBlock(block.preSibling) : null
}
getNextSibling (block) {
return block.nextSibling ? this.getBlock(block.nextSibling) : null
}
/**
* if target is descendant of parent return true, else return false
* @param {[type]} parent [description]
* @param {[type]} target [description]
* @return {Boolean} [description]
*/
isInclude (parent, target) {
const children = parent.children
if (children.length === 0) {
return false
} else {
if (children.some(child => child.key === target.key)) {
return true
} else {
return children.some(child => this.isInclude(child, target))
}
}
}
removeTextOrBlock (block) {
if (block.functionType === 'languageInput') return
const checkerIn = block => {
if (this.exemption.has(block.key)) {
return true
} else {
const parent = this.getBlock(block.parent)
return parent ? checkerIn(parent) : false
}
}
const checkerOut = block => {
const children = block.children
if (children.length) {
if (children.some(child => this.exemption.has(child.key))) {
return true
} else {
return children.some(child => checkerOut(child))
}
} else {
return false
}
}
if (checkerIn(block) || checkerOut(block)) {
block.text = ''
const { children } = block
if (children.length) {
children.forEach(child => this.removeTextOrBlock(child))
}
} else if (block.editable) {
this.removeBlock(block)
}
}
/**
* remove blocks between before and after, and includes after block.
*/
removeBlocks (before, after, isRemoveAfter = true, isRecursion = false) {
if (!isRecursion) {
if (/td|th/.test(before.type)) {
this.exemption.add(this.closest(before, 'figure'))
}
if (/td|th/.test(after.type)) {
this.exemption.add(this.closest(after, 'figure'))
}
}
let nextSibling = this.getBlock(before.nextSibling)
let beforeEnd = false
while (nextSibling) {
if (nextSibling.key === after.key || this.isInclude(nextSibling, after)) {
beforeEnd = true
break
}
this.removeTextOrBlock(nextSibling)
nextSibling = this.getBlock(nextSibling.nextSibling)
}
if (!beforeEnd) {
const parent = this.getParent(before)
if (parent) {
this.removeBlocks(parent, after, false, true)
}
}
let preSibling = this.getBlock(after.preSibling)
let afterEnd = false
while (preSibling) {
if (preSibling.key === before.key || this.isInclude(preSibling, before)) {
afterEnd = true
break
}
this.removeTextOrBlock(preSibling)
preSibling = this.getBlock(preSibling.preSibling)
}
if (!afterEnd) {
const parent = this.getParent(after)
if (parent) {
const removeAfter = isRemoveAfter && (this.isOnlyRemoveableChild(after))
this.removeBlocks(before, parent, removeAfter, true)
}
}
if (isRemoveAfter) {
this.removeTextOrBlock(after)
}
if (!isRecursion) {
this.exemption.clear()
}
}
removeBlock (block, fromBlocks = this.blocks) {
const remove = (blocks, block) => {
const len = blocks.length
let i
for (i = 0; i < len; i++) {
if (blocks[i].key === block.key) {
const preSibling = this.getBlock(block.preSibling)
const nextSibling = this.getBlock(block.nextSibling)
if (preSibling) {
preSibling.nextSibling = nextSibling ? nextSibling.key : null
}
if (nextSibling) {
nextSibling.preSibling = preSibling ? preSibling.key : null
}
return blocks.splice(i, 1)
} else {
if (blocks[i].children.length) {
remove(blocks[i].children, block)
}
}
}
}
remove(Array.isArray(fromBlocks) ? fromBlocks : fromBlocks.children, block)
}
getActiveBlocks () {
const result = []
let block = this.getBlock(this.cursor.start.key)
if (block) {
result.push(block)
}
while (block && block.parent) {
block = this.getBlock(block.parent)
result.push(block)
}
return result
}
insertAfter (newBlock, oldBlock) {
const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks
const oldNextSibling = this.getBlock(oldBlock.nextSibling)
const index = this.findIndex(siblings, oldBlock)
siblings.splice(index + 1, 0, newBlock)
oldBlock.nextSibling = newBlock.key
newBlock.parent = oldBlock.parent
newBlock.preSibling = oldBlock.key
if (oldNextSibling) {
newBlock.nextSibling = oldNextSibling.key
oldNextSibling.preSibling = newBlock.key
}
}
insertBefore (newBlock, oldBlock) {
const siblings = oldBlock.parent ? this.getBlock(oldBlock.parent).children : this.blocks
const oldPreSibling = this.getBlock(oldBlock.preSibling)
const index = this.findIndex(siblings, oldBlock)
siblings.splice(index, 0, newBlock)
oldBlock.preSibling = newBlock.key
newBlock.parent = oldBlock.parent
newBlock.nextSibling = oldBlock.key
newBlock.preSibling = null
if (oldPreSibling) {
oldPreSibling.nextSibling = newBlock.key
newBlock.preSibling = oldPreSibling.key
}
}
findOutMostBlock (block) {
const parent = this.getBlock(block.parent)
return parent ? this.findOutMostBlock(parent) : block
}
findIndex (children, block) {
return children.findIndex(child => child === block)
}
prependChild (parent, block) {
block.parent = parent.key
block.preSibling = null
if (parent.children.length) {
block.nextSibling = parent.children[0].key
}
parent.children.unshift(block)
}
appendChild (parent, block) {
const len = parent.children.length
const lastChild = parent.children[len - 1]
parent.children.push(block)
block.parent = parent.key
if (lastChild) {
lastChild.nextSibling = block.key
block.preSibling = lastChild.key
} else {
block.preSibling = null
}
block.nextSibling = null
}
replaceBlock (newBlock, oldBlock) {
const blockList = oldBlock.parent ? this.getParent(oldBlock).children : this.blocks
const index = this.findIndex(blockList, oldBlock)
blockList.splice(index, 1, newBlock)
newBlock.parent = oldBlock.parent
newBlock.preSibling = oldBlock.preSibling
newBlock.nextSibling = oldBlock.nextSibling
}
canInserFrontMatter (block) {
if (!block) return true
const parent = this.getParent(block)
return block.type === 'span' &&
!block.preSibling &&
!parent.preSibling &&
!parent.parent
}
isFirstChild (block) {
return !block.preSibling
}
isLastChild (block) {
return !block.nextSibling
}
isOnlyChild (block) {
return !block.nextSibling && !block.preSibling
}
isOnlyRemoveableChild (block) {
if (block.editable === false) return false
const parent = this.getParent(block)
return (parent ? parent.children : this.blocks).filter(child => child.editable && child.functionType !== 'languageInput').length === 1
}
getLastChild (block) {
if (block) {
const len = block.children.length
if (len) {
return block.children[len - 1]
}
}
return null
}
firstInDescendant (block) {
const children = block.children
if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {
return block
} else if (children.length) {
if (
children[0].type === 'input' ||
(children[0].type === 'div' && children[0].editable === false)
) { // handle task item
return this.firstInDescendant(children[1])
} else {
return this.firstInDescendant(children[0])
}
}
}
lastInDescendant (block) {
if (block.children.length === 0 && HAS_TEXT_BLOCK_REG.test(block.type)) {
return block
} else if (block.children.length) {
const children = block.children
let lastChild = children[children.length - 1]
while (lastChild.editable === false) {
lastChild = this.getPreSibling(lastChild)
}
return this.lastInDescendant(lastChild)
}
}
findPreBlockInLocation (block) {
const parent = this.getParent(block)
const preBlock = this.getPreSibling(block)
if (
block.preSibling &&
preBlock.type !== 'input' &&
preBlock.type !== 'div' &&
preBlock.editable !== false
) { // handle task item and table
return this.lastInDescendant(preBlock)
} else if (parent) {
return this.findPreBlockInLocation(parent)
} else {
return null
}
}
findNextBlockInLocation (block) {
const parent = this.getParent(block)
const nextBlock = this.getNextSibling(block)
if (
nextBlock && nextBlock.editable !== false
) {
return this.firstInDescendant(nextBlock)
} else if (parent) {
return this.findNextBlockInLocation(parent)
} else {
return null
}
}
getPositionReference () {
const { fontSize, lineHeight } = this.muya.options
const { start } = this.cursor
const block = this.getBlock(start.key)
const { x, y, width } = selection.getCursorCoords()
const height = fontSize * lineHeight
const bottom = y + height
const right = x + width
const left = x
const top = y
return {
getBoundingClientRect () {
return { x, y, top, left, right, bottom, height, width }
},
clientWidth: width,
clientHeight: height,
id: block ? block.key : null
}
}
getFirstBlock () {
return this.firstInDescendant(this.blocks[0])
}
getLastBlock () {
const { blocks } = this
const len = blocks.length
return this.lastInDescendant(blocks[len - 1])
}
closest (block, type) {
if (!block) {
return null
}
if (type instanceof RegExp ? type.test(block.type) : block.type === type) {
return block
} else {
const parent = this.getParent(block)
return this.closest(parent, type)
}
}
getAnchor (block) {
const { type, functionType } = block
if (type !== 'span') {
return null
}
if (functionType === 'codeContent' || functionType === 'cellContent') {
return this.closest(block, 'figure') || this.closest(block, 'pre')
} else {
return this.getParent(block)
}
}
clear () {
this.history.clearHistory()
}
}
prototypes.forEach(ctrl => ctrl(ContentState))
export default ContentState
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/clickCtrl.js | src/muya/lib/contentState/clickCtrl.js | import selection from '../selection'
import { isMuyaEditorElement } from '../selection/dom'
import { HAS_TEXT_BLOCK_REG, CLASS_OR_ID } from '../config'
import { getParentCheckBox } from '../utils/getParentCheckBox'
import { cumputeCheckboxStatus } from '../utils/cumputeCheckBoxStatus'
const clickCtrl = ContentState => {
ContentState.prototype.clickHandler = function (event) {
const { eventCenter } = this.muya
const { target } = event
if (isMuyaEditorElement(target)) {
const lastBlock = this.getLastBlock()
const archor = this.findOutMostBlock(lastBlock)
const archorParagraph = document.querySelector(`#${archor.key}`)
if (archorParagraph === null) {
return
}
const rect = archorParagraph.getBoundingClientRect()
// If click below the last paragraph
// and the last paragraph is not empty, create a new empty paragraph
if (event.clientY > rect.top + rect.height) {
let needToInsertNewParagraph = false
if (lastBlock.type === 'span') {
if (/atxLine|paragraphContent/.test(lastBlock.functionType) && /\S/.test(lastBlock.text)) {
needToInsertNewParagraph = true
}
if (!/atxLine|paragraphContent/.test(lastBlock.functionType)) {
needToInsertNewParagraph = true
}
} else {
needToInsertNewParagraph = true
}
if (needToInsertNewParagraph) {
event.preventDefault()
const paragraphBlock = this.createBlockP()
this.insertAfter(paragraphBlock, archor)
const key = paragraphBlock.children[0].key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.render()
}
}
}
// handle front menu click
const { start: oldStart, end: oldEnd } = this.cursor
if (oldStart && oldEnd) {
let hasSameParent = false
const startBlock = this.getBlock(oldStart.key)
const endBlock = this.getBlock(oldEnd.key)
if (startBlock && endBlock) {
const startOutBlock = this.findOutMostBlock(startBlock)
const endOutBlock = this.findOutMostBlock(endBlock)
hasSameParent = startOutBlock === endOutBlock
}
// show the muya-front-menu only when the cursor in the same paragraph
if (target.closest('.ag-front-icon') && hasSameParent) {
const currentBlock = this.findOutMostBlock(startBlock)
const frontIcon = target.closest('.ag-front-icon')
const rect = frontIcon.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
return rect
},
clientWidth: rect.width,
clientHeight: rect.height,
id: currentBlock.key
}
this.selectedBlock = currentBlock
eventCenter.dispatch('muya-front-menu', { reference, outmostBlock: currentBlock, startBlock, endBlock })
return this.partialRender()
}
}
const { start, end } = selection.getCursorRange()
// fix #625, the selection maybe not in edit area.
if (!start || !end) {
return
}
// format-click
const node = selection.getSelectionStart()
const inlineNode = node ? node.closest('.ag-inline-rule') : null
// link-format-click
let parentNode = inlineNode
while (parentNode !== null && parentNode.classList.contains(CLASS_OR_ID.AG_INLINE_RULE)) {
if (parentNode.tagName === 'A') {
const formatType = 'link' // auto link or []() link
const data = {
text: inlineNode.textContent,
href: parentNode.getAttribute('href') || ''
}
eventCenter.dispatch('format-click', {
event,
formatType,
data
})
break
} else {
parentNode = parentNode.parentNode
}
}
if (inlineNode) {
let formatType = null
let data = null
switch (inlineNode.tagName) {
case 'SPAN': {
if (inlineNode.hasAttribute('data-emoji')) {
formatType = 'emoji'
data = inlineNode.getAttribute('data-emoji')
} else if (inlineNode.classList.contains('ag-math-text')) {
formatType = 'inline_math'
data = inlineNode.textContent
}
break
}
case 'STRONG': {
formatType = 'strong'
data = inlineNode.textContent
break
}
case 'EM': {
formatType = 'em'
data = inlineNode.textContent
break
}
case 'DEL': {
formatType = 'del'
data = inlineNode.textContent
break
}
case 'CODE': {
formatType = 'inline_code'
data = inlineNode.textContent
break
}
}
if (formatType) {
eventCenter.dispatch('format-click', {
event,
formatType,
data
})
}
}
const block = this.getBlock(start.key)
let needRender = false
// is show format float box?
if (
start.key === end.key &&
start.offset !== end.offset &&
HAS_TEXT_BLOCK_REG.test(block.type) &&
block.functionType !== 'codeContent' &&
block.functionType !== 'languageInput'
) {
const reference = this.getPositionReference()
const { formats } = this.selectionFormats()
eventCenter.dispatch('muya-format-picker', { reference, formats })
}
// update '```xxx' to code block when you click other place or use press arrow key.
if (block && start.key !== this.cursor.start.key) {
const oldBlock = this.getBlock(this.cursor.start.key)
if (oldBlock) {
needRender = needRender || this.codeBlockUpdate(oldBlock)
}
}
// change active status when paragraph changed
if (
start.key !== this.cursor.start.key ||
end.key !== this.cursor.end.key
) {
needRender = true
}
const needMarkedUpdate = this.checkNeedRender(this.cursor) || this.checkNeedRender({ start, end })
if (needRender) {
this.cursor = { start, end }
return this.partialRender()
} else if (needMarkedUpdate) {
// Fix: whole select can not be canceled #613
requestAnimationFrame(() => {
const cursor = selection.getCursorRange()
if (!cursor.start || !cursor.end) {
return
}
this.cursor = cursor
return this.partialRender()
})
} else {
this.cursor = { start, end }
}
}
ContentState.prototype.setCheckBoxState = function (checkbox, checked) {
checkbox.checked = checked
const block = this.getBlock(checkbox.id)
block.checked = checked
checkbox.classList.toggle(CLASS_OR_ID.AG_CHECKBOX_CHECKED)
}
ContentState.prototype.updateParentsCheckBoxState = function (checkbox) {
let parent = getParentCheckBox(checkbox)
while (parent !== null) {
const checked = cumputeCheckboxStatus(parent)
if (parent.checked !== checked) {
this.setCheckBoxState(parent, checked)
parent = getParentCheckBox(parent)
} else {
break
}
}
}
ContentState.prototype.updateChildrenCheckBoxState = function (checkbox, checked) {
const checkboxes = checkbox.parentElement.querySelectorAll(`input ~ ul .${CLASS_OR_ID.AG_TASK_LIST_ITEM_CHECKBOX}`)
const len = checkboxes.length
for (let i = 0; i < len; i++) {
const checkbox = checkboxes[i]
if (checkbox.checked !== checked) {
this.setCheckBoxState(checkbox, checked)
}
}
}
// handle task list item checkbox click
ContentState.prototype.listItemCheckBoxClick = function (checkbox) {
const { checked } = checkbox
this.setCheckBoxState(checkbox, checked)
// A task checked, then related task should be update
const { autoCheck } = this.muya.options
if (autoCheck) {
this.updateChildrenCheckBoxState(checkbox, checked)
this.updateParentsCheckBoxState(checkbox)
}
const block = this.getBlock(checkbox.id)
const parentBlock = this.getParent(block)
const firstEditableBlock = this.firstInDescendant(parentBlock)
const { key } = firstEditableBlock
const offset = 0
this.cursor = { start: { key, offset }, end: { key, offset } }
return this.partialRender()
}
}
export default clickCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/backspaceCtrl.js | src/muya/lib/contentState/backspaceCtrl.js | import selection from '../selection'
import { findNearestParagraph, findOutMostParagraph } from '../selection/dom'
import { tokenizer, generator } from '../parser/'
import { getImageInfo } from '../utils/getImageInfo'
const backspaceCtrl = ContentState => {
ContentState.prototype.checkBackspaceCase = function () {
const node = selection.getSelectionStart()
const paragraph = findNearestParagraph(node)
const outMostParagraph = findOutMostParagraph(node)
let block = this.getBlock(paragraph.id)
if (block.type === 'span' && block.preSibling) {
return false
}
if (block.type === 'span') {
block = this.getParent(block)
}
const preBlock = this.getPreSibling(block)
const outBlock = this.findOutMostBlock(block)
const parent = this.getParent(block)
const { left: outLeft } = selection.getCaretOffsets(outMostParagraph)
const { left: inLeft } = selection.getCaretOffsets(paragraph)
if (
(parent && parent.type === 'li' && inLeft === 0 && this.isFirstChild(block)) ||
(parent && parent.type === 'li' && inLeft === 0 && parent.listItemType === 'task' && preBlock.type === 'input') // handle task item
) {
if (this.isOnlyChild(parent)) {
/**
* <ul>
* <li>
* <p>|text</p>
* <p>maybe has other paragraph</p>
* </li>
* <ul>
* ===>
* <p>|text</p>
* <p>maybe has other paragraph</p>
*/
return { type: 'LI', info: 'REPLACEMENT' }
} else if (this.isFirstChild(parent)) {
/**
* <ul>
* <li>
* <p>|text</p>
* <p>maybe has other paragraph</p>
* </li>
* <li>
* <p>other list item</p>
* </li>
* <ul>
* ===>
* <p>|text</p>
* <p>maybe has other paragraph</p>
* <ul>
* <li>
* <p>other list item</p>
* </li>
* <ul>
*/
return { type: 'LI', info: 'REMOVE_INSERT_BEFORE' }
} else {
/**
* <ul>
* <li>
* <p>other list item</p>
* </li>
* <li>
* <p>|text</p>
* <p>maybe has other paragraph</p>
* </li>
* <li>
* <p>other list item</p>
* </li>
* <ul>
* ===>
* <ul>
* <li>
* <p>other list item</p>
* <p>|text</p>
* <p>maybe has other paragraph</p>
* </li>
* <li>
* <p>other list item</p>
* </li>
* <ul>
*/
return { type: 'LI', info: 'INSERT_PRE_LIST_ITEM' }
}
}
if (parent && parent.type === 'blockquote' && inLeft === 0) {
if (this.isOnlyChild(block)) {
return { type: 'BLOCKQUOTE', info: 'REPLACEMENT' }
} else if (this.isFirstChild(block)) {
return { type: 'BLOCKQUOTE', info: 'INSERT_BEFORE' }
}
}
if (!outBlock.preSibling && outLeft === 0) {
return { type: 'STOP' }
}
}
ContentState.prototype.docBackspaceHandler = function (event) {
// handle delete selected image
if (this.selectedImage) {
event.preventDefault()
return this.deleteImage(this.selectedImage)
}
if (this.selectedTableCells) {
event.preventDefault()
return this.deleteSelectedTableCells()
}
}
ContentState.prototype.backspaceHandler = function (event) {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
// handle delete selected image
if (this.selectedImage) {
event.preventDefault()
return this.deleteImage(this.selectedImage)
}
// Handle select all content.
if (this.isSelectAll()) {
event.preventDefault()
this.blocks = [this.createBlockP()]
this.init()
this.render()
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
return this.muya.dispatchChange()
}
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const maybeLastRow = this.getParent(endBlock)
const startOutmostBlock = this.findOutMostBlock(startBlock)
const endOutmostBlock = this.findOutMostBlock(endBlock)
// Just for fix delete the last `#` or all the atx heading cause error @fixme
if (
start.key === end.key &&
startBlock.type === 'span' &&
startBlock.functionType === 'atxLine'
) {
if (
start.offset === 0 && end.offset === startBlock.text.length ||
start.offset === end.offset && start.offset === 1 && startBlock.text === '#'
) {
event.preventDefault()
startBlock.text = ''
this.cursor = {
start: { key: start.key, offset: 0 },
end: { key: end.key, offset: 0 }
}
this.updateToParagraph(this.getParent(startBlock), startBlock)
return this.partialRender()
}
}
// fix: #897
const { text } = startBlock
const tokens = tokenizer(text, {
options: this.muya.options
})
let needRender = false
let preToken = null
for (const token of tokens) {
// handle delete the second $ in inline_math.
if (
token.range.end === start.offset &&
token.type === 'inline_math'
) {
needRender = true
token.raw = token.raw.substr(0, token.raw.length - 1)
break
}
// handle pre token is a <ruby> html tag, need preventdefault.
if (
token.range.start + 1 === start.offset &&
preToken &&
preToken.type === 'html_tag' &&
preToken.tag === 'ruby'
) {
needRender = true
token.raw = token.raw.substr(1)
break
}
preToken = token
}
if (needRender) {
startBlock.text = generator(tokens)
event.preventDefault()
start.offset--
end.offset--
this.cursor = {
start,
end
}
return this.partialRender()
}
// fix bug when the first block is table, these two ways will cause bugs.
// 1. one paragraph bollow table, selectAll, press backspace.
// 2. select table from the first cell to the last cell, press backsapce.
const maybeCell = this.getParent(startBlock)
if (/th/.test(maybeCell.type) && start.offset === 0 && !maybeCell.preSibling) {
if (
end.offset === endBlock.text.length &&
startOutmostBlock === endOutmostBlock &&
!endBlock.nextSibling && !maybeLastRow.nextSibling ||
startOutmostBlock !== endOutmostBlock
) {
event.preventDefault()
// need remove the figure block.
const figureBlock = this.getBlock(this.closest(startBlock, 'figure'))
// if table is the only block, need create a p block.
const p = this.createBlockP(endBlock.text.substring(end.offset))
this.insertBefore(p, figureBlock)
const cursorBlock = p.children[0]
if (startOutmostBlock !== endOutmostBlock) {
this.removeBlocks(figureBlock, endBlock)
}
this.removeBlock(figureBlock)
const { key } = cursorBlock
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.render()
}
}
// Fixed #1456 existed bugs `Select one cell and press backspace will cause bug`
if (
startBlock.functionType === 'cellContent' &&
this.cursor.start.offset === 0 &&
this.cursor.end.offset !== 0 &&
this.cursor.end.offset === startBlock.text.length
) {
event.preventDefault()
event.stopPropagation()
startBlock.text = ''
const { key } = startBlock
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.singleRender(startBlock)
}
// Fix: https://github.com/marktext/marktext/issues/2013
// Also fix the codeblock crashed when the code content is '\n' and press backspace.
if (
startBlock.functionType === 'codeContent' &&
startBlock.key === endBlock.key &&
this.cursor.start.offset === this.cursor.end.offset &&
(/\n.$/.test(startBlock.text) || startBlock.text === '\n') &&
startBlock.text.length === this.cursor.start.offset
) {
event.preventDefault()
event.stopPropagation()
startBlock.text = /\n.$/.test(startBlock.text) ? startBlock.text.replace(/.$/, '') : ''
const { key } = startBlock
const offset = startBlock.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.singleRender(startBlock)
}
// If select multiple paragraph or multiple characters in one paragraph, just let
// inputCtrl to handle this case.
if (start.key !== end.key || start.offset !== end.offset) {
return
}
const node = selection.getSelectionStart()
const parentNode = node && node.nodeType === 1 ? node.parentNode : null
const paragraph = findNearestParagraph(node)
const id = paragraph.id
let block = this.getBlock(id)
let parent = this.getBlock(block.parent)
const preBlock = this.findPreBlockInLocation(block)
const { left, right } = selection.getCaretOffsets(paragraph)
const inlineDegrade = this.checkBackspaceCase()
// Handle backspace when the previous is an inline image.
if (parentNode && parentNode.classList.contains('ag-inline-image')) {
if (selection.getCaretOffsets(node).left === 0) {
event.preventDefault()
event.stopPropagation()
const imageInfo = getImageInfo(parentNode)
return this.deleteImage(imageInfo)
}
if (selection.getCaretOffsets(node).left === 1 && right === 0) {
event.stopPropagation()
event.preventDefault()
const key = startBlock.key
const text = startBlock.text
startBlock.text = text.substring(0, start.offset - 1) + text.substring(start.offset)
const offset = start.offset - 1
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.singleRender(startBlock)
}
}
// handle backspace when cursor at the end of inline image.
if (node.classList.contains('ag-image-container')) {
const imageWrapper = node.parentNode
const imageInfo = getImageInfo(imageWrapper)
if (start.offset === imageInfo.token.range.end) {
event.preventDefault()
event.stopPropagation()
return this.selectImage(imageInfo)
}
}
// Fix issue #1218
if (startBlock.functionType === 'cellContent' && /<br\/>.{1}$/.test(startBlock.text)) {
event.preventDefault()
event.stopPropagation()
const { text } = startBlock
startBlock.text = text.substring(0, text.length - 1)
const key = startBlock.key
const offset = startBlock.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.singleRender(startBlock)
}
// Fix delete the last character in table cell, the default action will delete the cell content if not preventDefault.
if (startBlock.functionType === 'cellContent' && left === 1 && right === 0) {
event.stopPropagation()
event.preventDefault()
startBlock.text = ''
const { key } = startBlock
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.singleRender(startBlock)
}
const tableHasContent = table => {
const tHead = table.children[0]
const tBody = table.children[1]
const tHeadHasContent = tHead.children[0].children.some(th => th.children[0].text.trim())
const tBodyHasContent = tBody.children.some(row => row.children.some(td => td.children[0].text.trim()))
return tHeadHasContent || tBodyHasContent
}
if (
block.type === 'span' &&
block.functionType === 'paragraphContent' &&
left === 0 &&
preBlock &&
preBlock.functionType === 'footnoteInput'
) {
event.preventDefault()
event.stopPropagation()
if (!parent.nextSibling) {
const pBlock = this.createBlockP(block.text)
const figureBlock = this.closest(block, 'figure')
this.insertBefore(pBlock, figureBlock)
this.removeBlock(figureBlock)
const key = pBlock.children[0].key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
}
} else if (
block.type === 'span' &&
block.functionType === 'codeContent' &&
left === 0 &&
!block.preSibling
) {
event.preventDefault()
event.stopPropagation()
if (
!block.nextSibling
) {
const preBlock = this.getParent(parent)
const pBlock = this.createBlock('p')
const lineBlock = this.createBlock('span', { text: block.text })
const key = lineBlock.key
const offset = 0
this.appendChild(pBlock, lineBlock)
let referenceBlock = null
switch (preBlock.functionType) {
case 'fencecode':
case 'indentcode':
case 'frontmatter':
referenceBlock = preBlock
break
case 'multiplemath':
case 'flowchart':
case 'mermaid':
case 'sequence':
case 'plantuml':
case 'vega-lite':
case 'html':
referenceBlock = this.getParent(preBlock)
break
}
this.insertBefore(pBlock, referenceBlock)
this.removeBlock(referenceBlock)
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
}
} else if (left === 0 && block.functionType === 'cellContent') {
event.preventDefault()
event.stopPropagation()
const table = this.closest(block, 'table')
const figure = this.closest(table, 'figure')
const hasContent = tableHasContent(table)
let key
let offset
if ((!preBlock || preBlock.functionType !== 'cellContent') && !hasContent) {
const paragraphContent = this.createBlock('span')
delete figure.functionType
figure.children = []
this.appendChild(figure, paragraphContent)
figure.text = ''
figure.type = 'p'
key = paragraphContent.key
offset = 0
} else if (preBlock) {
key = preBlock.key
offset = preBlock.text.length
}
if (key !== undefined && offset !== undefined) {
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
}
} else if (inlineDegrade) {
event.preventDefault()
if (block.type === 'span') {
block = this.getParent(block)
parent = this.getParent(parent)
}
switch (inlineDegrade.type) {
case 'STOP': // Cursor at begin of article and nothing need to do
break
case 'LI': {
if (inlineDegrade.info === 'REPLACEMENT') {
const children = parent.children
const grandpa = this.getBlock(parent.parent)
if (children[0].type === 'input') {
this.removeBlock(children[0])
}
children.forEach(child => {
this.insertBefore(child, grandpa)
})
this.removeBlock(grandpa)
} else if (inlineDegrade.info === 'REMOVE_INSERT_BEFORE') {
const children = parent.children
const grandpa = this.getBlock(parent.parent)
if (children[0].type === 'input') {
this.removeBlock(children[0])
}
children.forEach(child => {
this.insertBefore(child, grandpa)
})
this.removeBlock(parent)
} else if (inlineDegrade.info === 'INSERT_PRE_LIST_ITEM') {
const parPre = this.getBlock(parent.preSibling)
const children = parent.children
if (children[0].type === 'input') {
this.removeBlock(children[0])
}
children.forEach(child => {
this.appendChild(parPre, child)
})
this.removeBlock(parent)
}
break
}
case 'BLOCKQUOTE':
if (inlineDegrade.info === 'REPLACEMENT') {
this.insertBefore(block, parent)
this.removeBlock(parent)
} else if (inlineDegrade.info === 'INSERT_BEFORE') {
this.removeBlock(block)
this.insertBefore(block, parent)
}
break
}
const key = block.type === 'p' ? block.children[0].key : block.key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
if (inlineDegrade.type !== 'STOP') {
this.partialRender()
}
} else if (left === 0 && preBlock) {
event.preventDefault()
const { text } = block
const key = preBlock.key
const offset = preBlock.text.length
preBlock.text += text
// If block is a line block and its parent paragraph only has one text line,
// also need to remove the paragrah
if (this.isOnlyChild(block) && block.type === 'span') {
this.removeBlock(parent)
} else if (block.functionType !== 'languageInput' && block.functionType !== 'footnoteInput') {
this.removeBlock(block)
}
this.cursor = {
start: { key, offset },
end: { key, offset }
}
let needRenderAll = false
if (this.isCollapse() && preBlock.type === 'span' && preBlock.functionType === 'paragraphContent') {
this.checkInlineUpdate(preBlock)
needRenderAll = true
}
needRenderAll ? this.render() : this.partialRender()
}
}
}
export default backspaceCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/arrowCtrl.js | src/muya/lib/contentState/arrowCtrl.js | import { EVENT_KEYS, CLASS_OR_ID } from '../config'
import { findNearestParagraph } from '../selection/dom'
import selection from '../selection'
// If the next block is header, put cursor after the `#{1,6} *`
const adjustOffset = (offset, block, event) => {
if (/^span$/.test(block.type) && block.functionType === 'atxLine' && event.key === EVENT_KEYS.ArrowDown) {
const match = /^\s{0,3}(?:#{1,6})(?:\s{1,}|$)/.exec(block.text)
if (match) {
return match[0].length
}
}
return offset
}
const arrowCtrl = ContentState => {
ContentState.prototype.findNextRowCell = function (cell) {
if (cell.functionType !== 'cellContent') {
throw new Error(`block with type ${cell && cell.type} is not a table cell`)
}
const thOrTd = this.getParent(cell)
const row = this.closest(cell, 'tr')
const rowContainer = this.closest(row, /thead|tbody/) // thead or tbody
const column = row.children.indexOf(thOrTd)
if (rowContainer.type === 'thead') {
const tbody = this.getNextSibling(rowContainer)
if (tbody && tbody.children.length) {
return tbody.children[0].children[column].children[0]
}
} else if (rowContainer.type === 'tbody') {
const nextRow = this.getNextSibling(row)
if (nextRow) {
return nextRow.children[column].children[0]
}
}
return null
}
ContentState.prototype.findPrevRowCell = function (cell) {
if (cell.functionType !== 'cellContent') {
throw new Error(`block with type ${cell && cell.type} is not a table cell`)
}
const thOrTd = this.getParent(cell)
const row = this.closest(cell, 'tr')
const rowContainer = this.getParent(row) // thead or tbody
const rowIndex = rowContainer.children.indexOf(row)
const column = row.children.indexOf(thOrTd)
if (rowContainer.type === 'tbody') {
if (rowIndex === 0 && rowContainer.preSibling) {
const thead = this.getPreSibling(rowContainer)
return thead.children[0].children[column].children[0]
} else if (rowIndex > 0) {
return this.getPreSibling(row).children[column].children[0]
}
return null
}
return null
}
ContentState.prototype.docArrowHandler = function (event) {
const { selectedImage } = this
if (selectedImage) {
const { key, token } = selectedImage
const { start, end } = token.range
event.preventDefault()
event.stopPropagation()
const block = this.getBlock(key)
switch (event.key) {
case EVENT_KEYS.ArrowUp:
case EVENT_KEYS.ArrowLeft: {
this.cursor = {
start: { key, offset: start },
end: { key, offset: start }
}
break
}
case EVENT_KEYS.ArrowDown:
case EVENT_KEYS.ArrowRight: {
this.cursor = {
start: { key, offset: end },
end: { key, offset: end }
}
break
}
}
this.muya.keyboard.hideAllFloatTools()
return this.singleRender(block)
}
}
ContentState.prototype.arrowHandler = function (event) {
const node = selection.getSelectionStart()
const paragraph = findNearestParagraph(node)
const id = paragraph.id
const block = this.getBlock(id)
const preBlock = this.findPreBlockInLocation(block)
const nextBlock = this.findNextBlockInLocation(block)
const { start, end } = selection.getCursorRange()
const { topOffset, bottomOffset } = selection.getCursorYOffset(paragraph)
if (!start || !end) {
return
}
// fix #101
if (event.key === EVENT_KEYS.ArrowRight && node && node.classList && node.classList.contains(CLASS_OR_ID.AG_MATH_TEXT)) {
const { right } = selection.getCaretOffsets(node)
if (right === 0 && start.key === end.key && start.offset === end.offset) {
// It's not recommended to use such lower API, but it's work well.
return selection.select(node.parentNode.nextElementSibling, 0)
}
}
// Just do nothing if the cursor is not collapsed or `shiftKey` pressed
if (
(start.key === end.key && start.offset !== end.offset) ||
start.key !== end.key || event.shiftKey
) {
return
}
if (
(event.key === EVENT_KEYS.ArrowUp && topOffset > 0) ||
(event.key === EVENT_KEYS.ArrowDown && bottomOffset > 0)
) {
if (!/pre/.test(block.type) || block.functionType !== 'cellContent') {
return
}
}
if (block.functionType === 'cellContent') {
let activeBlock
const cellInNextRow = this.findNextRowCell(block)
const cellInPrevRow = this.findPrevRowCell(block)
if (event.key === EVENT_KEYS.ArrowUp) {
if (cellInPrevRow) {
activeBlock = cellInPrevRow
} else {
activeBlock = this.findPreBlockInLocation(this.getTableBlock())
}
}
if (event.key === EVENT_KEYS.ArrowDown) {
if (cellInNextRow) {
activeBlock = cellInNextRow
} else {
activeBlock = this.findNextBlockInLocation(this.getTableBlock())
}
}
if (activeBlock) {
event.preventDefault()
event.stopPropagation()
let offset = activeBlock.type === 'p'
? 0
: (event.key === EVENT_KEYS.ArrowUp
? activeBlock.text.length
: 0)
offset = adjustOffset(offset, activeBlock, event)
const key = activeBlock.type === 'p'
? activeBlock.children[0].key
: activeBlock.key
this.cursor = {
start: {
key,
offset
},
end: {
key,
offset
}
}
return this.partialRender()
}
}
if (
(event.key === EVENT_KEYS.ArrowUp) ||
(event.key === EVENT_KEYS.ArrowLeft && start.offset === 0)
) {
event.preventDefault()
event.stopPropagation()
if (!preBlock) return
const key = preBlock.key
const offset = preBlock.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
} else if (
(event.key === EVENT_KEYS.ArrowDown) ||
(event.key === EVENT_KEYS.ArrowRight && start.offset === block.text.length)
) {
event.preventDefault()
event.stopPropagation()
let key
let newBlock
if (nextBlock) {
key = nextBlock.key
} else {
newBlock = this.createBlockP()
const lastBlock = this.blocks[this.blocks.length - 1]
this.insertAfter(newBlock, lastBlock)
key = newBlock.children[0].key
}
const offset = adjustOffset(0, nextBlock || newBlock, event)
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
}
}
export default arrowCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/htmlBlock.js | src/muya/lib/contentState/htmlBlock.js | import { VOID_HTML_TAGS, HTML_TAGS } from '../config'
import { inlineRules } from '../parser/rules'
const HTML_BLOCK_REG = /^<([a-zA-Z\d-]+)(?=\s|>)[^<>]*?>$/
const htmlBlock = ContentState => {
ContentState.prototype.createHtmlBlock = function (code) {
const block = this.createBlock('figure')
block.functionType = 'html'
const { preBlock, preview } = this.createPreAndPreview('html', code)
this.appendChild(block, preBlock)
this.appendChild(block, preview)
return block
}
ContentState.prototype.initHtmlBlock = function (block) {
let htmlContent = ''
const text = block.children[0].text
const matches = inlineRules.html_tag.exec(text)
if (matches) {
const tag = matches[3]
const content = matches[4] || ''
const openTag = matches[2]
const closeTag = matches[5]
const isVoidTag = VOID_HTML_TAGS.indexOf(tag) > -1
if (closeTag) {
htmlContent = text
} else if (isVoidTag) {
htmlContent = text
if (content) {
// TODO: @jocs notice user that the html is not valid.
console.warn('Invalid html content.')
}
} else {
htmlContent = `${openTag}\n${content}\n</${tag}>`
}
} else {
htmlContent = `<div>\n${text}\n</div>`
}
block.type = 'figure'
block.functionType = 'html'
block.text = htmlContent
block.children = []
const { preBlock, preview } = this.createPreAndPreview('html', htmlContent)
this.appendChild(block, preBlock)
this.appendChild(block, preview)
return preBlock // preBlock
}
ContentState.prototype.updateHtmlBlock = function (block) {
const { type } = block
if (type !== 'li' && type !== 'p') return false
const { text } = block.children[0]
const match = HTML_BLOCK_REG.exec(text)
const tagName = match && match[1] && HTML_TAGS.find(t => t === match[1])
return VOID_HTML_TAGS.indexOf(tagName) === -1 && tagName ? this.initHtmlBlock(block) : false
}
}
export default htmlBlock
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/emojiCtrl.js | src/muya/lib/contentState/emojiCtrl.js | import { tokenizer, generator } from '../parser/'
const emojiCtrl = ContentState => {
ContentState.prototype.setEmoji = function (item) {
let { key, offset } = this.cursor.start
const startBlock = this.getBlock(key)
const { text } = startBlock
const tokens = tokenizer(text, {
options: this.muya.options
})
let delta = 0
const findEmojiToken = (tokens, offset) => {
for (const token of tokens) {
const { start, end } = token.range
if (offset >= start && offset <= end) {
delta = end - offset
return token.children && Array.isArray(token.children) && token.children.length
? findEmojiToken(token.children, offset)
: token
}
}
}
const token = findEmojiToken(tokens, offset)
if (token && token.type === 'emoji') {
const emojiText = item.aliases[0]
offset += delta + emojiText.length - token.content.length
token.content = emojiText
token.raw = `:${emojiText}:`
startBlock.text = generator(tokens)
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
}
}
export default emojiCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/tableBlockCtrl.js | src/muya/lib/contentState/tableBlockCtrl.js | import { isLengthEven, getParagraphReference } from '../utils'
const TABLE_BLOCK_REG = /^\|.*?(\\*)\|.*?(\\*)\|/
const tableBlockCtrl = ContentState => {
ContentState.prototype.createTableInFigure = function ({ rows, columns }, tableContents = []) {
const table = this.createBlock('table', {
row: rows - 1, // zero base
column: columns - 1
})
const tHead = this.createBlock('thead')
const tBody = this.createBlock('tbody')
let i
let j
for (i = 0; i < rows; i++) {
const rowBlock = this.createBlock('tr')
i === 0 ? this.appendChild(tHead, rowBlock) : this.appendChild(tBody, rowBlock)
const rowContents = tableContents[i]
for (j = 0; j < columns; j++) {
const cell = this.createBlock(i === 0 ? 'th' : 'td', {
align: rowContents ? rowContents[j].align : '',
column: j
})
const cellContent = this.createBlock('span', {
text: rowContents ? rowContents[j].text : '',
functionType: 'cellContent'
})
this.appendChild(cell, cellContent)
this.appendChild(rowBlock, cell)
}
}
this.appendChild(table, tHead)
if (tBody.children.length) {
this.appendChild(table, tBody)
}
return table
}
ContentState.prototype.createFigure = function ({ rows, columns }) {
const { end } = this.cursor
const table = this.createTableInFigure({ rows, columns })
const figureBlock = this.createBlock('figure', {
functionType: 'table'
})
const endBlock = this.getBlock(end.key)
const anchor = this.getAnchor(endBlock)
if (!anchor) {
return
}
this.insertAfter(figureBlock, anchor)
if (/p|h\d/.test(anchor.type) && !endBlock.text) {
this.removeBlock(anchor)
}
this.appendChild(figureBlock, table)
const { key } = this.firstInDescendant(table) // fist cell key in thead
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
}
ContentState.prototype.createTable = function (tableChecker) {
this.createFigure(tableChecker)
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
this.muya.dispatchChange()
}
ContentState.prototype.initTable = function (block) {
const { text } = block.children[0]
const rowHeader = []
const len = text.length
let i
for (i = 0; i < len; i++) {
const char = text[i]
if (/^[^|]$/.test(char)) {
rowHeader[rowHeader.length - 1] += char
}
if (/\\/.test(char)) {
rowHeader[rowHeader.length - 1] += text[++i]
}
if (/\|/.test(char) && i !== len - 1) {
rowHeader.push('')
}
}
const columns = rowHeader.length
const rows = 2
const table = this.createTableInFigure({ rows, columns }, [rowHeader.map(text => ({ text, align: '' }))])
block.type = 'figure'
block.text = ''
block.children = []
block.functionType = 'table'
this.appendChild(block, table)
return this.firstInDescendant(table.children[1]) // first cell content in tbody
}
ContentState.prototype.tableToolBarClick = function (type) {
const { start: { key } } = this.cursor
const block = this.getBlock(key)
const parentBlock = this.getParent(block)
if (block.functionType !== 'cellContent') {
throw new Error('table is not active')
}
const { column, align } = parentBlock
const table = this.closest(block, 'table')
const figure = this.getBlock(table.parent)
switch (type) {
case 'left':
case 'center':
case 'right': {
const newAlign = align === type ? '' : type
table.children.forEach(rowContainer => {
rowContainer.children.forEach(row => {
row.children[column].align = newAlign
})
})
this.muya.eventCenter.dispatch('stateChange')
this.partialRender()
break
}
case 'delete': {
const newLine = this.createBlock('span')
figure.children = []
this.appendChild(figure, newLine)
figure.type = 'p'
figure.text = ''
const key = newLine.key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.muya.eventCenter.dispatch('stateChange')
this.partialRender()
break
}
case 'table': {
const { eventCenter } = this.muya
const figureKey = figure.key
const tableEle = document.querySelector(`#${figureKey} [data-label=table]`)
const { row = 1, column = 1 } = table // zero base
const handler = (row, column) => {
const { row: oldRow, column: oldColumn } = table
let tBody = table.children[1]
const tHead = table.children[0]
const headerRow = tHead.children[0]
const bodyRows = tBody ? tBody.children : []
let i
if (column > oldColumn) {
for (i = oldColumn + 1; i <= column; i++) {
const th = this.createBlock('th', {
column: i,
align: ''
})
const thContent = this.createBlock('span', {
functionType: 'cellContent'
})
this.appendChild(th, thContent)
this.appendChild(headerRow, th)
bodyRows.forEach(bodyRow => {
const td = this.createBlock('td', {
column: i,
align: ''
})
const tdContent = this.createBlock('span', {
functionType: 'cellContent'
})
this.appendChild(td, tdContent)
this.appendChild(bodyRow, td)
})
}
} else if (column < oldColumn) {
const rows = [headerRow, ...bodyRows]
rows.forEach(row => {
while (row.children.length > column + 1) {
const lastChild = row.children[row.children.length - 1]
this.removeBlock(lastChild)
}
})
}
if (row < oldRow) {
while (tBody.children.length > row) {
const lastRow = tBody.children[tBody.children.length - 1]
this.removeBlock(lastRow)
}
if (tBody.children.length === 0) {
this.removeBlock(tBody)
}
} else if (row > oldRow) {
if (!tBody) {
tBody = this.createBlock('tbody')
this.appendChild(table, tBody)
}
const oneHeaderRow = tHead.children[0]
for (i = oldRow + 1; i <= row; i++) {
const bodyRow = this.createRow(oneHeaderRow, false)
this.appendChild(tBody, bodyRow)
}
}
Object.assign(table, { row, column })
const cursorBlock = this.firstInDescendant(headerRow)
const key = cursorBlock.key
const offset = cursorBlock.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.muya.eventCenter.dispatch('stateChange')
this.partialRender()
}
const reference = getParagraphReference(tableEle, tableEle.id)
eventCenter.dispatch('muya-table-picker', { row, column }, reference, handler.bind(this))
}
}
}
// insert/remove row/column
ContentState.prototype.editTable = function ({ location, action, target }, cellContentKey) {
let block
let start
let end
if (cellContentKey) {
block = this.getBlock(cellContentKey)
} else {
({ start, end } = this.cursor)
if (start.key !== end.key) {
throw new Error('Cursor is not in one block, can not editTable')
}
block = this.getBlock(start.key)
}
if (block.functionType !== 'cellContent') {
throw new Error('Cursor is not in table block, so you can not insert/edit row/column')
}
const cellBlock = this.getParent(block)
const currentRow = this.getParent(cellBlock)
const table = this.closest(block, 'table')
const thead = table.children[0]
const tbody = table.children[1]
const columnIndex = currentRow.children.indexOf(cellBlock)
// const rowIndex = rowContainer.type === 'thead' ? 0 : tbody.children.indexOf(currentRow) + 1
let cursorBlock
if (target === 'row') {
if (action === 'insert') {
const newRow = (location === 'previous' && cellBlock.type === 'th')
? this.createRow(currentRow, true)
: this.createRow(currentRow, false)
if (location === 'previous') {
this.insertBefore(newRow, currentRow)
if (cellBlock.type === 'th') {
this.removeBlock(currentRow)
currentRow.children.forEach(cell => (cell.type = 'td'))
const firstRow = tbody.children[0]
this.insertBefore(currentRow, firstRow)
}
} else {
if (cellBlock.type === 'th') {
const firstRow = tbody.children[0]
this.insertBefore(newRow, firstRow)
} else {
this.insertAfter(newRow, currentRow)
}
}
cursorBlock = newRow.children[columnIndex].children[0]
// handle remove row
} else {
if (location === 'previous') {
if (cellBlock.type === 'th') return
if (!currentRow.preSibling) {
const headRow = thead.children[0]
if (!currentRow.nextSibling) return
this.removeBlock(headRow)
this.removeBlock(currentRow)
currentRow.children.forEach(cell => (cell.type = 'th'))
this.appendChild(thead, currentRow)
} else {
const preRow = this.getPreSibling(currentRow)
this.removeBlock(preRow)
}
} else if (location === 'current') {
if (cellBlock.type === 'th' && tbody.children.length >= 2) {
const firstRow = tbody.children[0]
this.removeBlock(currentRow)
this.removeBlock(firstRow)
this.appendChild(thead, firstRow)
firstRow.children.forEach(cell => (cell.type = 'th'))
cursorBlock = firstRow.children[columnIndex].children[0]
}
if (cellBlock.type === 'td' && (currentRow.preSibling || currentRow.nextSibling)) {
cursorBlock = (this.getNextSibling(currentRow) || this.getPreSibling(currentRow)).children[columnIndex].children[0]
this.removeBlock(currentRow)
}
} else {
if (cellBlock.type === 'th') {
if (tbody.children.length >= 2) {
const firstRow = tbody.children[0]
this.removeBlock(firstRow)
} else {
return
}
} else {
const nextRow = this.getNextSibling(currentRow)
if (nextRow) {
this.removeBlock(nextRow)
}
}
}
}
} else if (target === 'column') {
if (action === 'insert') {
[...thead.children, ...tbody.children].forEach(tableRow => {
const targetCell = tableRow.children[columnIndex]
const cell = this.createBlock(targetCell.type, {
align: ''
})
const cellContent = this.createBlock('span', {
functionType: 'cellContent'
})
this.appendChild(cell, cellContent)
if (location === 'left') {
this.insertBefore(cell, targetCell)
} else {
this.insertAfter(cell, targetCell)
}
tableRow.children.forEach((cell, i) => {
cell.column = i
})
})
cursorBlock = location === 'left' ? this.getPreSibling(cellBlock).children[0] : this.getNextSibling(cellBlock).children[0]
// handle remove column
} else {
if (currentRow.children.length <= 2) return
[...thead.children, ...tbody.children].forEach(tableRow => {
const targetCell = tableRow.children[columnIndex]
const removeCell = location === 'left'
? this.getPreSibling(targetCell)
: (location === 'current' ? targetCell : this.getNextSibling(targetCell))
if (removeCell === cellBlock) {
cursorBlock = this.findNextBlockInLocation(block)
}
if (removeCell) this.removeBlock(removeCell)
tableRow.children.forEach((cell, i) => {
cell.column = i
})
})
}
}
const newColum = thead.children[0].children.length - 1
const newRow = thead.children.length + tbody.children.length - 1
Object.assign(table, { row: newRow, column: newColum })
if (cursorBlock) {
const { key } = cursorBlock
const offset = 0
this.cursor = { start: { key, offset }, end: { key, offset } }
} else {
this.cursor = { start, end }
}
this.partialRender()
this.muya.eventCenter.dispatch('stateChange')
}
ContentState.prototype.getTableBlock = function () {
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const startParents = this.getParents(startBlock)
const endParents = this.getParents(endBlock)
const affiliation = startParents
.filter(p => endParents.includes(p))
if (affiliation.length) {
const figure = affiliation.find(p => p.type === 'figure')
return figure
}
}
ContentState.prototype.tableBlockUpdate = function (block) {
const { type } = block
if (type !== 'p') return false
const { text } = block.children[0]
const match = TABLE_BLOCK_REG.exec(text)
return (match && isLengthEven(match[1]) && isLengthEven(match[2])) ? this.initTable(block) : false
}
}
export default tableBlockCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/pasteCtrl.js | src/muya/lib/contentState/pasteCtrl.js |
import { PARAGRAPH_TYPES, PREVIEW_DOMPURIFY_CONFIG, HAS_TEXT_BLOCK_REG, IMAGE_EXT_REG, URL_REG } from '../config'
import { sanitize, getUniqueId, getImageInfo as getImageSrc, getPageTitle } from '../utils'
import { getImageInfo } from '../utils/getImageInfo'
const LIST_REG = /ul|ol/
const LINE_BREAKS_REG = /\n/
const pasteCtrl = ContentState => {
// check paste type: `MERGE` or `NEWLINE`
ContentState.prototype.checkPasteType = function (start, fragment) {
const fragmentType = fragment.type
const parent = this.getParent(start)
if (fragmentType === 'p') {
return 'MERGE'
} else if (/^h\d/.test(fragmentType)) {
if (start.text) {
return 'MERGE'
} else {
return 'NEWLINE'
}
} else if (LIST_REG.test(fragmentType)) {
const listItem = this.getParent(parent)
const list = listItem && listItem.type === 'li' ? this.getParent(listItem) : null
if (list) {
if (
list.listType === fragment.listType &&
listItem.bulletMarkerOrDelimiter === fragment.children[0].bulletMarkerOrDelimiter
) {
return 'MERGE'
} else {
return 'NEWLINE'
}
} else {
return 'NEWLINE'
}
} else {
return 'NEWLINE'
}
}
// Try to identify the data type.
ContentState.prototype.checkCopyType = function (html, rawText) {
let type = 'normal'
if (!html && rawText) {
type = 'copyAsMarkdown'
const match = /^<([a-zA-Z\d-]+)(?=\s|>).*?>[\s\S]+?<\/([a-zA-Z\d-]+)>$/.exec(rawText.trim())
if (match && match[1]) {
const tag = match[1]
if (tag === 'table' && match.length === 3 && match[2] === 'table') {
// Try to import a single table
const tmp = document.createElement('table')
tmp.innerHTML = sanitize(rawText, PREVIEW_DOMPURIFY_CONFIG, false)
if (tmp.childElementCount === 1) {
return 'htmlToMd'
}
}
// TODO: We could try to import HTML elements such as headings, text and lists to markdown for better UX.
type = PARAGRAPH_TYPES.find(type => type === tag) ? 'copyAsHtml' : type
}
}
return type
}
ContentState.prototype.standardizeHTML = async function (rawHtml) {
// Only extract the `body.innerHTML` when the `html` is a full HTML Document.
if (/<body>[\s\S]*<\/body>/.test(rawHtml)) {
const match = /<body>([\s\S]*)<\/body>/.exec(rawHtml)
if (match && typeof match[1] === 'string') {
rawHtml = match[1]
}
}
// Prevent XSS and sanitize HTML.
const sanitizedHtml = sanitize(rawHtml, PREVIEW_DOMPURIFY_CONFIG, false)
const tempWrapper = document.createElement('div')
tempWrapper.innerHTML = sanitizedHtml
// Special process for turndown.js, needed for Number app on macOS.
const tables = Array.from(tempWrapper.querySelectorAll('table'))
for (const table of tables) {
const row = table.querySelector('tr')
if (row.firstElementChild.tagName !== 'TH') {
[...row.children].forEach(cell => {
const th = document.createElement('th')
th.innerHTML = cell.innerHTML
cell.replaceWith(th)
})
}
const paragraphs = Array.from(table.querySelectorAll('p'))
for (const p of paragraphs) {
const span = document.createElement('span')
span.innerHTML = p.innerHTML
p.replaceWith(span)
}
const tds = table.querySelectorAll('td')
for (const td of tds) {
const tableDataHtml = td.innerHTML
if (/<br>/.test(tableDataHtml)) {
td.innerHTML = tableDataHtml.replace(/<br>/g, '<br>')
}
}
}
// Prevent it parse into a link if copy a url.
const links = Array.from(tempWrapper.querySelectorAll('a'))
for (const link of links) {
const href = link.getAttribute('href')
const text = link.textContent
if (URL_REG.test(href) && href === text) {
const title = await getPageTitle(href)
if (title) {
link.innerHTML = sanitize(title, PREVIEW_DOMPURIFY_CONFIG, true)
} else {
const span = document.createElement('span')
span.innerHTML = text
link.replaceWith(span)
}
}
}
return tempWrapper.innerHTML
}
ContentState.prototype.pasteImage = async function (event) {
// Try to guess the clipboard file path.
const imagePath = this.muya.options.clipboardFilePath()
if (imagePath && typeof imagePath === 'string' && IMAGE_EXT_REG.test(imagePath)) {
const id = `loading-${getUniqueId()}`
if (this.selectedImage) {
this.replaceImage(this.selectedImage, {
alt: id,
src: imagePath
})
} else {
this.insertImage({
alt: id,
src: imagePath
})
}
let newSrc = null
try {
newSrc = await this.muya.options.imageAction(imagePath, id)
} catch (error) {
// TODO: Notify user about an error.
console.error('Unexpected error on image action:', error)
return null
}
const { src } = getImageSrc(imagePath)
if (src) {
this.stateRender.urlMap.set(newSrc, src)
}
const imageWrapper = this.muya.container.querySelector(`span[data-id=${id}]`)
if (imageWrapper) {
const imageInfo = getImageInfo(imageWrapper)
this.replaceImage(imageInfo, {
src: newSrc
})
}
return imagePath
}
const items = event.clipboardData && event.clipboardData.items
let file = null
if (items && items.length) {
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile()
break
}
}
}
// handle paste to create inline image
if (file) {
const id = `loading-${getUniqueId()}`
if (this.selectedImage) {
this.replaceImage(this.selectedImage, {
alt: id,
src: ''
})
} else {
this.insertImage({
alt: id,
src: ''
})
}
const reader = new FileReader()
reader.onload = event => {
const base64 = event.target.result
const imageWrapper = this.muya.container.querySelector(`span[data-id=${id}]`)
const imageContainer = this.muya.container.querySelector(`span[data-id=${id}] .ag-image-container`)
this.stateRender.urlMap.set(id, base64)
if (imageContainer) {
imageWrapper.classList.remove('ag-empty-image')
imageWrapper.classList.add('ag-image-success')
const image = document.createElement('img')
image.src = base64
imageContainer.appendChild(image)
}
}
reader.readAsDataURL(file)
let newSrc = null
try {
newSrc = await this.muya.options.imageAction(file, id)
} catch (error) {
// TODO: Notify user about an error.
console.error('Unexpected error on image action:', error)
return null
}
const base64 = this.stateRender.urlMap.get(id)
if (base64) {
this.stateRender.urlMap.set(newSrc, base64)
this.stateRender.urlMap.delete(id)
}
const imageWrapper = this.muya.container.querySelector(`span[data-id=${id}]`)
if (imageWrapper) {
const imageInfo = getImageInfo(imageWrapper)
this.replaceImage(imageInfo, {
src: newSrc
})
}
return file
}
return null
}
// Handle global events.
ContentState.prototype.docPasteHandler = async function (event) {
// TODO: Pasting into CodeMirror will not work for special data like images
// or tables (HTML) because it's not handled.
const file = await this.pasteImage(event)
if (file) {
return event.preventDefault()
}
if (this.selectedTableCells) {
const { start } = this.cursor
const startBlock = this.getBlock(start.key)
const { selectedTableCells: stc } = this
// Exactly one table cell is selected. Replace the cells text via default handler.
if (startBlock && startBlock.functionType === 'cellContent' && stc.row === 1 && stc.column === 1) {
this.pasteHandler(event)
return event.preventDefault()
}
}
}
// Handle `normal` and `pasteAsPlainText` paste for preview mode.
ContentState.prototype.pasteHandler = async function (event, type = 'normal', rawText, rawHtml) {
event.preventDefault()
event.stopPropagation()
const text = rawText || event.clipboardData.getData('text/plain')
let html = rawHtml || event.clipboardData.getData('text/html')
// Support pasted URLs from Firefox.
if (URL_REG.test(text) && !/\s/.test(text) && !html) {
html = `<a href="${text}">${text}</a>`
}
// Remove crap from HTML such as meta data and styles and sanitize HTML,
// but `text` may still contain dangerous HTML.
html = await this.standardizeHTML(html)
let copyType = this.checkCopyType(html, text)
const { start, end } = this.cursor
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
const parent = this.getParent(startBlock)
if (copyType === 'htmlToMd') {
html = sanitize(text, PREVIEW_DOMPURIFY_CONFIG, false)
copyType = 'normal'
}
if (start.key !== end.key) {
this.cutHandler()
return this.pasteHandler(event, type, rawText, rawHtml)
}
// NOTE: We should parse HTML if we can and use it instead the image (see GH#1271).
if (!html) {
const file = await this.pasteImage(event)
if (file) {
return
}
}
const appendHtml = (text) => {
startBlock.text = startBlock.text.substring(0, start.offset) + text + startBlock.text.substring(start.offset)
const { key } = start
const offset = start.offset + text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
}
// Prepare paste
if (startBlock.type === 'span' && startBlock.functionType === 'languageInput') {
// Extract the first line from the language identifier (GH#553)
let language = text.trim().match(/^.*$/m)[0] || ''
const oldLanguageLength = startBlock.text.length
let offset = 0
if (start.offset !== 0 || end.offset !== oldLanguageLength) {
const prePartText = startBlock.text.substring(0, start.offset)
const postPartText = startBlock.text.substring(end.offset)
// Expect that the language doesn't contain new lines
language = prePartText + language + postPartText
offset = prePartText.length + language.length
} else {
offset = language.length
}
startBlock.text = language
const key = startBlock.key
this.cursor = {
start: { key, offset },
end: { key, offset }
}
// Hide code picker float box
const { eventCenter } = this.muya
eventCenter.dispatch('muya-code-picker', { reference: null })
// Update code block language and render
this.updateCodeLanguage(startBlock, language)
return
}
if (startBlock.type === 'span' && startBlock.functionType === 'codeContent') {
const blockText = startBlock.text
const prePartText = blockText.substring(0, start.offset)
const postPartText = blockText.substring(end.offset)
startBlock.text = prePartText + text + postPartText
const { key } = startBlock
const offset = start.offset + text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
if (startBlock.functionType === 'cellContent') {
let isOneCellSelected = false
if (this.selectedTableCells) {
const { selectedTableCells: stc } = this
// Replace cells text when one cell is selected.
if (stc.row === 1 && stc.column === 1) {
isOneCellSelected = true
} else {
// Cancel event, multiple cells are selected.
return this.partialRender()
}
}
const { key } = startBlock
const pendingText = text.trim().replace(/\n/g, '<br/>')
let offset = pendingText.length
if (isOneCellSelected) {
// Replace text and deselect cell.
startBlock.text = pendingText
this.selectedTableCells = null
} else {
offset += start.offset
startBlock.text = startBlock.text.substring(0, start.offset) + pendingText + startBlock.text.substring(end.offset)
}
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
// Handle paste event and transform data into internal block structure.
if (copyType === 'copyAsHtml') {
switch (type) {
case 'normal': {
const htmlBlock = this.createBlockP(text.trim())
this.insertAfter(htmlBlock, parent)
this.removeBlock(parent)
// handler heading
this.insertHtmlBlock(htmlBlock)
break
}
case 'pasteAsPlainText': {
const lines = text.trim().split(LINE_BREAKS_REG)
let htmlBlock = null
if (!startBlock.text || lines.length > 1) {
htmlBlock = this.createBlockP((startBlock.text ? lines.slice(1) : lines).join('\n'))
}
if (htmlBlock) {
this.insertAfter(htmlBlock, parent)
this.insertHtmlBlock(htmlBlock)
}
if (startBlock.text) {
appendHtml(lines[0])
} else {
this.removeBlock(parent)
}
break
}
}
return this.partialRender()
}
const stateFragments = type === 'pasteAsPlainText' || copyType === 'copyAsMarkdown'
? this.markdownToState(text)
: this.html2State(html)
if (stateFragments.length <= 0) {
return
}
// Step 1: if select content, cut the content, and chop the block text into two part by the cursor.
const cacheText = endBlock.text.substring(end.offset)
startBlock.text = startBlock.text.substring(0, start.offset)
// Step 2: when insert the fragments, check begin a new block, or insert into pre block.
const firstFragment = stateFragments[0]
const tailFragments = stateFragments.slice(1)
const pasteType = this.checkPasteType(startBlock, firstFragment)
const getLastBlock = blocks => {
const len = blocks.length
const lastBlock = blocks[len - 1]
if (lastBlock.children.length === 0 && HAS_TEXT_BLOCK_REG.test(lastBlock.type)) {
return lastBlock
} else {
if (lastBlock.editable === false) {
return getLastBlock(blocks[len - 2].children)
} else {
return getLastBlock(lastBlock.children)
}
}
}
const lastBlock = getLastBlock(stateFragments)
let key = lastBlock.key
let offset = lastBlock.text.length
lastBlock.text += cacheText
switch (pasteType) {
case 'MERGE': {
if (LIST_REG.test(firstFragment.type)) {
const listItems = firstFragment.children
const firstListItem = listItems[0]
const liChildren = firstListItem.children
const originListItem = this.getParent(parent)
const originList = this.getParent(originListItem)
const targetListType = firstFragment.children[0].isLooseListItem
const originListType = originList.children[0].isLooseListItem
// No matter copy loose list to tight list or vice versa, the result is one loose list.
if (targetListType !== originListType) {
if (!targetListType) {
firstFragment.children.forEach(item => (item.isLooseListItem = true))
} else {
originList.children.forEach(item => (item.isLooseListItem = true))
}
}
if (liChildren[0].type === 'p') {
// TODO @JOCS
startBlock.text += liChildren[0].children[0].text
const tail = liChildren.slice(1)
if (tail.length) {
tail.forEach(t => {
this.appendChild(originListItem, t)
})
}
const firstFragmentTail = listItems.slice(1)
if (firstFragmentTail.length) {
firstFragmentTail.forEach(t => {
this.appendChild(originList, t)
})
}
} else {
listItems.forEach(c => {
this.appendChild(originList, c)
})
}
let target = originList
tailFragments.forEach(block => {
this.insertAfter(block, target)
target = block
})
} else if (firstFragment.type === 'p' || /^h\d/.test(firstFragment.type)) {
const text = firstFragment.children[0].text
const lines = text.split('\n')
let target = parent
if (parent.headingStyle === 'atx') {
startBlock.text += lines[0]
if (lines.length > 1) {
const pBlock = this.createBlockP(lines.slice(1).join('\n'))
this.insertAfter(parent, pBlock)
target = pBlock
}
} else {
startBlock.text += text
}
tailFragments.forEach(block => {
this.insertAfter(block, target)
target = block
})
}
break
}
case 'NEWLINE': {
let target = parent
stateFragments.forEach(block => {
this.insertAfter(block, target)
target = block
})
if (startBlock.text.length === 0) {
this.removeBlock(parent)
}
break
}
default: {
throw new Error('unknown paste type')
}
}
// Step 3: set cursor and render
let cursorBlock = this.getBlock(key)
if (!cursorBlock) {
key = startBlock.key
offset = startBlock.text.length - cacheText.length
cursorBlock = startBlock
}
this.cursor = {
start: {
key, offset
},
end: {
key, offset
}
}
this.checkInlineUpdate(cursorBlock)
this.partialRender()
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
return this.muya.dispatchChange()
}
}
export default pasteCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/deleteCtrl.js | src/muya/lib/contentState/deleteCtrl.js | import selection from '../selection'
const deleteCtrl = ContentState => {
// Handle `delete` keydown event on document.
ContentState.prototype.docDeleteHandler = function (event) {
// handle delete selected image
const { selectedImage } = this
if (selectedImage) {
event.preventDefault()
this.selectedImage = null
return this.deleteImage(selectedImage)
}
if (this.selectedTableCells) {
event.preventDefault()
return this.deleteSelectedTableCells()
}
}
ContentState.prototype.deleteHandler = function (event) {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
const startBlock = this.getBlock(start.key)
const nextBlock = this.findNextBlockInLocation(startBlock)
// TODO: @jocs It will delete all the editor and cause error in console when there is only one empty table. same as #67
if (startBlock.type === 'figure') event.preventDefault()
// If select multiple paragraph or multiple characters in one paragraph, just let
// updateCtrl to handle this case.
if (start.key !== end.key || start.offset !== end.offset) {
return
}
// Only handle h1~h6 span block
const { type, text, key } = startBlock
if (/span/.test(type) && start.offset === 0 && text[1] === '\n') {
event.preventDefault()
startBlock.text = text.substring(2)
this.cursor = {
start: { key, offset: 0 },
end: { key, offset: 0 }
}
return this.singleRender(startBlock)
}
if (
/h\d|span/.test(type) &&
start.offset === text.length
) {
event.preventDefault()
if (nextBlock && /h\d|span/.test(nextBlock.type)) {
// if cursor at the end of code block-language input, do nothing!
if (nextBlock.functionType === 'codeContent' && startBlock.functionType === 'languageInput') {
return
}
startBlock.text += nextBlock.text
const toBeRemoved = [nextBlock]
let parent = this.getParent(nextBlock)
let target = nextBlock
while (this.isOnlyRemoveableChild(target)) {
toBeRemoved.push(parent)
target = parent
parent = this.getParent(parent)
}
toBeRemoved.forEach(b => this.removeBlock(b))
const offset = start.offset
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.render()
}
}
}
}
export default deleteCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/copyCutCtrl.js | src/muya/lib/contentState/copyCutCtrl.js | import selection from '../selection'
import { CLASS_OR_ID } from '../config'
import { escapeHTML } from '../utils'
import { getSanitizeHtml } from '../utils/exportHtml'
import ExportMarkdown from '../utils/exportMarkdown'
import marked from '../parser/marked'
const copyCutCtrl = ContentState => {
ContentState.prototype.docCutHandler = function (event) {
const { selectedTableCells } = this
if (selectedTableCells) {
event.preventDefault()
return this.deleteSelectedTableCells(true)
}
}
ContentState.prototype.cutHandler = function () {
if (this.selectedTableCells) {
return
}
const { selectedImage } = this
if (selectedImage) {
const { key, token } = selectedImage
this.deleteImage({
key,
token
})
this.selectedImage = null
return
}
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
const startBlock = this.getBlock(start.key)
const endBlock = this.getBlock(end.key)
startBlock.text = startBlock.text.substring(0, start.offset) + endBlock.text.substring(end.offset)
if (start.key !== end.key) {
this.removeBlocks(startBlock, endBlock)
}
this.cursor = {
start,
end: start
}
this.checkInlineUpdate(startBlock)
this.partialRender()
}
ContentState.prototype.getClipBoardData = function () {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return { html: '', text: '' }
}
if (start.key === end.key) {
const startBlock = this.getBlock(start.key)
const { type, text, functionType } = startBlock
// Fix issue #942
if (type === 'span' && functionType === 'codeContent') {
const selectedText = text.substring(start.offset, end.offset)
return {
html: marked(selectedText, this.muya.options),
text: selectedText
}
}
}
const html = selection.getSelectionHtml()
const wrapper = document.createElement('div')
wrapper.innerHTML = html
const removedElements = wrapper.querySelectorAll(
`.${CLASS_OR_ID.AG_TOOL_BAR},
.${CLASS_OR_ID.AG_MATH_RENDER},
.${CLASS_OR_ID.AG_RUBY_RENDER},
.${CLASS_OR_ID.AG_HTML_PREVIEW},
.${CLASS_OR_ID.AG_MATH_PREVIEW},
.${CLASS_OR_ID.AG_COPY_REMOVE},
.${CLASS_OR_ID.AG_LANGUAGE_INPUT},
.${CLASS_OR_ID.AG_HTML_TAG} br,
.${CLASS_OR_ID.AG_FRONT_ICON}`
)
for (const e of removedElements) {
e.remove()
}
// Fix #1678 copy task list, and the first list item is not task list item.
const taskListItems = wrapper.querySelectorAll('li.ag-task-list-item')
for (const item of taskListItems) {
const firstChild = item.firstElementChild
if (firstChild && firstChild.nodeName !== 'INPUT') {
const originItem = document.querySelector(`#${item.id}`)
let checked = false
if (originItem && originItem.firstElementChild && originItem.firstElementChild.nodeName === 'INPUT') {
checked = originItem.firstElementChild.checked
}
const input = document.createElement('input')
input.setAttribute('type', 'checkbox')
if (checked) {
input.setAttribute('checked', true)
}
item.insertBefore(input, firstChild)
}
}
const images = wrapper.querySelectorAll('span.ag-inline-image img')
for (const image of images) {
const src = image.getAttribute('src')
let originSrc = null
for (const [sSrc, tSrc] of this.stateRender.urlMap.entries()) {
if (tSrc === src) {
originSrc = sSrc
break
}
}
if (originSrc) {
image.setAttribute('src', originSrc)
}
}
const hrs = wrapper.querySelectorAll('[data-role=hr]')
for (const hr of hrs) {
hr.replaceWith(document.createElement('hr'))
}
const headers = wrapper.querySelectorAll('[data-head]')
for (const header of headers) {
const p = document.createElement('p')
p.textContent = header.textContent
header.replaceWith(p)
}
// replace inline rule element: code, a, strong, em, del, auto_link to span element
// in order to escape turndown translation
const inlineRuleElements = wrapper.querySelectorAll(
`a.${CLASS_OR_ID.AG_INLINE_RULE},
code.${CLASS_OR_ID.AG_INLINE_RULE},
strong.${CLASS_OR_ID.AG_INLINE_RULE},
em.${CLASS_OR_ID.AG_INLINE_RULE},
del.${CLASS_OR_ID.AG_INLINE_RULE}`
)
for (const e of inlineRuleElements) {
const span = document.createElement('span')
span.textContent = e.textContent
e.replaceWith(span)
}
const aLinks = wrapper.querySelectorAll(`.${CLASS_OR_ID.AG_A_LINK}`)
for (const l of aLinks) {
const span = document.createElement('span')
span.innerHTML = l.innerHTML
l.replaceWith(span)
}
const codefense = wrapper.querySelectorAll('pre[data-role$=\'code\']')
for (const cf of codefense) {
const id = cf.id
const block = this.getBlock(id)
const language = block.lang || ''
const codeContent = cf.querySelector('.ag-code-content')
const value = escapeHTML(codeContent.textContent)
cf.innerHTML = `<code class="language-${language}">${value}</code>`
}
const tightListItem = wrapper.querySelectorAll('.ag-tight-list-item')
for (const li of tightListItem) {
for (const item of li.childNodes) {
if (item.tagName === 'P' && item.childElementCount === 1 && item.classList.contains('ag-paragraph')) {
li.replaceChild(item.firstElementChild, item)
}
}
}
const htmlBlock = wrapper.querySelectorAll('figure[data-role=\'HTML\']')
for (const hb of htmlBlock) {
const codeContent = hb.querySelector('.ag-code-content')
const pre = document.createElement('pre')
pre.textContent = codeContent.textContent
hb.replaceWith(pre)
}
// Just work for turndown, turndown will add `leading` and `traling` space in line-break.
const lineBreaks = wrapper.querySelectorAll('span.ag-soft-line-break, span.ag-hard-line-break')
for (const b of lineBreaks) {
b.innerHTML = ''
}
const mathBlock = wrapper.querySelectorAll('figure.ag-container-block')
for (const mb of mathBlock) {
const preElement = mb.querySelector('pre[data-role]')
const functionType = preElement.getAttribute('data-role')
const codeContent = mb.querySelector('.ag-code-content')
const value = codeContent.textContent
let pre
switch (functionType) {
case 'multiplemath':
pre = document.createElement('pre')
pre.classList.add('multiple-math')
pre.textContent = value
mb.replaceWith(pre)
break
case 'mermaid':
case 'flowchart':
case 'sequence':
case 'plantuml':
case 'vega-lite':
pre = document.createElement('pre')
pre.innerHTML = `<code class="language-${functionType}">${value}</code>`
mb.replaceWith(pre)
break
}
}
let htmlData = wrapper.innerHTML
const textData = this.htmlToMarkdown(htmlData)
htmlData = marked(textData)
return { html: htmlData, text: textData }
}
ContentState.prototype.docCopyHandler = function (event) {
const { selectedTableCells } = this
if (selectedTableCells) {
event.preventDefault()
const { row, column, cells } = selectedTableCells
const tableContents = []
let i
let j
for (i = 0; i < row; i++) {
const rowWrapper = []
for (j = 0; j < column; j++) {
const cell = cells[i * column + j]
rowWrapper.push({
text: cell.text,
align: cell.align
})
}
tableContents.push(rowWrapper)
}
if (row === 1 && column === 1) {
// Copy cells text if only one is selected
if (tableContents[0][0].text.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', tableContents[0][0].text)
}
} else {
// Copy as markdown table
const figureBlock = this.createBlock('figure', {
functionType: 'table'
})
const table = this.createTableInFigure({ rows: row, columns: column }, tableContents)
this.appendChild(figureBlock, table)
const { isGitlabCompatibilityEnabled, listIndentation } = this
const markdown = new ExportMarkdown([figureBlock], listIndentation, isGitlabCompatibilityEnabled).generate()
if (markdown.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', markdown)
}
}
}
}
ContentState.prototype.copyHandler = function (event, type, copyInfo = null) {
if (this.selectedTableCells) {
// Hand over to docCopyHandler
return
}
event.preventDefault()
const { selectedImage } = this
if (selectedImage) {
const { token } = selectedImage
if (token.raw.length > 0) {
event.clipboardData.setData('text/html', token.raw)
event.clipboardData.setData('text/plain', token.raw)
}
return
}
const { html, text } = this.getClipBoardData()
switch (type) {
case 'normal': {
if (text.length > 0) {
event.clipboardData.setData('text/html', html)
event.clipboardData.setData('text/plain', text)
}
break
}
case 'copyAsMarkdown': {
if (text.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', text)
}
break
}
case 'copyAsHtml': {
if (text.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', getSanitizeHtml(text, {
superSubScript: this.muya.options.superSubScript,
footnote: this.muya.options.footnote,
isGitlabCompatibilityEnabled: this.muya.options.isGitlabCompatibilityEnabled
}))
}
break
}
case 'copyBlock': {
const block = typeof copyInfo === 'string' ? this.getBlock(copyInfo) : copyInfo
if (!block) return
const anchor = this.getAnchor(block)
const { isGitlabCompatibilityEnabled, listIndentation } = this
const markdown = new ExportMarkdown([anchor], listIndentation, isGitlabCompatibilityEnabled).generate()
if (markdown.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', markdown)
}
break
}
case 'copyCodeContent': {
const codeContent = copyInfo
if (typeof codeContent !== 'string') {
return
}
if (codeContent.length > 0) {
event.clipboardData.setData('text/html', '')
event.clipboardData.setData('text/plain', codeContent)
}
}
}
}
}
export default copyCutCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/tableDragBarCtrl.js | src/muya/lib/contentState/tableDragBarCtrl.js | const calculateAspects = (tableId, barType) => {
const table = document.querySelector(`#${tableId}`)
if (barType === 'bottom') {
const firstRow = table.querySelector('tr')
return Array.from(firstRow.children).map(cell => cell.clientWidth)
} else {
return Array.from(table.querySelectorAll('tr')).map(row => row.clientHeight)
}
}
export const getAllTableCells = tableId => {
const table = document.querySelector(`#${tableId}`)
const rows = table.querySelectorAll('tr')
const cells = []
for (const row of Array.from(rows)) {
cells.push(Array.from(row.children))
}
return cells
}
export const getIndex = (barType, cell) => {
if (cell.tagName === 'SPAN') {
cell = cell.parentNode
}
const row = cell.parentNode
if (barType === 'bottom') {
return Array.from(row.children).indexOf(cell)
} else {
const rowContainer = row.parentNode
if (rowContainer.tagName === 'THEAD') {
return 0
} else {
return Array.from(rowContainer.children).indexOf(row) + 1
}
}
}
const getDragCells = (tableId, barType, index) => {
const table = document.querySelector(`#${tableId}`)
const dragCells = []
if (barType === 'left') {
if (index === 0) {
dragCells.push(...table.querySelectorAll('th'))
} else {
const row = table.querySelector('tbody').children[index - 1]
dragCells.push(...row.children)
}
} else {
const rows = Array.from(table.querySelectorAll('tr'))
const len = rows.length
let i
for (i = 0; i < len; i++) {
dragCells.push(rows[i].children[index])
}
}
return dragCells
}
const tableDragBarCtrl = ContentState => {
ContentState.prototype.handleMouseDown = function (event) {
event.preventDefault()
const { eventCenter } = this.muya
const { clientX, clientY, target } = event
const tableId = target.closest('table').id
const barType = target.classList.contains('left') ? 'left' : 'bottom'
const index = getIndex(barType, target)
const aspects = calculateAspects(tableId, barType)
this.dragInfo = {
tableId,
clientX,
clientY,
barType,
index,
curIndex: index,
dragCells: getDragCells(tableId, barType, index),
cells: getAllTableCells(tableId),
aspects,
offset: 0
}
for (const row of this.dragInfo.cells) {
for (const cell of row) {
if (!this.dragInfo.dragCells.includes(cell)) {
cell.classList.add('ag-cell-transform')
}
}
}
const mouseMoveId = eventCenter.attachDOMEvent(document, 'mousemove', this.handleMouseMove.bind(this))
const mouseUpId = eventCenter.attachDOMEvent(document, 'mouseup', this.handleMouseUp.bind(this))
this.dragEventIds.push(mouseMoveId, mouseUpId)
}
ContentState.prototype.handleMouseMove = function (event) {
if (!this.dragInfo) {
return
}
const { barType } = this.dragInfo
const attrName = barType === 'bottom' ? 'clientX' : 'clientY'
const offset = this.dragInfo.offset = event[attrName] - this.dragInfo[attrName]
if (Math.abs(offset) < 5) {
return
}
this.isDragTableBar = true
this.hideUnnecessaryBar()
this.calculateCurIndex()
this.setDragTargetStyle()
this.setSwitchStyle()
}
ContentState.prototype.handleMouseUp = function (event) {
const { eventCenter } = this.muya
for (const id of this.dragEventIds) {
eventCenter.detachDOMEvent(id)
}
this.dragEventIds = []
if (!this.isDragTableBar) {
return
}
this.setDropTargetStyle()
// The drop animation need 300ms.
setTimeout(() => {
this.switchTableData()
this.resetDragTableBar()
}, 300)
}
ContentState.prototype.hideUnnecessaryBar = function () {
const { barType } = this.dragInfo
const hideClassName = barType === 'bottom' ? 'left' : 'bottom'
const needHideBar = document.querySelector(`.ag-drag-handler.${hideClassName}`)
if (needHideBar) {
needHideBar.style.display = 'none'
}
}
ContentState.prototype.calculateCurIndex = function () {
let { offset, aspects, index } = this.dragInfo
let curIndex = index
const len = aspects.length
let i
if (offset > 0) {
for (i = index; i < len; i++) {
const aspect = aspects[i]
if (i === index) {
offset -= Math.floor(aspect / 2)
} else {
offset -= aspect
}
if (offset < 0) {
break
} else {
curIndex++
}
}
} else if (offset < 0) {
for (i = index; i >= 0; i--) {
const aspect = aspects[i]
if (i === index) {
offset += Math.floor(aspect / 2)
} else {
offset += aspect
}
if (offset > 0) {
break
} else {
curIndex--
}
}
}
this.dragInfo.curIndex = Math.max(0, Math.min(curIndex, len - 1))
}
ContentState.prototype.setDragTargetStyle = function () {
const { offset, barType, dragCells } = this.dragInfo
for (const cell of dragCells) {
if (!cell.classList.contains('ag-drag-cell')) {
cell.classList.add('ag-drag-cell')
cell.classList.add(`ag-drag-${barType}`)
}
const valueName = barType === 'bottom' ? 'translateX' : 'translateY'
cell.style.transform = `${valueName}(${offset}px)`
}
}
ContentState.prototype.setSwitchStyle = function () {
const { index, offset, curIndex, barType, aspects, cells } = this.dragInfo
const aspect = aspects[index]
const len = aspects.length
let i
if (offset > 0) {
if (barType === 'bottom') {
for (const row of cells) {
for (i = 0; i < len; i++) {
const cell = row[i]
if (i > index && i <= curIndex) {
cell.style.transform = `translateX(${-aspect}px)`
} else if (i !== index) {
cell.style.transform = 'translateX(0px)'
}
}
}
} else {
for (i = 0; i < len; i++) {
const row = cells[i]
for (const cell of row) {
if (i > index && i <= curIndex) {
cell.style.transform = `translateY(${-aspect}px)`
} else if (i !== index) {
cell.style.transform = 'translateY(0px)'
}
}
}
}
} else {
if (barType === 'bottom') {
for (const row of cells) {
for (i = 0; i < len; i++) {
const cell = row[i]
if (i >= curIndex && i < index) {
cell.style.transform = `translateX(${aspect}px)`
} else if (i !== index) {
cell.style.transform = 'translateX(0px)'
}
}
}
} else {
for (i = 0; i < len; i++) {
const row = cells[i]
for (const cell of row) {
if (i >= curIndex && i < index) {
cell.style.transform = `translateY(${aspect}px)`
} else if (i !== index) {
cell.style.transform = 'translateY(0px)'
}
}
}
}
}
}
ContentState.prototype.setDropTargetStyle = function () {
const { dragCells, barType, curIndex, index, aspects, offset } = this.dragInfo
let move = 0
let i
if (offset > 0) {
for (i = index + 1; i <= curIndex; i++) {
move += aspects[i]
}
} else {
for (i = curIndex; i < index; i++) {
move -= aspects[i]
}
}
for (const cell of dragCells) {
cell.classList.remove('ag-drag-cell')
cell.classList.remove(`ag-drag-${barType}`)
cell.classList.add('ag-cell-transform')
const valueName = barType === 'bottom' ? 'translateX' : 'translateY'
cell.style.transform = `${valueName}(${move}px)`
}
}
ContentState.prototype.switchTableData = function () {
const { barType, index, curIndex, tableId, offset } = this.dragInfo
const table = this.getBlock(tableId)
const tHead = table.children[0]
const tBody = table.children[1]
const rows = [tHead.children[0], ...(tBody ? tBody.children : [])]
let i
if (index !== curIndex) {
// Cursor in the same cell.
const { start, end } = this.cursor
let key = null
if (barType === 'bottom') {
for (const row of rows) {
const isCursorCell = row.children[index].children[0].key === start.key
const { text } = row.children[index].children[0]
const { align } = row.children[index]
if (offset > 0) {
for (i = index; i < curIndex; i++) {
row.children[i].children[0].text = row.children[i + 1].children[0].text
row.children[i].align = row.children[i + 1].align
}
row.children[curIndex].children[0].text = text
row.children[curIndex].align = align
} else {
for (i = index; i > curIndex; i--) {
row.children[i].children[0].text = row.children[i - 1].children[0].text
row.children[i].align = row.children[i - 1].align
}
row.children[curIndex].children[0].text = text
row.children[curIndex].align = align
}
if (isCursorCell) {
key = row.children[curIndex].children[0].key
}
}
} else {
let column = null
const temp = rows[index].children.map((cell, i) => {
if (cell.children[0].key === start.key) {
column = i
}
return cell.children[0].text
})
if (offset > 0) {
for (i = index; i < curIndex; i++) {
rows[i].children.forEach((cell, ii) => {
cell.children[0].text = rows[i + 1].children[ii].children[0].text
})
}
rows[curIndex].children.forEach((cell, i) => {
if (i === column) {
key = cell.children[0].key
}
cell.children[0].text = temp[i]
})
} else {
for (i = index; i > curIndex; i--) {
rows[i].children.forEach((cell, ii) => {
cell.children[0].text = rows[i - 1].children[ii].children[0].text
})
}
rows[curIndex].children.forEach((cell, i) => {
if (i === column) {
key = cell.children[0].key
}
cell.children[0].text = temp[i]
})
}
}
if (key) {
this.cursor = {
start: {
key,
offset: start.offset
},
end: {
key,
offset: end.offset
}
}
return this.singleRender(table)
} else {
return this.partialRender()
}
}
}
ContentState.prototype.resetDragTableBar = function () {
this.dragInfo = null
this.isDragTableBar = false
}
}
export default tableDragBarCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/dragDropCtrl.js | src/muya/lib/contentState/dragDropCtrl.js | import { findNearestParagraph, findOutMostParagraph } from '../selection/dom'
import { verticalPositionInRect, getUniqueId, getImageInfo as getImageSrc, checkImageContentType } from '../utils'
import { getImageInfo } from '../utils/getImageInfo'
import { URL_REG, IMAGE_EXT_REG } from '../config'
const GHOST_ID = 'mu-dragover-ghost'
const GHOST_HEIGHT = 3
const dragDropCtrl = ContentState => {
ContentState.prototype.hideGhost = function () {
this.dropAnchor = null
const ghost = document.querySelector(`#${GHOST_ID}`)
ghost && ghost.remove()
}
/**
* create the ghost element.
*/
ContentState.prototype.createGhost = function (event) {
const target = event.target
let ghost = null
const nearestParagraph = findNearestParagraph(target)
const outmostParagraph = findOutMostParagraph(target)
if (!outmostParagraph) {
return this.hideGhost()
}
const block = this.getBlock(nearestParagraph.id)
let anchor = this.getAnchor(block)
// dragover preview container
if (!anchor && outmostParagraph) {
anchor = this.getBlock(outmostParagraph.id)
}
if (anchor) {
const anchorParagraph = this.muya.container.querySelector(`#${anchor.key}`)
const rect = anchorParagraph.getBoundingClientRect()
const position = verticalPositionInRect(event, rect)
this.dropAnchor = {
position,
anchor
}
// create ghost
ghost = document.querySelector(`#${GHOST_ID}`)
if (!ghost) {
ghost = document.createElement('div')
ghost.id = GHOST_ID
document.body.appendChild(ghost)
}
Object.assign(ghost.style, {
width: `${rect.width}px`,
left: `${rect.left}px`,
top: position === 'up' ? `${rect.top - GHOST_HEIGHT}px` : `${rect.top + rect.height}px`
})
}
}
ContentState.prototype.dragoverHandler = function (event) {
// Cancel to allow tab drag&drop.
if (!event.dataTransfer.types.length) {
event.dataTransfer.dropEffect = 'none'
return
}
if (event.dataTransfer.types.includes('text/uri-list')) {
const items = Array.from(event.dataTransfer.items)
const hasUriItem = items.some(i => i.type === 'text/uri-list')
const hasTextItem = items.some(i => i.type === 'text/plain')
const hasHtmlItem = items.some(i => i.type === 'text/html')
if (hasUriItem && hasHtmlItem && !hasTextItem) {
this.createGhost(event)
event.dataTransfer.dropEffect = 'copy'
}
}
if (event.dataTransfer.types.indexOf('Files') >= 0) {
if (event.dataTransfer.items.length === 1 && event.dataTransfer.items[0].type.indexOf('image') > -1) {
event.preventDefault()
this.createGhost(event)
event.dataTransfer.dropEffect = 'copy'
}
} else {
event.stopPropagation()
event.dataTransfer.dropEffect = 'none'
}
}
ContentState.prototype.dragleaveHandler = function (event) {
return this.hideGhost()
}
ContentState.prototype.dropHandler = async function (event) {
event.preventDefault()
const { dropAnchor } = this
this.hideGhost()
// handle drag/drop web link image.
if (event.dataTransfer.items.length) {
for (const item of event.dataTransfer.items) {
if (item.kind === 'string' && item.type === 'text/uri-list') {
item.getAsString(async str => {
if (URL_REG.test(str) && dropAnchor) {
let isImage = false
if (IMAGE_EXT_REG.test(str)) {
isImage = true
}
if (!isImage) {
isImage = await checkImageContentType(str)
}
if (!isImage) return
const text = ``
const imageBlock = this.createBlockP(text)
const { anchor, position } = dropAnchor
if (position === 'up') {
this.insertBefore(imageBlock, anchor)
} else {
this.insertAfter(imageBlock, anchor)
}
const key = imageBlock.children[0].key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.render()
this.muya.eventCenter.dispatch('stateChange')
}
})
}
}
}
if (event.dataTransfer.files) {
const fileList = []
for (const file of event.dataTransfer.files) {
fileList.push(file)
}
const image = fileList.find(file => /image/.test(file.type))
if (image && dropAnchor) {
const { name, path } = image
const id = `loading-${getUniqueId()}`
const text = ``
const imageBlock = this.createBlockP(text)
const { anchor, position } = dropAnchor
if (position === 'up') {
this.insertBefore(imageBlock, anchor)
} else {
this.insertAfter(imageBlock, anchor)
}
const key = imageBlock.children[0].key
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.render()
try {
const newSrc = await this.muya.options.imageAction(path, id, name)
const { src } = getImageSrc(path)
if (src) {
this.stateRender.urlMap.set(newSrc, src)
}
const imageWrapper = this.muya.container.querySelector(`span[data-id=${id}]`)
if (imageWrapper) {
const imageInfo = getImageInfo(imageWrapper)
this.replaceImage(imageInfo, {
alt: name,
src: newSrc
})
}
} catch (error) {
// TODO: Notify user about an error.
console.error('Unexpected error on image action:', error)
}
}
this.muya.eventCenter.dispatch('stateChange')
}
}
}
export default dragDropCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/codeBlockCtrl.js | src/muya/lib/contentState/codeBlockCtrl.js | import { loadLanguage } from '../prism/index'
import { escapeHTML } from '../utils'
// import resizeCodeBlockLineNumber from '../utils/resizeCodeLineNumber'
import selection from '../selection'
const CODE_UPDATE_REP = /^`{3,}(.*)/
const codeBlockCtrl = ContentState => {
/**
* check edit language
*/
ContentState.prototype.checkEditLanguage = function () {
const { start } = selection.getCursorRange()
if (!start) {
return { lang: '', paragraph: null }
}
const startBlock = this.getBlock(start.key)
const paragraph = document.querySelector(`#${start.key}`)
let lang = ''
const { text } = startBlock
if (startBlock.type === 'span') {
if (startBlock.functionType === 'languageInput') {
lang = text.trim()
} else if (startBlock.functionType === 'paragraphContent') {
const token = text.match(/(^`{3,})([^`]+)/)
if (token) {
const len = token[1].length
if (start.offset >= len) {
lang = token[2].trim()
}
}
}
}
return { lang, paragraph }
}
ContentState.prototype.selectLanguage = function (paragraph, lang) {
const block = this.getBlock(paragraph.id)
if (lang === 'math' && this.isGitlabCompatibilityEnabled && this.updateMathBlock(block)) {
return
}
this.updateCodeLanguage(block, lang)
}
/**
* Update the code block language or creates a new code block.
*
* @param block Language-input block or paragraph
* @param lang Language identifier
*/
ContentState.prototype.updateCodeLanguage = function (block, lang) {
if (!lang || typeof lang !== 'string') {
console.error('Invalid code block language string:', lang)
// Use fallback language
lang = ''
}
// Prevent possible XSS on language input when using lang attribute later on. The input is also sanitized before rendering.
lang = escapeHTML(lang)
if (lang !== '') {
loadLanguage(lang)
}
if (block.functionType === 'languageInput') {
const preBlock = this.getParent(block)
const nextSibling = this.getNextSibling(block)
// Only update code language if necessary
if (block.text !== lang || preBlock.text !== lang || nextSibling.text !== lang) {
block.text = lang
preBlock.lang = lang
preBlock.functionType = 'fencecode'
nextSibling.lang = lang
nextSibling.children.forEach(c => (c.lang = lang))
}
// Set cursor at the first line
const { key } = nextSibling.children[0]
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
} else {
block.text = block.text.replace(/^(`+)([^`]+$)/g, `$1${lang}`)
this.codeBlockUpdate(block)
}
this.partialRender()
}
/**
* [codeBlockUpdate if block updated to `pre` return true, else return false]
*/
ContentState.prototype.codeBlockUpdate = function (block, code = '', lang) {
if (block.type === 'span') {
block = this.getParent(block)
}
// If it's not a p block, no need to update
if (block.type !== 'p') return false
// If p block's children are more than one, no need to update
if (block.children.length !== 1) return false
const { text } = block.children[0]
const match = CODE_UPDATE_REP.exec(text)
if (match || lang) {
const language = lang || (match ? match[1] : '')
const codeBlock = this.createBlock('code', {
lang: language
})
const codeContent = this.createBlock('span', {
text: code,
lang: language,
functionType: 'codeContent'
})
const inputBlock = this.createBlock('span', {
text: language,
functionType: 'languageInput'
})
if (language) {
loadLanguage(language)
}
block.type = 'pre'
block.functionType = 'fencecode'
block.lang = language
block.text = ''
block.history = null
block.children = []
this.appendChild(codeBlock, codeContent)
this.appendChild(block, inputBlock)
this.appendChild(block, codeBlock)
const { key } = codeContent
const offset = code.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return true
}
return false
}
/**
* Copy the code block by click right-top copy icon in code block.
*/
ContentState.prototype.copyCodeBlock = function (event) {
const { target } = event
const preEle = target.closest('pre')
const preBlock = this.getBlock(preEle.id)
const codeBlock = preBlock.children.find(c => c.type === 'code')
const codeContent = codeBlock.children[0].text
this.muya.clipboard.copy('copyCodeContent', codeContent)
}
ContentState.prototype.resizeLineNumber = function () {
// FIXME: Disabled due to #1648.
// const { codeBlockLineNumbers } = this.muya.options
// if (!codeBlockLineNumbers) {
// return
// }
// const codeBlocks = document.querySelectorAll('pre.line-numbers')
// if (codeBlocks.length) {
// for (const ele of codeBlocks) {
// resizeCodeBlockLineNumber(ele)
// }
// }
}
}
export default codeBlockCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/tableSelectCellsCtrl.js | src/muya/lib/contentState/tableSelectCellsCtrl.js | import { getAllTableCells, getIndex } from './tableDragBarCtrl'
const tableSelectCellsCtrl = ContentState => {
ContentState.prototype.handleCellMouseDown = function (event) {
if (event.buttons === 2) {
// the contextmenu is emit.
return
}
const { eventCenter } = this.muya
const { target } = event
const cell = target.closest('th') || target.closest('td')
const tableId = target.closest('table').id
const row = getIndex('left', cell)
const column = getIndex('bottom', cell)
this.cellSelectInfo = {
tableId,
anchor: {
key: cell.id,
row,
column
},
focus: null,
isStartSelect: false,
cells: getAllTableCells(tableId),
selectedCells: []
}
const mouseMoveId = eventCenter.attachDOMEvent(document.body, 'mousemove', this.handleCellMouseMove.bind(this))
const mouseUpId = eventCenter.attachDOMEvent(document.body, 'mouseup', this.handleCellMouseUp.bind(this))
this.cellSelectEventIds.push(mouseMoveId, mouseUpId)
}
ContentState.prototype.handleCellMouseMove = function (event) {
const { target } = event
const cell = target.closest('th') || target.closest('td')
const table = target.closest('table')
const isOverSameTableCell = cell && table && table.id === this.cellSelectInfo.tableId
if (isOverSameTableCell && cell.id !== this.cellSelectInfo.anchor.key) {
this.cellSelectInfo.isStartSelect = true
this.muya.blur(true)
}
if (isOverSameTableCell && this.cellSelectInfo.isStartSelect) {
const row = getIndex('left', cell)
const column = getIndex('bottom', cell)
this.cellSelectInfo.focus = {
key: cell.key,
row,
column
}
} else {
this.cellSelectInfo.focus = null
}
this.calculateSelectedCells()
this.setSelectedCellsStyle()
}
ContentState.prototype.handleCellMouseUp = function (event) {
const { eventCenter } = this.muya
for (const id of this.cellSelectEventIds) {
eventCenter.detachDOMEvent(id)
}
this.cellSelectEventIds = []
if (this.cellSelectInfo && this.cellSelectInfo.isStartSelect) {
event.preventDefault()
const { tableId, selectedCells, anchor, focus } = this.cellSelectInfo
// Mouse up outside table, the focus is null
if (!focus) {
return
}
// We need to handle this after click event, because click event is emited after mouseup(mouseup will be followed by a click envent), but we set
// the `selectedTableCells` to null when click event emited.
setTimeout(() => {
this.selectedTableCells = {
tableId,
row: Math.abs(anchor.row - focus.row) + 1, // 1 base
column: Math.abs(anchor.column - focus.column) + 1, // 1 base
cells: selectedCells.map(c => {
delete c.ele
return c
})
}
this.cellSelectInfo = null
const table = this.getBlock(tableId)
return this.singleRender(table, false)
})
}
}
ContentState.prototype.calculateSelectedCells = function () {
const { anchor, focus, cells } = this.cellSelectInfo
this.cellSelectInfo.selectedCells = []
if (focus) {
const startRowIndex = Math.min(anchor.row, focus.row)
const endRowIndex = Math.max(anchor.row, focus.row)
const startColIndex = Math.min(anchor.column, focus.column)
const endColIndex = Math.max(anchor.column, focus.column)
let i
let j
for (i = startRowIndex; i <= endRowIndex; i++) {
const row = cells[i]
for (j = startColIndex; j <= endColIndex; j++) {
const cell = row[j]
const cellBlock = this.getBlock(cell.id)
this.cellSelectInfo.selectedCells.push({
ele: cell,
key: cell.id,
text: cellBlock.children[0].text,
align: cellBlock.align,
top: i === startRowIndex,
right: j === endColIndex,
bottom: i === endRowIndex,
left: j === startColIndex
})
}
}
}
}
ContentState.prototype.setSelectedCellsStyle = function () {
const { selectedCells, cells } = this.cellSelectInfo
for (const row of cells) {
for (const cell of row) {
cell.classList.remove('ag-cell-selected')
cell.classList.remove('ag-cell-border-top')
cell.classList.remove('ag-cell-border-right')
cell.classList.remove('ag-cell-border-bottom')
cell.classList.remove('ag-cell-border-left')
}
}
for (const cell of selectedCells) {
const { ele, top, right, bottom, left } = cell
ele.classList.add('ag-cell-selected')
if (top) {
ele.classList.add('ag-cell-border-top')
}
if (right) {
ele.classList.add('ag-cell-border-right')
}
if (bottom) {
ele.classList.add('ag-cell-border-bottom')
}
if (left) {
ele.classList.add('ag-cell-border-left')
}
}
}
// Remove the content of selected table cell, delete the row/column if selected one row/column without content.
// Delete the table if the selected whole table is empty.
ContentState.prototype.deleteSelectedTableCells = function (isCut = false) {
const { tableId, cells } = this.selectedTableCells
const tableBlock = this.getBlock(tableId)
const { row, column } = tableBlock
const rows = new Set()
let lastColumn = null
let isSameColumn = true
let hasContent = false
for (const cell of cells) {
const cellBlock = this.getBlock(cell.key)
const rowBlock = this.getParent(cellBlock)
const { column: cellColumn } = cellBlock
rows.add(rowBlock)
if (cellBlock.children[0].text) {
hasContent = true
}
if (typeof lastColumn === 'object') {
lastColumn = cellColumn
} else if (cellColumn !== lastColumn) {
isSameColumn = false
}
cellBlock.children[0].text = ''
}
const isOneColumnSelected = rows.size === +row + 1 && isSameColumn
const isOneRowSelected = cells.length === +column + 1 && rows.size === 1
const isWholeTableSelected = rows.size === +row + 1 && cells.length === (+row + 1) * (+column + 1)
if (isCut && isWholeTableSelected) {
this.selectedTableCells = null
return this.deleteParagraph(tableId)
}
if (hasContent) {
this.singleRender(tableBlock, false)
return this.muya.dispatchChange()
} else {
const cellKey = cells[0].key
const cellBlock = this.getBlock(cellKey)
const cellContentKey = cellBlock.children[0].key
this.selectedTableCells = null
if (isOneColumnSelected) {
// Remove one empty column
return this.editTable({
location: 'current',
action: 'remove',
target: 'column'
}, cellContentKey)
} else if (isOneRowSelected) {
// Remove one empty row
return this.editTable({
location: 'current',
action: 'remove',
target: 'row'
}, cellContentKey)
} else if (isWholeTableSelected) {
// Select whole empty table
return this.deleteParagraph(tableId)
}
}
}
ContentState.prototype.selectTable = function (table) {
// For calculateSelectedCells
this.cellSelectInfo = {
anchor: {
row: 0,
column: 0
},
focus: {
row: table.row,
column: table.column
},
cells: getAllTableCells(table.key)
}
this.calculateSelectedCells()
this.selectedTableCells = {
tableId: table.key,
row: table.row + 1,
column: table.column + 1,
cells: this.cellSelectInfo.selectedCells.map(c => {
delete c.ele
return c
})
}
// reset cellSelectInfo
this.cellSelectInfo = null
this.muya.blur()
return this.singleRender(table, false)
}
// Return the cell block if yes, else return null.
ContentState.prototype.isSingleCellSelected = function () {
const { selectedTableCells } = this
if (selectedTableCells && selectedTableCells.cells.length === 1) {
const key = selectedTableCells.cells[0].key
return this.getBlock(key)
}
return null
}
// Return the cell block if yes, else return null.
ContentState.prototype.isWholeTableSelected = function () {
const { selectedTableCells } = this
const table = selectedTableCells ? this.getBlock(selectedTableCells.tableId) : {}
const { row, column } = table
if (selectedTableCells && table && selectedTableCells.cells.length === (+row + 1) * (+column + 1)) {
return table
}
return null
}
}
export default tableSelectCellsCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/marktext.js | src/muya/lib/contentState/marktext.js | // __MARKTEXT_ONLY__
import { extractWord, offsetToWordCursor, validateLineCursor } from '../marktext/spellchecker'
import selection from '../selection'
const marktextApi = ContentState => {
/**
* Replace the current selected word with the given replacement.
*
* NOTE: Unsafe method because exacly one word have to be selected. This
* is currently used to replace a misspelled word in MarkText that was selected
* by Chromium.
*
* @param {string} word The old word that should be replaced. The whole word must be selected.
* @param {string} replacement The word to replace the selecte one.
* @returns {boolean} True on success.
*/
ContentState.prototype._replaceCurrentWordInlineUnsafe = function (word, replacement) {
// Right clicking on a misspelled word select the whole word by Chromium.
const { start, end } = selection.getCursorRange()
const cursor = Object.assign({}, { start, end })
cursor.start.block = this.getBlock(start.key)
if (!validateLineCursor(cursor)) {
console.warn('Unable to replace word: multiple lines are selected.', JSON.stringify(cursor))
return false
}
const { start: startCursor } = cursor
const { offset: lineOffset } = startCursor
const { text } = startCursor.block
const wordInfo = extractWord(text, lineOffset)
if (wordInfo) {
const { left, right, word: selectedWord } = wordInfo
if (selectedWord !== word) {
console.warn(`Unable to replace word: Chromium selection mismatch (expected "${selectedWord}" but found "${word}").`)
return false
}
// Translate offsets into a cursor with the given line.
const wordRange = offsetToWordCursor(this.cursor, left, right)
this.replaceWordInline(cursor, wordRange, replacement, true)
return true
}
return false
}
}
export default marktextApi
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/tocCtrl.js | src/muya/lib/contentState/tocCtrl.js | const tocCtrl = ContentState => {
ContentState.prototype.getTOC = function () {
const { blocks } = this
const toc = []
for (const block of blocks) {
if (/^h\d$/.test(block.type)) {
const { headingStyle, key, type } = block
const { text } = block.children[0]
const content = headingStyle === 'setext' ? text.trim() : text.replace(/^\s*#{1,6}\s{1,}/, '').trim()
const lvl = +type.substring(1)
const slug = key
toc.push({
content,
lvl,
slug
})
}
}
return toc
}
}
export default tocCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/imageCtrl.js | src/muya/lib/contentState/imageCtrl.js | import { URL_REG, DATA_URL_REG } from '../config'
import { correctImageSrc } from '../utils/getImageInfo'
const imageCtrl = ContentState => {
/**
* insert inline image at the cursor position.
*/
ContentState.prototype.insertImage = function ({ alt = '', src = '', title = '' }) {
const match = /(?:\/|\\)?([^./\\]+)\.[a-z]+$/.exec(src)
if (!alt) {
alt = match && match[1] ? match[1] : ''
}
const { start, end } = this.cursor
const { formats } = this.selectionFormats({ start, end })
const { key, offset: startOffset } = start
const { offset: endOffset } = end
const block = this.getBlock(key)
if (
block.type === 'span' &&
(
block.functionType === 'codeContent' ||
block.functionType === 'languageInput' ||
block.functionType === 'thematicBreakLine'
)
) {
// You can not insert image into code block or language input...
return
}
const { text } = block
const imageFormat = formats.filter(f => f.type === 'image')
// Only encode URLs but not local paths or data URLs
let imgUrl
if (URL_REG.test(src)) {
imgUrl = encodeURI(src)
} else if (DATA_URL_REG.test(src)) {
imgUrl = src
} else {
imgUrl = src.replace(/ /g, encodeURI(' ')).replace(/#/g, encodeURIComponent('#'))
}
let srcAndTitle = imgUrl
if (srcAndTitle && title) {
srcAndTitle += ` "${title}"`
}
if (
imageFormat.length === 1 &&
imageFormat[0].range.start !== startOffset &&
imageFormat[0].range.end !== endOffset
) {
// Replace already existing image
let imageAlt = alt
// Extract alt from image if there isn't an image source already (GH#562). E.g: ![old-alt]()
if (imageFormat[0].alt && !imageFormat[0].src) {
imageAlt = imageFormat[0].alt
}
const { start, end } = imageFormat[0].range
block.text = text.substring(0, start) +
`` +
text.substring(end)
this.cursor = {
start: { key, offset: start + 2 },
end: { key, offset: start + 2 + imageAlt.length }
}
} else if (key !== end.key) {
// Replace multi-line text
const endBlock = this.getBlock(end.key)
const { text } = endBlock
endBlock.text = text.substring(0, endOffset) + `` + text.substring(endOffset)
const offset = endOffset + 2
this.cursor = {
start: { key: end.key, offset },
end: { key: end.key, offset: offset + alt.length }
}
} else {
// Replace single-line text
const imageAlt = startOffset !== endOffset ? text.substring(startOffset, endOffset) : alt
block.text = text.substring(0, start.offset) +
`` +
text.substring(end.offset)
this.cursor = {
start: {
key,
offset: startOffset + 2
},
end: {
key,
offset: startOffset + 2 + imageAlt.length
}
}
}
this.partialRender()
this.muya.dispatchChange()
}
ContentState.prototype.updateImage = function ({ imageId, key, token }, attrName, attrValue) { // inline/left/center/right
const block = this.getBlock(key)
const { range } = token
const { start, end } = range
const oldText = block.text
let imageText = ''
const attrs = Object.assign({}, token.attrs)
attrs[attrName] = attrValue
imageText = '<img '
for (const attr of Object.keys(attrs)) {
let value = attrs[attr]
if (value && attr === 'src') {
value = correctImageSrc(value)
}
imageText += `${attr}="${value}" `
}
imageText = imageText.trim()
imageText += '>'
block.text = oldText.substring(0, start) + imageText + oldText.substring(end)
this.singleRender(block, false)
const image = document.querySelector(`#${imageId} img`)
if (image) {
image.click()
return this.muya.dispatchChange()
}
}
ContentState.prototype.replaceImage = function ({ key, token }, { alt = '', src = '', title = '' }) {
const { type } = token
const block = this.getBlock(key)
const { start, end } = token.range
const oldText = block.text
let imageText = ''
if (type === 'image') {
imageText = ' {
imageText += src.replace(/ /g, encodeURI(' ')).replace(/#/g, encodeURIComponent('#'))
}
if (title) {
imageText += ` "${title}"`
}
imageText += ')'
} else if (type === 'html_tag') {
const { attrs } = token
Object.assign(attrs, { alt, src, title })
imageText = '<img '
for (const attr of Object.keys(attrs)) {
let value = attrs[attr]
if (value && attr === 'src') {
value = correctImageSrc(value)
}
imageText += `${attr}="${value}" `
}
imageText = imageText.trim()
imageText += '>'
}
block.text = oldText.substring(0, start) + imageText + oldText.substring(end)
this.singleRender(block)
return this.muya.dispatchChange()
}
ContentState.prototype.deleteImage = function ({ key, token }) {
const block = this.getBlock(key)
const oldText = block.text
const { start, end } = token.range
const { eventCenter } = this.muya
block.text = oldText.substring(0, start) + oldText.substring(end)
this.cursor = {
start: { key, offset: start },
end: { key, offset: start }
}
this.singleRender(block)
// Hide image toolbar and image transformer
eventCenter.dispatch('muya-transformer', { reference: null })
eventCenter.dispatch('muya-image-toolbar', { reference: null })
return this.muya.dispatchChange()
}
ContentState.prototype.selectImage = function (imageInfo) {
this.selectedImage = imageInfo
const { key } = imageInfo
const block = this.getBlock(key)
const outMostBlock = this.findOutMostBlock(block)
this.cursor = {
start: { key, offset: imageInfo.token.range.end },
end: { key, offset: imageInfo.token.range.end }
}
// Fix #1568
const { start } = this.prevCursor
const oldBlock = this.findOutMostBlock(this.getBlock(start.key))
if (oldBlock.key !== outMostBlock.key) {
this.singleRender(oldBlock, false)
}
return this.singleRender(outMostBlock, true)
}
}
export default imageCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/enterCtrl.js | src/muya/lib/contentState/enterCtrl.js | import selection from '../selection'
import { isOsx } from '../config'
/* eslint-disable no-useless-escape */
const FOOTNOTE_REG = /^\[\^([^\^\[\]\s]+?)(?<!\\)\]:$/
/* eslint-enable no-useless-escape */
const checkAutoIndent = (text, offset) => {
const pairStr = text.substring(offset - 1, offset + 1)
return /^(\{\}|\[\]|\(\)|><)$/.test(pairStr)
}
const getIndentSpace = text => {
const match = /^(\s*)\S/.exec(text)
return match ? match[1] : ''
}
const enterCtrl = ContentState => {
// TODO@jocs this function need opti.
ContentState.prototype.chopBlockByCursor = function (block, key, offset) {
const newBlock = this.createBlock('p')
const { children } = block
const index = children.findIndex(child => child.key === key)
const activeLine = this.getBlock(key)
const { text } = activeLine
newBlock.children = children.splice(index + 1)
newBlock.children.forEach(c => (c.parent = newBlock.key))
children[index].nextSibling = null
if (newBlock.children.length) {
newBlock.children[0].preSibling = null
}
if (offset === 0) {
this.removeBlock(activeLine, children)
this.prependChild(newBlock, activeLine)
} else if (offset < text.length) {
activeLine.text = text.substring(0, offset)
const newLine = this.createBlock('span', { text: text.substring(offset) })
this.prependChild(newBlock, newLine)
}
return newBlock
}
ContentState.prototype.chopBlock = function (block) {
const parent = this.getParent(block)
const type = parent.type
const container = this.createBlock(type)
const index = this.findIndex(parent.children, block)
const partChildren = parent.children.splice(index + 1)
block.nextSibling = null
partChildren.forEach(b => {
this.appendChild(container, b)
})
this.insertAfter(container, parent)
return container
}
ContentState.prototype.createRow = function (row, isHeader = false) {
const tr = this.createBlock('tr')
const len = row.children.length
let i
for (i = 0; i < len; i++) {
const cell = this.createBlock(isHeader ? 'th' : 'td', {
align: row.children[i].align,
column: i
})
const cellContent = this.createBlock('span', {
functionType: 'cellContent'
})
this.appendChild(cell, cellContent)
this.appendChild(tr, cell)
}
return tr
}
ContentState.prototype.createBlockLi = function (paragraphInListItem) {
const liBlock = this.createBlock('li')
if (!paragraphInListItem) {
paragraphInListItem = this.createBlockP()
}
this.appendChild(liBlock, paragraphInListItem)
return liBlock
}
ContentState.prototype.createTaskItemBlock = function (paragraphInListItem, checked = false) {
const listItem = this.createBlock('li')
const checkboxInListItem = this.createBlock('input')
listItem.listItemType = 'task'
checkboxInListItem.checked = checked
if (!paragraphInListItem) {
paragraphInListItem = this.createBlockP()
}
this.appendChild(listItem, checkboxInListItem)
this.appendChild(listItem, paragraphInListItem)
return listItem
}
ContentState.prototype.enterInEmptyParagraph = function (block) {
if (block.type === 'span') block = this.getParent(block)
const parent = this.getParent(block)
let newBlock = null
if (parent && (/ul|ol|blockquote/.test(parent.type))) {
newBlock = this.createBlockP()
if (this.isOnlyChild(block)) {
this.insertAfter(newBlock, parent)
this.removeBlock(parent)
} else if (this.isFirstChild(block)) {
this.insertBefore(newBlock, parent)
} else if (this.isLastChild(block)) {
this.insertAfter(newBlock, parent)
} else {
this.chopBlock(block)
this.insertAfter(newBlock, parent)
}
this.removeBlock(block)
} else if (parent && parent.type === 'li') {
if (parent.listItemType === 'task') {
const { checked } = parent.children[0]
newBlock = this.createTaskItemBlock(null, checked)
} else {
newBlock = this.createBlockLi()
newBlock.listItemType = parent.listItemType
newBlock.bulletMarkerOrDelimiter = parent.bulletMarkerOrDelimiter
}
newBlock.isLooseListItem = parent.isLooseListItem
this.insertAfter(newBlock, parent)
const index = this.findIndex(parent.children, block)
const blocksInListItem = parent.children.splice(index + 1)
blocksInListItem.forEach(b => this.appendChild(newBlock, b))
this.removeBlock(block)
newBlock = newBlock.listItemType === 'task'
? newBlock.children[1]
: newBlock.children[0]
} else {
newBlock = this.createBlockP()
if (block.type === 'li') {
this.insertAfter(newBlock, parent)
this.removeBlock(block)
} else {
this.insertAfter(newBlock, block)
}
}
const { key } = newBlock.children[0]
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
ContentState.prototype.docEnterHandler = function (event) {
const { eventCenter } = this.muya
const { selectedImage } = this
// Show image selector when you press Enter key and there is already one image selected.
if (selectedImage) {
event.preventDefault()
event.stopPropagation()
const { imageId, ...imageInfo } = selectedImage
const imageWrapper = document.querySelector(`#${imageId}`)
const rect = imageWrapper.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
rect.height = 0 // Put image selector below the top border of image.
return rect
}
}
eventCenter.dispatch('muya-image-selector', {
reference,
imageInfo,
cb: () => {}
})
this.selectedImage = null
}
}
ContentState.prototype.enterHandler = function (event) {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return event.preventDefault()
}
let block = this.getBlock(start.key)
const { text } = block
const endBlock = this.getBlock(end.key)
let parent = this.getParent(block)
event.preventDefault()
// Don't allow new lines in language identifiers (GH#569)
if (block.functionType && block.functionType === 'languageInput') {
// Jump inside the code block and update code language if necessary
this.updateCodeLanguage(block, block.text.trim())
return
}
// handle select multiple blocks
if (start.key !== end.key) {
const key = start.key
const offset = start.offset
const startRemainText = block.text.substring(0, start.offset)
const endRemainText = endBlock.text.substring(end.offset)
block.text = startRemainText + endRemainText
this.removeBlocks(block, endBlock)
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
return this.enterHandler(event)
}
// handle select multiple charactors
if (start.key === end.key && start.offset !== end.offset) {
const key = start.key
const offset = start.offset
block.text = block.text.substring(0, start.offset) + block.text.substring(end.offset)
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
return this.enterHandler(event)
}
if (
block.type === 'span' &&
block.functionType === 'paragraphContent' &&
!this.getParent(block).parent &&
start.offset === text.length &&
FOOTNOTE_REG.test(text)
) {
event.preventDefault()
event.stopPropagation()
// Just to feet the `updateFootnote` API and add one white space.
block.text += ' '
const key = block.key
const offset = block.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.updateFootnote(this.getParent(block), block)
}
// handle `shift + enter` insert `soft line break` or `hard line break`
// only cursor in `line block` can create `soft line break` and `hard line break`
// handle line in code block
if (event.shiftKey && block.type === 'span' && block.functionType === 'paragraphContent') {
let { offset } = start
const { text, key } = block
const indent = getIndentSpace(text)
block.text = text.substring(0, offset) + '\n' + indent + text.substring(offset)
offset += 1 + indent.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
} else if (
block.type === 'span' &&
block.functionType === 'codeContent'
) {
const { text, key } = block
const autoIndent = checkAutoIndent(text, start.offset)
const indent = getIndentSpace(text)
block.text = text.substring(0, start.offset) +
'\n' +
(autoIndent ? indent + ' '.repeat(this.tabSize) + '\n' : '') +
indent +
text.substring(start.offset)
let offset = start.offset + 1 + indent.length
if (autoIndent) {
offset += this.tabSize
}
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
// Insert `<br/>` in table cell if you want to open a new line.
// Why not use `soft line break` or `hard line break` ?
// Becasuse table cell only have one line.
if (event.shiftKey && block.functionType === 'cellContent') {
const { text, key } = block
const brTag = '<br/>'
block.text = text.substring(0, start.offset) + brTag + text.substring(start.offset)
const offset = start.offset + brTag.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender([block])
}
const getFirstBlockInNextRow = row => {
let nextSibling = this.getBlock(row.nextSibling)
if (!nextSibling) {
const rowContainer = this.getBlock(row.parent)
const table = this.getBlock(rowContainer.parent)
const figure = this.getBlock(table.parent)
if (rowContainer.type === 'thead' && table.children[1]) {
nextSibling = table.children[1]
} else if (figure.nextSibling) {
nextSibling = this.getBlock(figure.nextSibling)
} else {
nextSibling = this.createBlockP()
this.insertAfter(nextSibling, figure)
}
}
return this.firstInDescendant(nextSibling)
}
// handle enter in table
if (block.functionType === 'cellContent') {
const row = this.closest(block, 'tr')
const rowContainer = this.getBlock(row.parent)
const table = this.closest(rowContainer, 'table')
if (
(isOsx && event.metaKey) ||
(!isOsx && event.ctrlKey)
) {
const nextRow = this.createRow(row, false)
if (rowContainer.type === 'thead') {
let tBody = this.getBlock(rowContainer.nextSibling)
if (!tBody) {
tBody = this.createBlock('tbody')
this.appendChild(table, tBody)
}
if (tBody.children.length) {
this.insertBefore(nextRow, tBody.children[0])
} else {
this.appendChild(tBody, nextRow)
}
} else {
this.insertAfter(nextRow, row)
}
table.row++
}
const { key } = getFirstBlockInNextRow(row)
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return this.partialRender()
}
if (block.type === 'span') {
block = parent
parent = this.getParent(block)
}
const paragraph = document.querySelector(`#${block.key}`)
if (
(parent && parent.type === 'li' && this.isOnlyChild(block)) ||
(parent && parent.type === 'li' && parent.listItemType === 'task' && parent.children.length === 2) // one `input` and one `p`
) {
block = parent
parent = this.getParent(block)
}
const left = start.offset
const right = text.length - left
const type = block.type
let newBlock
switch (true) {
case left !== 0 && right !== 0: {
// cursor in the middle
let { pre, post } = selection.chopHtmlByCursor(paragraph)
if (/^h\d$/.test(block.type)) {
if (block.headingStyle === 'atx') {
const PREFIX = /^#+/.exec(pre)[0]
post = `${PREFIX} ${post}`
}
block.children[0].text = pre
newBlock = this.createBlock(type, {
headingStyle: block.headingStyle
})
const headerContent = this.createBlock('span', {
text: post,
functionType: block.headingStyle === 'atx' ? 'atxLine' : 'paragraphContent'
})
this.appendChild(newBlock, headerContent)
if (block.marker) {
newBlock.marker = block.marker
}
} else if (block.type === 'p') {
newBlock = this.chopBlockByCursor(block, start.key, start.offset)
} else if (type === 'li') {
// handle task item
if (block.listItemType === 'task') {
const { checked } = block.children[0] // block.children[0] is input[type=checkbox]
newBlock = this.chopBlockByCursor(block.children[1], start.key, start.offset)
newBlock = this.createTaskItemBlock(newBlock, checked)
} else {
newBlock = this.chopBlockByCursor(block.children[0], start.key, start.offset)
newBlock = this.createBlockLi(newBlock)
newBlock.listItemType = block.listItemType
newBlock.bulletMarkerOrDelimiter = block.bulletMarkerOrDelimiter
}
newBlock.isLooseListItem = block.isLooseListItem
} else if (block.type === 'hr') {
const preText = text.substring(0, left)
const postText = text.substring(left)
// Degrade thematice break to paragraph
if (preText.replace(/ /g, '').length < 3) {
block.type = 'p'
block.children[0].functionType = 'paragraphContent'
}
if (postText.replace(/ /g, '').length >= 3) {
newBlock = this.createBlock('hr')
const content = this.createBlock('span', {
functionType: 'thematicBreakLine',
text: postText
})
this.appendChild(newBlock, content)
} else {
newBlock = this.createBlockP(postText)
}
block.children[0].text = preText
}
this.insertAfter(newBlock, block)
break
}
case left === 0 && right === 0: {
// paragraph is empty
return this.enterInEmptyParagraph(block)
}
case left !== 0 && right === 0:
case left === 0 && right !== 0: {
// cursor at end of paragraph or at begin of paragraph
if (type === 'li') {
if (block.listItemType === 'task') {
const checked = false
newBlock = this.createTaskItemBlock(null, checked)
} else {
newBlock = this.createBlockLi()
newBlock.listItemType = block.listItemType
newBlock.bulletMarkerOrDelimiter = block.bulletMarkerOrDelimiter
}
newBlock.isLooseListItem = block.isLooseListItem
} else {
newBlock = this.createBlockP()
}
if (left === 0 && right !== 0) {
this.insertBefore(newBlock, block)
newBlock = block
} else {
if (block.type === 'p') {
const lastLine = block.children[block.children.length - 1]
if (lastLine.text === '') {
this.removeBlock(lastLine)
}
}
this.insertAfter(newBlock, block)
}
break
}
default: {
newBlock = this.createBlockP()
this.insertAfter(newBlock, block)
break
}
}
const getParagraphBlock = block => {
if (block.type === 'li') {
return block.listItemType === 'task' ? block.children[1] : block.children[0]
} else {
return block
}
}
this.codeBlockUpdate(getParagraphBlock(newBlock))
// If block is pre block when updated, need to focus it.
const preParagraphBlock = getParagraphBlock(block)
const blockNeedFocus = this.codeBlockUpdate(preParagraphBlock)
const tableNeedFocus = this.tableBlockUpdate(preParagraphBlock)
const htmlNeedFocus = this.updateHtmlBlock(preParagraphBlock)
const mathNeedFocus = this.updateMathBlock(preParagraphBlock)
let cursorBlock
switch (true) {
case !!blockNeedFocus:
cursorBlock = block
break
case !!tableNeedFocus:
cursorBlock = tableNeedFocus
break
case !!htmlNeedFocus:
cursorBlock = htmlNeedFocus.children[0].children[0] // the second line
break
case !!mathNeedFocus:
cursorBlock = mathNeedFocus
break
default:
cursorBlock = newBlock
break
}
cursorBlock = getParagraphBlock(cursorBlock)
const key = cursorBlock.type === 'p' || cursorBlock.type === 'pre' ? cursorBlock.children[0].key : cursorBlock.key
let offset = 0
if (htmlNeedFocus) {
const { text } = cursorBlock
const match = /^[^\n]+\n[^\n]*/.exec(text)
offset = match && match[0] ? match[0].length : 0
}
this.cursor = {
start: { key, offset },
end: { key, offset }
}
let needRenderAll = false
if (this.isCollapse() && cursorBlock.type === 'p') {
this.checkInlineUpdate(cursorBlock.children[0])
needRenderAll = true
}
needRenderAll ? this.render() : this.partialRender()
}
}
export default enterCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/containerCtrl.js | src/muya/lib/contentState/containerCtrl.js | const FUNCTION_TYPE_LANG = {
multiplemath: 'latex',
flowchart: 'yaml',
mermaid: 'yaml',
sequence: 'yaml',
plantuml: 'yaml',
'vega-lite': 'yaml',
html: 'markup'
}
const containerCtrl = ContentState => {
ContentState.prototype.createContainerBlock = function (functionType, value = '', style = undefined) {
const figureBlock = this.createBlock('figure', {
functionType
})
if (functionType === 'multiplemath') {
if (style === undefined) {
figureBlock.mathStyle = this.isGitlabCompatibilityEnabled ? 'gitlab' : ''
}
figureBlock.mathStyle = style
}
const { preBlock, preview } = this.createPreAndPreview(functionType, value)
this.appendChild(figureBlock, preBlock)
this.appendChild(figureBlock, preview)
return figureBlock
}
ContentState.prototype.createPreAndPreview = function (functionType, value = '') {
const lang = FUNCTION_TYPE_LANG[functionType]
const preBlock = this.createBlock('pre', {
functionType,
lang
})
const codeBlock = this.createBlock('code', {
lang
})
this.appendChild(preBlock, codeBlock)
if (typeof value === 'string' && value) {
value = value.replace(/^\s+/, '')
const codeContent = this.createBlock('span', {
text: value,
lang,
functionType: 'codeContent'
})
this.appendChild(codeBlock, codeContent)
} else {
const emptyCodeContent = this.createBlock('span', {
functionType: 'codeContent',
lang
})
this.appendChild(codeBlock, emptyCodeContent)
}
const preview = this.createBlock('div', {
editable: false,
functionType
})
return { preBlock, preview }
}
ContentState.prototype.initContainerBlock = function (functionType, block, style = undefined) { // p block
block.type = 'figure'
block.functionType = functionType
block.children = []
if (functionType === 'multiplemath') {
if (style === undefined) {
block.mathStyle = this.isGitlabCompatibilityEnabled ? 'gitlab' : ''
}
block.mathStyle = style
}
const { preBlock, preview } = this.createPreAndPreview(functionType)
this.appendChild(block, preBlock)
this.appendChild(block, preview)
return preBlock.children[0].children[0]
}
ContentState.prototype.handleContainerBlockClick = function (figureEle) {
const { id } = figureEle
const mathBlock = this.getBlock(id)
const preBlock = mathBlock.children[0]
const firstLine = preBlock.children[0].children[0]
const { key } = firstLine
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.partialRender()
}
ContentState.prototype.updateMathBlock = function (block) {
const functionType = 'multiplemath'
const { type } = block
// TODO(GitLab): Allow "functionType" 'languageInput' to convert an existing
// code block into math block.
if (type === 'span' && block.functionType === 'paragraphContent') {
const isMathBlock = !!block.text.match(/^`{3,}math\s*/)
if (isMathBlock) {
const result = this.initContainerBlock(functionType, block, 'gitlab')
if (result) {
// Set cursor at the first line
const { key } = result
const offset = 0
this.cursor = {
start: { key, offset },
end: { key, offset }
}
// Force render
this.partialRender()
return result
}
}
return false
} else if (type !== 'p') {
return false
}
const { text } = block.children[0]
return text.trim() === '$$' ? this.initContainerBlock(functionType, block, '') : false
}
}
export default containerCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/updateCtrl.js | src/muya/lib/contentState/updateCtrl.js | import { tokenizer } from '../parser/'
import { conflict } from '../utils'
const INLINE_UPDATE_FRAGMENTS = [
'(?:^|\n) {0,3}([*+-] {1,4})', // Bullet list
'(?:^|\n)(\\[[x ]{1}\\] {1,4})', // Task list
'(?:^|\n) {0,3}(\\d{1,9}(?:\\.|\\)) {1,4})', // Order list
'(?:^|\n) {0,3}(#{1,6})(?=\\s{1,}|$)', // ATX headings
'^(?:[\\s\\S]+?)\\n {0,3}(\\={3,}|\\-{3,})(?= {1,}|$)', // Setext headings **match from beginning**
'(?:^|\n) {0,3}(>).+', // Block quote
'^( {4,})', // Indent code **match from beginning**
'^(\\[\\^[^\\^\\[\\]\\s]+?(?<!\\\\)\\]: )', // Footnote **match from beginning**
'(?:^|\n) {0,3}((?:\\* *\\* *\\*|- *- *-|_ *_ *_)[ \\*\\-\\_]*)$' // Thematic break
]
const INLINE_UPDATE_REG = new RegExp(INLINE_UPDATE_FRAGMENTS.join('|'), 'i')
const updateCtrl = ContentState => {
ContentState.prototype.checkSameMarkerOrDelimiter = function (list, markerOrDelimiter) {
if (!/ol|ul/.test(list.type)) return false
return list.children[0].bulletMarkerOrDelimiter === markerOrDelimiter
}
ContentState.prototype.checkNeedRender = function (cursor = this.cursor) {
const { labels } = this.stateRender
const { start: cStart, end: cEnd, anchor, focus } = cursor
const startBlock = this.getBlock(cStart ? cStart.key : anchor.key)
const endBlock = this.getBlock(cEnd ? cEnd.key : focus.key)
const startOffset = cStart ? cStart.offset : anchor.offset
const endOffset = cEnd ? cEnd.offset : focus.offset
const NO_NEED_TOKEN_REG = /text|hard_line_break|soft_line_break/
for (const token of tokenizer(startBlock.text, {
labels,
options: this.muya.options
})) {
if (NO_NEED_TOKEN_REG.test(token.type)) continue
const { start, end } = token.range
const textLen = startBlock.text.length
if (
conflict([Math.max(0, start - 1), Math.min(textLen, end + 1)], [startOffset, startOffset])
) {
return true
}
}
for (const token of tokenizer(endBlock.text, {
labels,
options: this.muya.options
})) {
if (NO_NEED_TOKEN_REG.test(token.type)) continue
const { start, end } = token.range
const textLen = endBlock.text.length
if (
conflict([Math.max(0, start - 1), Math.min(textLen, end + 1)], [endOffset, endOffset])
) {
return true
}
}
return false
}
/**
* block must be span block.
*/
ContentState.prototype.checkInlineUpdate = function (block) {
// table cell can not have blocks in it
if (/figure/.test(block.type)) {
return false
}
if (/cellContent|codeContent|languageInput|footnoteInput/.test(block.functionType)) {
return false
}
let line = null
const { text } = block
if (block.type === 'span') {
line = block
block = this.getParent(block)
}
const listItem = this.getParent(block)
const [
match, bullet, tasklist, order, atxHeader,
setextHeader, blockquote, indentCode, footnote, hr
] = text.match(INLINE_UPDATE_REG) || []
const { footnote: isSupportFootnote } = this.muya.options
switch (true) {
case (!!hr && new Set(hr.split('').filter(i => /\S/.test(i))).size === 1):
return this.updateThematicBreak(block, hr, line)
case !!bullet:
return this.updateList(block, 'bullet', bullet, line)
// only `bullet` list item can be update to `task` list item
case !!tasklist && listItem && listItem.listItemType === 'bullet':
return this.updateTaskListItem(block, 'tasklist', tasklist)
case !!order:
return this.updateList(block, 'order', order, line)
case !!atxHeader:
return this.updateAtxHeader(block, atxHeader, line)
case !!setextHeader:
return this.updateSetextHeader(block, setextHeader, line)
case !!blockquote:
return this.updateBlockQuote(block, line)
case !!indentCode:
return this.updateIndentCode(block, line)
case !!footnote && block.type === 'p' && !block.parent && isSupportFootnote:
return this.updateFootnote(block, line)
case !match:
default:
return this.updateToParagraph(block, line)
}
}
// Thematic break
ContentState.prototype.updateThematicBreak = function (block, marker, line) {
// If the block is already thematic break, no need to update.
if (block.type === 'hr') return null
const text = line.text
const lines = text.split('\n')
const preParagraphLines = []
let thematicLine = ''
const postParagraphLines = []
let thematicLineHasPushed = false
for (const l of lines) {
/* eslint-disable no-useless-escape */
if (/ {0,3}(?:\* *\* *\*|- *- *-|_ *_ *_)[ \*\-\_]*$/.test(l) && !thematicLineHasPushed) {
/* eslint-enable no-useless-escape */
thematicLine = l
thematicLineHasPushed = true
} else if (!thematicLineHasPushed) {
preParagraphLines.push(l)
} else {
postParagraphLines.push(l)
}
}
const thematicBlock = this.createBlock('hr')
const thematicLineBlock = this.createBlock('span', {
text: thematicLine,
functionType: 'thematicBreakLine'
})
this.appendChild(thematicBlock, thematicLineBlock)
this.insertBefore(thematicBlock, block)
if (preParagraphLines.length) {
const preBlock = this.createBlockP(preParagraphLines.join('\n'))
this.insertBefore(preBlock, thematicBlock)
}
if (postParagraphLines.length) {
const postBlock = this.createBlockP(postParagraphLines.join('\n'))
this.insertAfter(postBlock, thematicBlock)
}
this.removeBlock(block)
const { start, end } = this.cursor
const key = thematicBlock.children[0].key
const preParagraphLength = preParagraphLines.reduce((acc, i) => acc + i.length + 1, 0) // Add one, because the `\n`
const startOffset = start.offset - preParagraphLength
const endOffset = end.offset - preParagraphLength
this.cursor = {
start: { key, offset: startOffset },
end: { key, offset: endOffset }
}
return thematicBlock
}
ContentState.prototype.updateList = function (block, type, marker = '', line) {
const cleanMarker = marker ? marker.trim() : null
const { preferLooseListItem } = this.muya.options
const wrapperTag = type === 'order' ? 'ol' : 'ul' // `bullet` => `ul` and `order` => `ol`
const { start, end } = this.cursor
const startOffset = start.offset
const endOffset = end.offset
const newListItemBlock = this.createBlock('li')
const LIST_ITEM_REG = /^ {0,3}(?:[*+-]|\d{1,9}(?:\.|\))) {0,4}/
const text = line.text
const lines = text.split('\n')
const preParagraphLines = []
let listItemLines = []
let isPushedListItemLine = false
if (marker) {
for (const l of lines) {
if (LIST_ITEM_REG.test(l) && !isPushedListItemLine) {
listItemLines.push(l.replace(LIST_ITEM_REG, ''))
isPushedListItemLine = true
} else if (!isPushedListItemLine) {
preParagraphLines.push(l)
} else {
listItemLines.push(l)
}
}
} else {
// From front menu click.
listItemLines = lines
}
const pBlock = this.createBlockP(listItemLines.join('\n'))
this.insertBefore(pBlock, block)
if (preParagraphLines.length > 0) {
const preParagraphBlock = this.createBlockP(preParagraphLines.join('\n'))
this.insertBefore(preParagraphBlock, pBlock)
}
this.removeBlock(block)
// important!
block = pBlock
const preSibling = this.getPreSibling(block)
const nextSibling = this.getNextSibling(block)
newListItemBlock.listItemType = type
newListItemBlock.isLooseListItem = preferLooseListItem
let bulletMarkerOrDelimiter
if (type === 'order') {
bulletMarkerOrDelimiter = (cleanMarker && cleanMarker.length >= 2) ? cleanMarker.slice(-1) : '.'
} else {
const { bulletListMarker } = this.muya.options
bulletMarkerOrDelimiter = marker ? marker.charAt(0) : bulletListMarker
}
newListItemBlock.bulletMarkerOrDelimiter = bulletMarkerOrDelimiter
// Special cases for CommonMark 264 and 265: Changing the bullet or ordered list delimiter starts a new list.
// Same list type or new list
if (
preSibling &&
this.checkSameMarkerOrDelimiter(preSibling, bulletMarkerOrDelimiter) &&
nextSibling &&
this.checkSameMarkerOrDelimiter(nextSibling, bulletMarkerOrDelimiter)
) {
this.appendChild(preSibling, newListItemBlock)
const partChildren = nextSibling.children.splice(0)
partChildren.forEach(b => this.appendChild(preSibling, b))
this.removeBlock(nextSibling)
this.removeBlock(block)
const isLooseListItem = preSibling.children.some(c => c.isLooseListItem)
preSibling.children.forEach(c => (c.isLooseListItem = isLooseListItem))
} else if (
preSibling &&
this.checkSameMarkerOrDelimiter(preSibling, bulletMarkerOrDelimiter)
) {
this.appendChild(preSibling, newListItemBlock)
this.removeBlock(block)
const isLooseListItem = preSibling.children.some(c => c.isLooseListItem)
preSibling.children.forEach(c => (c.isLooseListItem = isLooseListItem))
} else if (
nextSibling &&
this.checkSameMarkerOrDelimiter(nextSibling, bulletMarkerOrDelimiter)
) {
this.insertBefore(newListItemBlock, nextSibling.children[0])
this.removeBlock(block)
const isLooseListItem = nextSibling.children.some(c => c.isLooseListItem)
nextSibling.children.forEach(c => (c.isLooseListItem = isLooseListItem))
} else {
// Create a new list when changing list type, bullet or list delimiter
const listBlock = this.createBlock(wrapperTag, {
listType: type
})
if (wrapperTag === 'ol') {
const start = cleanMarker ? cleanMarker.slice(0, -1) : 1
listBlock.start = /^\d+$/.test(start) ? start : 1
}
this.appendChild(listBlock, newListItemBlock)
this.insertBefore(listBlock, block)
this.removeBlock(block)
}
// key point
this.appendChild(newListItemBlock, block)
const TASK_LIST_REG = /^\[[x ]\] {1,4}/i
const listItemText = block.children[0].text
const { key } = block.children[0]
const delta = marker.length + preParagraphLines.join('\n').length + 1
this.cursor = {
start: {
key,
offset: Math.max(0, startOffset - delta)
},
end: {
key,
offset: Math.max(0, endOffset - delta)
}
}
if (TASK_LIST_REG.test(listItemText)) {
const [, , tasklist, , , ,] = listItemText.match(INLINE_UPDATE_REG) || [] // eslint-disable-line comma-spacing
return this.updateTaskListItem(block, 'tasklist', tasklist)
} else {
return block
}
}
ContentState.prototype.updateTaskListItem = function (block, type, marker = '') {
const { preferLooseListItem } = this.muya.options
const parent = this.getParent(block)
const grandpa = this.getParent(parent)
const checked = /\[x\]\s/i.test(marker) // use `i` flag to ignore upper case or lower case
const checkbox = this.createBlock('input', {
checked
})
const { start, end } = this.cursor
this.insertBefore(checkbox, block)
block.children[0].text = block.children[0].text.substring(marker.length)
parent.listItemType = 'task'
parent.isLooseListItem = preferLooseListItem
let taskListWrapper
if (this.isOnlyChild(parent)) {
grandpa.listType = 'task'
} else if (this.isFirstChild(parent) || this.isLastChild(parent)) {
taskListWrapper = this.createBlock('ul', {
listType: 'task'
})
this.isFirstChild(parent) ? this.insertBefore(taskListWrapper, grandpa) : this.insertAfter(taskListWrapper, grandpa)
this.removeBlock(parent)
this.appendChild(taskListWrapper, parent)
} else {
taskListWrapper = this.createBlock('ul', {
listType: 'task'
})
const bulletListWrapper = this.createBlock('ul', {
listType: 'bullet'
})
let preSibling = this.getPreSibling(parent)
while (preSibling) {
this.removeBlock(preSibling)
if (bulletListWrapper.children.length) {
const firstChild = bulletListWrapper.children[0]
this.insertBefore(preSibling, firstChild)
} else {
this.appendChild(bulletListWrapper, preSibling)
}
preSibling = this.getPreSibling(preSibling)
}
this.removeBlock(parent)
this.appendChild(taskListWrapper, parent)
this.insertBefore(taskListWrapper, grandpa)
this.insertBefore(bulletListWrapper, taskListWrapper)
}
this.cursor = {
start: {
key: start.key,
offset: Math.max(0, start.offset - marker.length)
},
end: {
key: end.key,
offset: Math.max(0, end.offset - marker.length)
}
}
return taskListWrapper || grandpa
}
// ATX heading doesn't support soft line break and hard line break.
ContentState.prototype.updateAtxHeader = function (block, header, line) {
const newType = `h${header.length}`
const headingStyle = 'atx'
if (block.type === newType && block.headingStyle === headingStyle) {
return null
}
const text = line.text
const lines = text.split('\n')
const preParagraphLines = []
let atxLine = ''
const postParagraphLines = []
let atxLineHasPushed = false
for (const l of lines) {
if (/^ {0,3}#{1,6}(?=\s{1,}|$)/.test(l) && !atxLineHasPushed) {
atxLine = l
atxLineHasPushed = true
} else if (!atxLineHasPushed) {
preParagraphLines.push(l)
} else {
postParagraphLines.push(l)
}
}
const atxBlock = this.createBlock(newType, {
headingStyle
})
const atxLineBlock = this.createBlock('span', {
text: atxLine,
functionType: 'atxLine'
})
this.appendChild(atxBlock, atxLineBlock)
this.insertBefore(atxBlock, block)
if (preParagraphLines.length) {
const preBlock = this.createBlockP(preParagraphLines.join('\n'))
this.insertBefore(preBlock, atxBlock)
}
if (postParagraphLines.length) {
const postBlock = this.createBlockP(postParagraphLines.join('\n'))
this.insertAfter(postBlock, atxBlock)
}
this.removeBlock(block)
const { start, end } = this.cursor
const key = atxBlock.children[0].key
this.cursor = {
start: { key, offset: start.offset },
end: { key, offset: end.offset }
}
return atxBlock
}
ContentState.prototype.updateSetextHeader = function (block, marker, line) {
const newType = /=/.test(marker) ? 'h1' : 'h2'
const headingStyle = 'setext'
if (block.type === newType && block.headingStyle === headingStyle) {
return null
}
const text = line.text
const lines = text.split('\n')
const setextLines = []
const postParagraphLines = []
let setextLineHasPushed = false
for (const l of lines) {
if (/^ {0,3}(?:={3,}|-{3,})(?= {1,}|$)/.test(l) && !setextLineHasPushed) {
setextLineHasPushed = true
} else if (!setextLineHasPushed) {
setextLines.push(l)
} else {
postParagraphLines.push(l)
}
}
const setextBlock = this.createBlock(newType, {
headingStyle,
marker
})
const setextLineBlock = this.createBlock('span', {
text: setextLines.join('\n'),
functionType: 'paragraphContent'
})
this.appendChild(setextBlock, setextLineBlock)
this.insertBefore(setextBlock, block)
if (postParagraphLines.length) {
const postBlock = this.createBlockP(postParagraphLines.join('\n'))
this.insertAfter(postBlock, setextBlock)
}
this.removeBlock(block)
const key = setextBlock.children[0].key
const offset = setextBlock.children[0].text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
return setextBlock
}
ContentState.prototype.updateBlockQuote = function (block, line) {
const text = line.text
const lines = text.split('\n')
const preParagraphLines = []
const quoteLines = []
let quoteLinesHasPushed = false
for (const l of lines) {
if (/^ {0,3}>/.test(l) && !quoteLinesHasPushed) {
quoteLinesHasPushed = true
quoteLines.push(l.trimStart().substring(1).trimStart())
} else if (!quoteLinesHasPushed) {
preParagraphLines.push(l)
} else {
quoteLines.push(l)
}
}
let quoteParagraphBlock
if (/^h\d/.test(block.type)) {
quoteParagraphBlock = this.createBlock(block.type, {
headingStyle: block.headingStyle
})
if (block.headingStyle === 'setext') {
quoteParagraphBlock.marker = block.marker
}
const headerContent = this.createBlock('span', {
text: quoteLines.join('\n'),
functionType: block.headingStyle === 'setext' ? 'paragraphContent' : 'atxLine'
})
this.appendChild(quoteParagraphBlock, headerContent)
} else {
quoteParagraphBlock = this.createBlockP(quoteLines.join('\n'))
}
const quoteBlock = this.createBlock('blockquote')
this.appendChild(quoteBlock, quoteParagraphBlock)
this.insertBefore(quoteBlock, block)
if (preParagraphLines.length) {
const preParagraphBlock = this.createBlockP(preParagraphLines.join('\n'))
this.insertBefore(preParagraphBlock, quoteBlock)
}
this.removeBlock(block)
const key = quoteParagraphBlock.children[0].key
const { start, end } = this.cursor
this.cursor = {
start: { key, offset: Math.max(0, start.offset - 1) },
end: { key, offset: Math.max(0, end.offset - 1) }
}
return quoteBlock
}
ContentState.prototype.updateIndentCode = function (block, line) {
const lang = ''
const codeBlock = this.createBlock('code', {
lang
})
const inputBlock = this.createBlock('span', {
functionType: 'languageInput'
})
const preBlock = this.createBlock('pre', {
functionType: 'indentcode',
lang
})
const text = line ? line.text : block.text
const lines = text.split('\n')
const codeLines = []
const paragraphLines = []
let canBeCodeLine = true
for (const l of lines) {
if (/^ {4,}/.test(l) && canBeCodeLine) {
codeLines.push(l.replace(/^ {4}/, ''))
} else {
canBeCodeLine = false
paragraphLines.push(l)
}
}
const codeContent = this.createBlock('span', {
text: codeLines.join('\n'),
functionType: 'codeContent',
lang
})
this.appendChild(codeBlock, codeContent)
this.appendChild(preBlock, inputBlock)
this.appendChild(preBlock, codeBlock)
this.insertBefore(preBlock, block)
if (paragraphLines.length > 0 && line) {
const newLine = this.createBlock('span', {
text: paragraphLines.join('\n')
})
this.insertBefore(newLine, line)
this.removeBlock(line)
} else {
this.removeBlock(block)
}
const key = codeBlock.children[0].key
const { start, end } = this.cursor
this.cursor = {
start: { key, offset: start.offset - 4 },
end: { key, offset: end.offset - 4 }
}
return preBlock
}
ContentState.prototype.updateToParagraph = function (block, line) {
if (/^h\d$/.test(block.type) && block.headingStyle === 'setext') {
return null
}
const newType = 'p'
if (block.type !== newType) {
const newBlock = this.createBlockP(line.text)
this.insertBefore(newBlock, block)
this.removeBlock(block)
const { start, end } = this.cursor
const key = newBlock.children[0].key
this.cursor = {
start: { key, offset: start.offset },
end: { key, offset: end.offset }
}
return block
}
return null
}
}
export default updateCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/contentState/inputCtrl.js | src/muya/lib/contentState/inputCtrl.js | import selection from '../selection'
import { getTextContent } from '../selection/dom'
import { beginRules } from '../parser/rules'
import { tokenizer } from '../parser/'
import { CLASS_OR_ID } from '../config'
const BRACKET_HASH = {
'{': '}',
'[': ']',
'(': ')',
'*': '*',
_: '_',
'"': '"',
'\'': '\'',
$: '$',
'~': '~'
}
const BACK_HASH = {
'}': '{',
']': '[',
')': '(',
'*': '*',
_: '_',
'"': '"',
'\'': '\'',
$: '$',
'~': '~'
}
// TODO: refactor later.
let renderCodeBlockTimer = null
const inputCtrl = ContentState => {
// Input @ to quick insert paragraph
ContentState.prototype.checkQuickInsert = function (block) {
const { type, text, functionType } = block
if (type !== 'span' || functionType !== 'paragraphContent') return false
return /^@\S*$/.test(text)
}
ContentState.prototype.checkCursorInTokenType = function (functionType, text, offset, type) {
if (!/atxLine|paragraphContent|cellContent/.test(functionType)) {
return false
}
const tokens = tokenizer(text, {
hasBeginRules: false,
options: this.muya.options
})
return tokens.filter(t => t.type === type).some(t => offset >= t.range.start && offset <= t.range.end)
}
ContentState.prototype.checkNotSameToken = function (functionType, oldText, text) {
if (!/atxLine|paragraphContent|cellContent/.test(functionType)) {
return false
}
const oldTokens = tokenizer(oldText, {
options: this.muya.options
})
const tokens = tokenizer(text, {
options: this.muya.options
})
const oldCache = {}
const cache = {}
for (const { type } of oldTokens) {
if (oldCache[type]) {
oldCache[type]++
} else {
oldCache[type] = 1
}
}
for (const { type } of tokens) {
if (cache[type]) {
cache[type]++
} else {
cache[type] = 1
}
}
if (Object.keys(oldCache).length !== Object.keys(cache).length) {
return true
}
for (const key of Object.keys(oldCache)) {
if (!cache[key] || oldCache[key] !== cache[key]) {
return true
}
}
return false
}
ContentState.prototype.inputHandler = function (event, notEqual = false) {
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
const { start: oldStart, end: oldEnd } = this.cursor
const key = start.key
const block = this.getBlock(key)
const paragraph = document.querySelector(`#${key}`)
// Fix issue 1447
// Fixme: any better solution?
if (
oldStart.key === oldEnd.key &&
oldStart.offset === oldEnd.offset &&
block.text.endsWith('\n') &&
oldStart.offset === block.text.length &&
event.inputType === 'insertText'
) {
event.preventDefault()
block.text += event.data
const offset = block.text.length
this.cursor = {
start: { key, offset },
end: { key, offset }
}
this.singleRender(block)
return this.inputHandler(event, true)
}
let text = getTextContent(paragraph, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER])
let needRender = false
let needRenderAll = false
if (oldStart.key !== oldEnd.key) {
const startBlock = this.getBlock(oldStart.key)
const startOutmostBlock = this.findOutMostBlock(startBlock)
const endBlock = this.getBlock(oldEnd.key)
const endOutmostBlock = this.findOutMostBlock(endBlock)
if (startBlock.functionType === 'languageInput') {
// fix #918.
if (startOutmostBlock === endOutmostBlock && !endBlock.nextSibling) {
this.removeBlocks(startBlock, endBlock, false)
endBlock.text = ''
} else if (startOutmostBlock !== endOutmostBlock) {
const preBlock = this.getParent(startBlock)
const pBlock = this.createBlock('p')
this.removeBlocks(startBlock, endBlock)
startBlock.functionType = 'paragraphContent'
this.appendChild(pBlock, startBlock)
this.insertBefore(pBlock, preBlock)
this.removeBlock(preBlock)
} else {
this.removeBlocks(startBlock, endBlock)
}
} else if (startBlock.functionType === 'paragraphContent' &&
start.key === end.key && oldStart.key === start.key && oldEnd.key !== end.key) {
// GH#2269: The end block will lose all soft-lines when removing multiple paragraphs and `oldEnd`
// includes soft-line breaks. The normal text from `oldEnd` is moved into the `start`
// block but the remaining soft-lines (separated by \n) not. We have to append the
// remaining text (soft-lines) to the new start block.
const matchBreak = /(?<=.)\n./.exec(endBlock.text)
if (matchBreak && matchBreak.index > 0) {
// Skip if end block is fully selected and the cursor is in the next line (e.g. via keyboard).
const lineOffset = matchBreak.index
if (oldEnd.offset <= lineOffset) {
text += endBlock.text.substring(lineOffset)
}
}
this.removeBlocks(startBlock, endBlock)
} else {
this.removeBlocks(startBlock, endBlock)
}
if (this.blocks.length === 1) {
needRenderAll = true
}
needRender = true
}
// auto pair (not need to auto pair in math block)
if (block && (block.text !== text || notEqual)) {
if (
start.key === end.key &&
start.offset === end.offset &&
event.type === 'input'
) {
const { offset } = start
const { autoPairBracket, autoPairMarkdownSyntax, autoPairQuote } = this.muya.options
const inputChar = text.charAt(+offset - 1)
const preInputChar = text.charAt(+offset - 2)
const prePreInputChar = text.charAt(+offset - 3)
const postInputChar = text.charAt(+offset)
if (/^delete/.test(event.inputType)) {
// handle `deleteContentBackward` or `deleteContentForward`
const deletedChar = block.text[offset]
if (event.inputType === 'deleteContentBackward' && postInputChar === BRACKET_HASH[deletedChar]) {
needRender = true
text = text.substring(0, offset) + text.substring(offset + 1)
}
if (event.inputType === 'deleteContentForward' && inputChar === BACK_HASH[deletedChar]) {
needRender = true
start.offset -= 1
end.offset -= 1
text = text.substring(0, offset - 1) + text.substring(offset)
}
/* eslint-disable no-useless-escape */
} else if (
(event.inputType.indexOf('delete') === -1) &&
(inputChar === postInputChar) &&
(
(autoPairQuote && /[']{1}/.test(inputChar)) ||
(autoPairQuote && /["]{1}/.test(inputChar)) ||
(autoPairBracket && /[\}\]\)]{1}/.test(inputChar)) ||
(autoPairMarkdownSyntax && /[$]{1}/.test(inputChar)) ||
(autoPairMarkdownSyntax && /[*$`~_]{1}/.test(inputChar)) && /[_*~]{1}/.test(prePreInputChar)
)
) {
needRender = true
text = text.substring(0, offset) + text.substring(offset + 1)
} else {
/* eslint-disable no-useless-escape */
// Not Unicode aware, since things like \p{Alphabetic} or \p{L} are not supported yet
const isInInlineMath = this.checkCursorInTokenType(block.functionType, text, offset, 'inline_math')
const isInInlineCode = this.checkCursorInTokenType(block.functionType, text, offset, 'inline_code')
if (
// Issue 2566: Do not complete markdown syntax if the previous character is
// alphanumeric.
!/\\/.test(preInputChar) &&
((autoPairQuote && /[']{1}/.test(inputChar) && !(/[\S]{1}/.test(postInputChar)) && !(/[a-zA-Z\d]{1}/.test(preInputChar))) ||
(autoPairQuote && /["]{1}/.test(inputChar) && !(/[\S]{1}/.test(postInputChar))) ||
(autoPairBracket && /[\{\[\(]{1}/.test(inputChar) && !(/[\S]{1}/.test(postInputChar))) ||
(block.functionType !== 'codeContent' && !isInInlineMath && !isInInlineCode && autoPairMarkdownSyntax && !/[a-z0-9]{1}/i.test(preInputChar) && /[*$`~_]{1}/.test(inputChar)))
) {
needRender = true
text = BRACKET_HASH[event.data]
? text.substring(0, offset) + BRACKET_HASH[inputChar] + text.substring(offset)
: text
}
/* eslint-enable no-useless-escape */
// Delete the last `*` of `**` when you insert one space between `**` to create a bullet list.
if (
/\s/.test(event.data) &&
/^\* /.test(text) &&
preInputChar === '*' &&
postInputChar === '*'
) {
text = text.substring(0, offset) + text.substring(offset + 1)
needRender = true
}
}
}
if (this.checkNotSameToken(block.functionType, block.text, text)) {
needRender = true
}
// Just work for `Shift + Enter` to create a soft and hard line break.
if (
block.text.endsWith('\n') &&
start.offset === text.length &&
(event.inputType === 'insertText' || event.type === 'compositionend')
) {
block.text += event.data
start.offset++
end.offset++
} else if (
block.text.length === oldStart.offset &&
block.text[oldStart.offset - 2] === '\n' &&
event.inputType === 'deleteContentBackward'
) {
block.text = block.text.substring(0, oldStart.offset - 1)
start.offset = block.text.length
end.offset = block.text.length
} else {
block.text = text
}
// Update code block language when modify code block identifer
if (block.functionType === 'languageInput') {
const parent = this.getParent(block)
parent.lang = block.text
}
if (beginRules.reference_definition.test(text)) {
needRenderAll = true
}
}
// show quick insert
const rect = paragraph.getBoundingClientRect()
const checkQuickInsert = this.checkQuickInsert(block)
const reference = this.getPositionReference()
reference.getBoundingClientRect = function () {
const { x, y, left, top, height, bottom } = rect
return Object.assign({}, {
left,
x,
top,
y,
bottom,
height,
width: 0,
right: left
})
}
this.muya.eventCenter.dispatch('muya-quick-insert', reference, block, !!checkQuickInsert)
this.cursor = { start, end }
// Throttle render if edit in code block.
if (block && block.type === 'span' && block.functionType === 'codeContent') {
if (renderCodeBlockTimer) {
clearTimeout(renderCodeBlockTimer)
}
if (needRender) {
this.partialRender()
} else {
renderCodeBlockTimer = setTimeout(() => {
this.partialRender()
}, 300)
}
return
}
const checkMarkedUpdate = /atxLine|paragraphContent|cellContent/.test(block.functionType)
? this.checkNeedRender()
: false
let inlineUpdatedBlock = null
if (/atxLine|paragraphContent|cellContent|thematicBreakLine/.test(block.functionType)) {
inlineUpdatedBlock = this.isCollapse() && this.checkInlineUpdate(block)
}
// just for fix #707,need render All if in combines pre list and next list into one list.
if (inlineUpdatedBlock) {
const liBlock = this.getParent(inlineUpdatedBlock)
if (liBlock && liBlock.type === 'li' && liBlock.preSibling && liBlock.nextSibling) {
needRenderAll = true
}
}
if (checkMarkedUpdate || inlineUpdatedBlock || needRender) {
return needRenderAll ? this.render() : this.partialRender()
}
}
}
export default inputCtrl
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/prism/index.js | src/muya/lib/prism/index.js | import Prism from 'prismjs'
import { filter } from 'fuzzaldrin'
import initLoadLanguage, { loadedLanguages, transformAliasToOrigin } from './loadLanguage'
import { languages } from 'prismjs/components.js'
const prism = Prism
window.Prism = Prism
/* eslint-disable */
import('prismjs/plugins/keep-markup/prism-keep-markup')
/* eslint-enable */
const langs = []
for (const name of Object.keys(languages)) {
const lang = languages[name]
langs.push({
name,
...lang
})
if (lang.alias) {
if (typeof lang.alias === 'string') {
langs.push({
name: lang.alias,
...lang
})
} else if (Array.isArray(lang.alias)) {
langs.push(...lang.alias.map(a => ({
name: a,
...lang
})))
}
}
}
const loadLanguage = initLoadLanguage(Prism)
const search = text => {
return filter(langs, text, { key: 'name' })
}
// pre load latex and yaml and html for `math block` \ `front matter` and `html block`
loadLanguage('latex')
loadLanguage('yaml')
export {
search,
loadLanguage,
loadedLanguages,
transformAliasToOrigin
}
export default prism
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/prism/loadLanguage.js | src/muya/lib/prism/loadLanguage.js | import components from 'prismjs/components.js'
import getLoader from 'prismjs/dependencies'
import { getDefer } from '../utils'
/**
* The set of all languages which have been loaded using the below function.
*
* @type {Set<string>}
*/
export const loadedLanguages = new Set(['markup', 'css', 'clike', 'javascript'])
const { languages } = components
// Look for the origin languge by alias
export const transformAliasToOrigin = langs => {
const result = []
for (const lang of langs) {
if (languages[lang]) {
result.push(lang)
} else {
const language = Object.keys(languages).find(name => {
const l = languages[name]
if (l.alias) {
return l.alias === lang || Array.isArray(l.alias) && l.alias.includes(lang)
}
return false
})
if (language) {
result.push(language)
} else {
// The lang is not exist, the will handle in `initLoadLanguage`
result.push(lang)
}
}
}
return result
}
function initLoadLanguage (Prism) {
return async function loadLanguages (langs) {
// If no argument is passed, load all components
if (!langs) {
langs = Object.keys(languages).filter(lang => lang !== 'meta')
}
if (langs && !langs.length) {
return Promise.reject(new Error('The first parameter should be a list of load languages or single language.'))
}
if (!Array.isArray(langs)) {
langs = [langs]
}
const promises = []
// The user might have loaded languages via some other way or used `prism.js` which already includes some
// We don't need to validate the ids because `getLoader` will ignore invalid ones
const loaded = [...loadedLanguages, ...Object.keys(Prism.languages)]
getLoader(components, langs, loaded).load(async lang => {
const defer = getDefer()
promises.push(defer.promise)
if (!(lang in components.languages)) {
defer.resolve({
lang,
status: 'noexist'
})
} else if (loadedLanguages.has(lang)) {
defer.resolve({
lang,
status: 'cached'
})
} else {
delete Prism.languages[lang]
await import('prismjs/components/prism-' + lang)
defer.resolve({
lang,
status: 'loaded'
})
loadedLanguages.add(lang)
}
})
return Promise.all(promises)
}
}
export default initLoadLanguage
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/renderers/index.js | src/muya/lib/renderers/index.js | const rendererCache = new Map()
/**
*
* @param {string} name the renderer name: katex, sequence, plantuml, flowchart, mermaid, vega-lite
*/
const loadRenderer = async (name) => {
if (!rendererCache.has(name)) {
let m
switch (name) {
case 'sequence':
m = await import('../parser/render/sequence')
rendererCache.set(name, m.default)
break
case 'plantuml':
m = await import('../parser/render/plantuml')
rendererCache.set(name, m.default)
break
case 'flowchart':
m = await import('flowchart.js')
rendererCache.set(name, m.default)
break
case 'mermaid':
m = await import('mermaid/dist/mermaid.core.mjs')
rendererCache.set(name, m.default)
break
case 'vega-lite':
m = await import('vega-embed')
rendererCache.set(name, m.default)
break
default:
throw new Error(`Unknown diagram name ${name}`)
}
}
return rendererCache.get(name)
}
export default loadRenderer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/marktext/spellchecker.js | src/muya/lib/marktext/spellchecker.js | // __MARKTEXT_ONLY__
import { deepClone } from '../utils'
// Source: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/common/model/wordHelper.ts
// /(-?\d*\.\d\w*)|([^\`\~\!\@\#\$\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/
/* eslint-disable no-useless-escape */
const WORD_SEPARATORS = /(?:[`~!@#$%^&*()-=+[{\]}\\|;:'",\.<>\/?\s])/g
const WORD_DEFINITION = /(?:-?\d*\.\d\w*)|(?:[^`~!@#$%^&*()-=+[{\]}\\|;:'",\.<>\/?\s]+)/g
/* eslint-enable no-useless-escape */
/**
* Translate a left and right offset from a word in `line` into a cursor with
* the given line cursor.
*
* @param {*} lineCursor The original line cursor.
* @param {number} left Start offset/index of word in `lineCursor`.
* @param {number} right End offset/index of word in `lineCursor`.
* @returns {*} Return a cursor of the word selected in `lineCursor`(e.g.
* "foo >bar< foo" where `>`/`<` start and end offset).
*/
export const offsetToWordCursor = (lineCursor, left, right) => {
// Deep clone cursor start and end
const start = deepClone(lineCursor.start)
const end = deepClone(lineCursor.end)
start.offset = left
end.offset = right
return { start, end }
}
/**
* Validate whether the selection is valid for spelling correction.
*
* @param {*} selection The preview editor selection range.
*/
export const validateLineCursor = selection => {
// Validate selection range.
if (!selection && !selection.start && !selection.start.hasOwnProperty('offset') &&
!selection.end && !selection.end.hasOwnProperty('offset')) {
return false
}
// Allow only single lines
const { start: startCursor, end: endCursor } = selection
if (startCursor.key !== endCursor.key || !startCursor.block) {
return false
}
// Don't correct words in code blocks or editors for HTML, LaTex and diagrams.
if (startCursor.block.functionType === 'codeContent' &&
startCursor.block.lang !== undefined) {
return false
}
// Don't correct words in code blocks or pre elements such as language identifier.
if (selection.affiliation && selection.affiliation.length === 1 &&
selection.affiliation[0].type === 'pre') {
return false
}
return true
}
/**
* Extract the word at the given offset from the text.
*
* @param {string} text Text
* @param {number} offset Normalized cursor offset (e.g. ab<cursor>c def --> 2)
*/
export const extractWord = (text, offset) => {
if (!text || text.length === 0) {
return null
} else if (offset < 0) {
offset = 0
} else if (offset >= text.length) {
offset = text.length - 1
}
// Matches all words starting at a good position.
WORD_DEFINITION.lastIndex = text.lastIndexOf(' ', offset - 1) + 1
let match = null
let left = -1
while (match = WORD_DEFINITION.exec(text)) { // eslint-disable-line
if (match && match.index <= offset) {
if (WORD_DEFINITION.lastIndex > offset) {
left = match.index
}
} else {
break
}
}
WORD_DEFINITION.lastIndex = 0
// Cursor is between two word separators (e.g "*<cursor>*" or " <cursor>*")
if (left <= -1) {
return null
}
// Find word ending.
WORD_SEPARATORS.lastIndex = offset
match = WORD_SEPARATORS.exec(text)
let right = -1
if (match) {
right = match.index
}
WORD_SEPARATORS.lastIndex = 0
// The last word in the string is a special case.
if (right < 0) {
return {
left,
right: text.length,
word: text.slice(left)
}
}
return {
left,
right: right,
word: text.slice(left, right)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/cumputeCheckBoxStatus.js | src/muya/lib/utils/cumputeCheckBoxStatus.js | export const cumputeCheckboxStatus = function (parentCheckbox) {
const children = parentCheckbox.parentElement.lastElementChild.children
const len = children.length
for (let i = 0; i < len; i++) {
const checkbox = children[i].firstElementChild
if (checkbox.checked === false) {
return false
}
}
return true
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/getLinkInfo.js | src/muya/lib/utils/getLinkInfo.js | import { findNearestParagraph } from '../selection/dom'
import { tokenizer } from '../parser'
export const getLinkInfo = a => {
const paragraph = findNearestParagraph(a)
const raw = a.getAttribute('data-raw')
const start = a.getAttribute('data-start')
const end = a.getAttribute('data-end')
const tokens = tokenizer(raw)
const token = tokens[0]
const href = a.getAttribute('href')
token.range = {
start,
end
}
return {
key: paragraph.id,
token,
href
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/getImageInfo.js | src/muya/lib/utils/getImageInfo.js | import { isWin } from '../config'
import { findNearestParagraph, getOffsetOfParagraph } from '../selection/dom'
import { tokenizer } from '../parser'
export const getImageInfo = image => {
const paragraph = findNearestParagraph(image)
const raw = image.getAttribute('data-raw')
const offset = getOffsetOfParagraph(image, paragraph)
const tokens = tokenizer(raw)
const token = tokens[0]
token.range = {
start: offset,
end: offset + raw.length
}
return {
key: paragraph.id,
token,
imageId: image.id
}
}
export const correctImageSrc = src => {
if (src) {
// Fix ASCII and UNC paths on Windows (#1997).
if (isWin && /^(?:[a-zA-Z]:\\|[a-zA-Z]:\/).+/.test(src)) {
src = 'file:///' + src.replace(/\\/g, '/')
} else if (isWin && /^\\\\\?\\.+/.test(src)) {
src = 'file:///' + src.substring(4).replace(/\\/g, '/')
} else if (/^\/.+/.test(src)) {
// Also adding file protocol on UNIX.
src = 'file://' + src
}
}
return src
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/index.js | src/muya/lib/utils/index.js | import runSanitize from './dompurify'
import { URL_REG, DATA_URL_REG, IMAGE_EXT_REG } from '../config'
export { getUniqueId, getLongUniqueId } from './random'
const TIMEOUT = 1500
const HTML_TAG_REPLACEMENTS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}
export const isMetaKey = ({ key }) => key === 'Shift' || key === 'Control' || key === 'Alt' || key === 'Meta'
export const noop = () => {}
export const identity = i => i
export const isOdd = number => Math.abs(number) % 2 === 1
export const isEven = number => Math.abs(number) % 2 === 0
export const isLengthEven = (str = '') => str.length % 2 === 0
export const snakeToCamel = name => name.replace(/_([a-z])/g, (p0, p1) => p1.toUpperCase())
export const camelToSnake = name => name.replace(/([A-Z])/g, (_, p) => `-${p.toLowerCase()}`)
/**
* Are two arrays have intersection
*/
export const conflict = (arr1, arr2) => {
return !(arr1[1] < arr2[0] || arr2[1] < arr1[0])
}
export const union = ({ start: tStart, end: tEnd }, { start: lStart, end: lEnd, active }) => {
if (!(tEnd <= lStart || lEnd <= tStart)) {
if (lStart < tStart) {
return {
start: tStart,
end: tEnd < lEnd ? tEnd : lEnd,
active
}
} else {
return {
start: lStart,
end: tEnd < lEnd ? tEnd : lEnd,
active
}
}
}
return null
}
// https://github.com/jashkenas/underscore
export const throttle = (func, wait = 50) => {
let context
let args
let result
let timeout = null
let previous = 0
const later = () => {
previous = Date.now()
timeout = null
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
}
return function () {
const now = Date.now()
const remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
result = func.apply(context, args)
if (!timeout) {
context = args = null
}
} else if (!timeout) {
timeout = setTimeout(later, remaining)
}
return result
}
}
// simple implementation...
export const debounce = (func, wait = 50) => {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func(...args)
}, wait)
}
}
export const deepCopyArray = array => {
const result = []
const len = array.length
let i
for (i = 0; i < len; i++) {
if (typeof array[i] === 'object' && array[i] !== null) {
if (Array.isArray(array[i])) {
result.push(deepCopyArray(array[i]))
} else {
result.push(deepCopy(array[i]))
}
} else {
result.push(array[i])
}
}
return result
}
// TODO: @jocs rewrite deepCopy
export const deepCopy = object => {
const obj = {}
Object.keys(object).forEach(key => {
if (typeof object[key] === 'object' && object[key] !== null) {
if (Array.isArray(object[key])) {
obj[key] = deepCopyArray(object[key])
} else {
obj[key] = deepCopy(object[key])
}
} else {
obj[key] = object[key]
}
})
return obj
}
export const loadImage = async (url, detectContentType = false) => {
if (detectContentType) {
const isImage = await checkImageContentType(url)
if (!isImage) throw new Error('not an image')
}
return new Promise((resolve, reject) => {
const image = new Image()
image.onload = () => {
resolve({
url,
width: image.width,
height: image.height
})
}
image.onerror = err => {
reject(err)
}
image.src = url
})
}
export const isOnline = () => {
return navigator.onLine === true
}
export const getPageTitle = url => {
// No need to request the title when it's not url.
if (!url.startsWith('http')) {
return ''
}
// No need to request the title when off line.
if (!isOnline()) {
return ''
}
const req = new XMLHttpRequest()
let settle
const promise = new Promise((resolve, reject) => {
settle = resolve
})
const handler = () => {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status === 200) {
const contentType = req.getResponseHeader('Content-Type')
if (/text\/html/.test(contentType)) {
const { response } = req
if (typeof response === 'string') {
const match = response.match(/<title>(.*)<\/title>/)
return match && match[1] ? settle(match[1]) : settle('')
}
return settle('')
}
return settle('')
} else {
return settle('')
}
}
}
const handleError = (e) => {
settle('')
}
req.open('GET', url)
req.onreadystatechange = handler
req.onerror = handleError
req.send()
// Resolve empty string when `TIMEOUT` passed.
const timer = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('')
}, TIMEOUT)
})
return Promise.race([promise, timer])
}
export const checkImageContentType = url => {
const req = new XMLHttpRequest()
let settle
const promise = new Promise((resolve, reject) => {
settle = resolve
})
const handler = () => {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status === 200) {
const contentType = req.getResponseHeader('Content-Type')
if (/^image\/(?:jpeg|png|gif|svg\+xml|webp)$/.test(contentType)) {
settle(true)
} else {
settle(false)
}
} else if (req.status === 405) { // status 405 means method not allowed, and just return true.(Solve issue#1297)
settle(true)
} else {
settle(false)
}
}
}
const handleError = () => {
settle(false)
}
req.open('HEAD', url)
req.onreadystatechange = handler
req.onerror = handleError
req.send()
return promise
}
/**
* Return image information and correct the relative image path if needed.
*
* @param {string} src Image url
* @param {string} baseUrl Base path; used on desktop to fix the relative image path.
*/
export const getImageInfo = (src, baseUrl = window.DIRNAME) => {
const imageExtension = IMAGE_EXT_REG.test(src)
const isUrl = URL_REG.test(src) || (imageExtension && /^file:\/\/.+/.test(src))
// Treat an URL with valid extension as image.
if (imageExtension) {
// NOTE: Check both "C:\" and "C:/" because we're using "file:///C:/".
const isAbsoluteLocal = /^(?:\/|\\\\|[a-zA-Z]:\\|[a-zA-Z]:\/).+/.test(src)
if (isUrl || (!isAbsoluteLocal && !baseUrl)) {
if (!isUrl && !baseUrl) {
console.warn('"baseUrl" is not defined!')
}
return {
isUnknownType: false,
src
}
} else {
// Correct relative path on desktop. If we resolve a absolute path "path.resolve" doesn't do anything.
// NOTE: We don't need to convert Windows styled path to UNIX style because Chromium handels this internal.
return {
isUnknownType: false,
src: 'file://' + require('path').resolve(baseUrl, src)
}
}
} else if (isUrl && !imageExtension) {
// Assume it's a valid image and make a http request later
return {
isUnknownType: true,
src
}
}
// Data url
if (DATA_URL_REG.test(src)) {
return {
isUnknownType: false,
src
}
}
// Url type is unknown
return {
isUnknownType: false,
src: ''
}
}
export const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
)
export const unescapeHTML = str =>
str.replace(
/(?:&|<|>|"|')/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
''': "'",
'"': '"'
}[tag] || tag)
)
export const escapeInBlockHtml = html => {
return html
.replace(/(<(style|script|title)[^<>]*>)([\s\S]*?)(<\/\2>)/g, (m, p1, p2, p3, p4) => {
return `${escapeHTML(p1)}${p3}${escapeHTML(p4)}`
})
}
export const escapeHtmlTags = html => {
return html.replace(/[&<>"']/g, x => { return HTML_TAG_REPLACEMENTS[x] })
}
export const wordCount = markdown => {
const paragraph = markdown.split(/\n{2,}/).filter(line => line).length
let word = 0
let character = 0
let all = 0
const removedChinese = markdown.replace(/[\u4e00-\u9fa5]/g, '')
const tokens = removedChinese.split(/[\s\n]+/).filter(t => t)
const chineseWordLength = markdown.length - removedChinese.length
word += chineseWordLength + tokens.length
character += tokens.reduce((acc, t) => acc + t.length, 0) + chineseWordLength
all += markdown.length
return { word, paragraph, character, all }
}
// mixins
export const mixins = (constructor, ...object) => {
return Object.assign(constructor.prototype, ...object)
}
export const sanitize = (html, purifyOptions, disableHtml) => {
if (disableHtml) {
return runSanitize(escapeHtmlTags(html), purifyOptions)
} else {
return runSanitize(escapeInBlockHtml(html), purifyOptions)
}
}
export const getParagraphReference = (ele, id) => {
const { x, y, left, top, bottom, height } = ele.getBoundingClientRect()
return {
getBoundingClientRect () {
return { x, y, left, top, bottom, height, width: 0, right: left }
},
clientWidth: 0,
clientHeight: height,
id
}
}
export const verticalPositionInRect = (event, rect) => {
const { clientY } = event
const { top, height } = rect
return (clientY - top) > (height / 2) ? 'down' : 'up'
}
export const collectFootnotes = (blocks) => {
const map = new Map()
for (const block of blocks) {
if (block.type === 'figure' && block.functionType === 'footnote') {
const identifier = block.children[0].text
map.set(identifier, block)
}
}
return map
}
export const getDefer = () => {
const defer = {}
const promise = new Promise((resolve, reject) => {
defer.resolve = resolve
defer.reject = reject
})
defer.promise = promise
return defer
}
/**
* Deep clone the given object.
*
* @param {*} obj Object to clone
*/
export const deepClone = obj => {
return JSON.parse(JSON.stringify(obj))
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/exportHtml.js | src/muya/lib/utils/exportHtml.js | import marked from '../parser/marked'
import Prism from 'prismjs'
import katex from 'katex'
import 'katex/dist/contrib/mhchem.min.js'
import loadRenderer from '../renderers'
import githubMarkdownCss from 'github-markdown-css/github-markdown.css'
import exportStyle from '../assets/styles/exportStyle.css'
import highlightCss from 'prismjs/themes/prism.css'
import katexCss from 'katex/dist/katex.css'
import footerHeaderCss from '../assets/styles/headerFooterStyle.css'
import { EXPORT_DOMPURIFY_CONFIG } from '../config'
import { sanitize, unescapeHTML } from '../utils'
import { validEmoji } from '../ui/emojis'
export const getSanitizeHtml = (markdown, options) => {
const html = marked(markdown, options)
return sanitize(html, EXPORT_DOMPURIFY_CONFIG, false)
}
const DIAGRAM_TYPE = [
'mermaid',
'flowchart',
'sequence',
'plantuml',
'vega-lite'
]
class ExportHtml {
constructor (markdown, muya) {
this.markdown = markdown
this.muya = muya
this.exportContainer = null
this.mathRendererCalled = false
}
async renderMermaid () {
const codes = this.exportContainer.querySelectorAll('code.language-mermaid')
for (const code of codes) {
const preEle = code.parentNode
const mermaidContainer = document.createElement('div')
mermaidContainer.innerHTML = sanitize(unescapeHTML(code.innerHTML), EXPORT_DOMPURIFY_CONFIG, true)
mermaidContainer.classList.add('mermaid')
preEle.replaceWith(mermaidContainer)
}
const mermaid = await loadRenderer('mermaid')
// We only export light theme, so set mermaid theme to `default`, in the future, we can choose whick theme to export.
mermaid.initialize({
securityLevel: 'strict',
theme: 'default'
})
mermaid.init(undefined, this.exportContainer.querySelectorAll('div.mermaid'))
if (this.muya) {
mermaid.initialize({
securityLevel: 'strict',
theme: this.muya.options.mermaidTheme
})
}
}
async renderDiagram () {
const selector = 'code.language-vega-lite, code.language-flowchart, code.language-sequence, code.language-plantuml'
const RENDER_MAP = {
flowchart: await loadRenderer('flowchart'),
sequence: await loadRenderer('sequence'),
plantuml: await loadRenderer('plantuml'),
'vega-lite': await loadRenderer('vega-lite')
}
const codes = this.exportContainer.querySelectorAll(selector)
for (const code of codes) {
const rawCode = unescapeHTML(code.innerHTML)
const functionType = (() => {
if (/sequence/.test(code.className)) {
return 'sequence'
} else if (/plantuml/.test(code.className)) {
return 'plantuml'
} else if (/flowchart/.test(code.className)) {
return 'flowchart'
} else {
return 'vega-lite'
}
})()
const render = RENDER_MAP[functionType]
const preParent = code.parentNode
const diagramContainer = document.createElement('div')
diagramContainer.classList.add(functionType)
preParent.replaceWith(diagramContainer)
const options = {}
if (functionType === 'sequence') {
Object.assign(options, { theme: this.muya.options.sequenceTheme })
} else if (functionType === 'vega-lite') {
Object.assign(options, {
actions: false,
tooltip: false,
renderer: 'svg',
theme: 'latimes' // only render light theme
})
}
try {
if (functionType === 'flowchart' || functionType === 'sequence') {
const diagram = render.parse(rawCode)
diagramContainer.innerHTML = ''
diagram.drawSVG(diagramContainer, options)
}
if (functionType === 'plantuml') {
const diagram = render.parse(rawCode)
diagramContainer.innerHTML = ''
diagram.insertImgElement(diagramContainer)
}
if (functionType === 'vega-lite') {
await render(diagramContainer, JSON.parse(rawCode), options)
}
} catch (err) {
diagramContainer.innerHTML = '< Invalid Diagram >'
}
}
}
mathRenderer = (math, displayMode) => {
this.mathRendererCalled = true
try {
return katex.renderToString(math, {
displayMode
})
} catch (err) {
return displayMode
? `<pre class="multiple-math invalid">\n${math}</pre>\n`
: `<span class="inline-math invalid" title="invalid math">${math}</span>`
}
}
// render pure html by marked
async renderHtml (toc) {
this.mathRendererCalled = false
let html = marked(this.markdown, {
superSubScript: this.muya ? this.muya.options.superSubScript : false,
footnote: this.muya ? this.muya.options.footnote : false,
isGitlabCompatibilityEnabled: this.muya ? this.muya.options.isGitlabCompatibilityEnabled : false,
highlight (code, lang) {
// Language may be undefined (GH#591)
if (!lang) {
return code
}
if (DIAGRAM_TYPE.includes(lang)) {
return code
}
const grammar = Prism.languages[lang]
if (!grammar) {
console.warn(`Unable to find grammar for "${lang}".`)
return code
}
return Prism.highlight(code, grammar, lang)
},
emojiRenderer (emoji) {
const validate = validEmoji(emoji)
if (validate) {
return validate.emoji
} else {
return `:${emoji}:`
}
},
mathRenderer: this.mathRenderer,
tocRenderer () {
if (!toc) {
return ''
}
return toc
}
})
html = sanitize(html, EXPORT_DOMPURIFY_CONFIG, false)
const exportContainer = this.exportContainer = document.createElement('div')
exportContainer.classList.add('ag-render-container')
exportContainer.innerHTML = html
document.body.appendChild(exportContainer)
// render only render the light theme of mermaid and diragram...
await this.renderMermaid()
await this.renderDiagram()
let result = exportContainer.innerHTML
exportContainer.remove()
// hack to add arrow marker to output html
const pathes = document.querySelectorAll('path[id^=raphael-marker-]')
const def = '<defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">'
result = result.replace(def, () => {
let str = ''
for (const path of pathes) {
str += path.outerHTML
}
return `${def}${str}`
})
this.exportContainer = null
return result
}
/**
* Get HTML with style
*
* @param {*} options Document options
*/
async generate (options) {
const { printOptimization } = options
// WORKAROUND: Hide Prism.js style when exporting or printing. Otherwise the background color is white in the dark theme.
const highlightCssStyle = printOptimization ? `@media print { ${highlightCss} }` : highlightCss
const html = this._prepareHtml(await this.renderHtml(options.toc), options)
const katexCssStyle = this.mathRendererCalled ? katexCss : ''
this.mathRendererCalled = false
// `extraCss` may changed in the mean time.
const { title, extraCss } = options
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${sanitize(title, EXPORT_DOMPURIFY_CONFIG, true)}</title>
<style>
${githubMarkdownCss}
</style>
<style>
${highlightCssStyle}
</style>
<style>
${katexCssStyle}
</style>
<style>
.markdown-body {
font-family: -apple-system,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media not print {
.markdown-body {
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
}
.hf-container {
color: #24292e;
line-height: 1.3;
}
.markdown-body .highlight pre,
.markdown-body pre {
white-space: pre-wrap;
}
.markdown-body table {
display: table;
}
.markdown-body img[data-align="center"] {
display: block;
margin: 0 auto;
}
.markdown-body img[data-align="right"] {
display: block;
margin: 0 0 0 auto;
}
.markdown-body li.task-list-item {
list-style-type: none;
}
.markdown-body li > [type=checkbox] {
margin: 0 0 0 -1.3em;
}
.markdown-body input[type="checkbox"] ~ p {
margin-top: 0;
display: inline-block;
}
.markdown-body ol ol,
.markdown-body ul ol {
list-style-type: decimal;
}
.markdown-body ol ol ol,
.markdown-body ol ul ol,
.markdown-body ul ol ol,
.markdown-body ul ul ol {
list-style-type: decimal;
}
</style>
<style>${exportStyle}</style>
<style>${extraCss}</style>
</head>
<body>
${html}
</body>
</html>`
}
/**
* @private
*
* @param {string} html The converted HTML text.
* @param {*} options The export options.
*/
_prepareHtml (html, options) {
const { header, footer } = options
const appendHeaderFooter = !!header || !!footer
if (!appendHeaderFooter) {
return createMarkdownArticle(html)
}
if (!options.extraCss) {
options.extraCss = footerHeaderCss
} else {
options.extraCss = footerHeaderCss + options.extraCss
}
let output = HF_TABLE_START
if (header) {
output += createTableHeader(options)
}
if (footer) {
output += HF_TABLE_FOOTER
output = createRealFooter(options) + output
}
output = output + createTableBody(html) + HF_TABLE_END
return sanitize(output, EXPORT_DOMPURIFY_CONFIG, false)
}
}
// Variables and function to generate the header and footer.
const HF_TABLE_START = '<table class="page-container">'
const createTableBody = html => {
return `<tbody><tr><td>
<div class="main-container">
${createMarkdownArticle(html)}
</div>
</td></tr></tbody>`
}
const HF_TABLE_END = '</table>'
/// The header at is shown at the top.
const createTableHeader = options => {
const { header, headerFooterStyled } = options
const { type, left, center, right } = header
let headerClass = type === 1 ? 'single' : ''
headerClass += getHeaderFooterStyledClass(headerFooterStyled)
return `<thead class="page-header ${headerClass}"><tr><th>
<div class="hf-container">
<div class="header-content-left">${left}</div>
<div class="header-content">${center}</div>
<div class="header-content-right">${right}</div>
</div>
</th></tr></thead>`
}
/// Fake footer to reserve space.
const HF_TABLE_FOOTER = `<tfoot class="page-footer-fake"><tr><td>
<div class="hf-container">
</div>
</td></tr></tfoot>`
/// The real footer at is shown at the bottom.
const createRealFooter = options => {
const { footer, headerFooterStyled } = options
const { type, left, center, right } = footer
let footerClass = type === 1 ? 'single' : ''
footerClass += getHeaderFooterStyledClass(headerFooterStyled)
return `<div class="page-footer ${footerClass}">
<div class="hf-container">
<div class="footer-content-left">${left}</div>
<div class="footer-content">${center}</div>
<div class="footer-content-right">${right}</div>
</div>
</div>`
}
/// Generate the mardown article HTML.
const createMarkdownArticle = html => {
return `<article class="markdown-body">${html}</article>`
}
/// Return the class whether a header/footer should be styled.
const getHeaderFooterStyledClass = value => {
if (value === undefined) {
// Prefer theme settings.
return ''
}
return !value ? ' simple' : ' styled'
}
export default ExportHtml
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/turndownService.js | src/muya/lib/utils/turndownService.js | import TurndownService from 'turndown'
import { identity } from './index'
const turndownPluginGfm = require('joplin-turndown-plugin-gfm')
export const usePluginAddRules = (turndownService, keeps) => {
// Use the gfm plugin
const { gfm } = turndownPluginGfm
turndownService.use(gfm)
// We need a extra strikethrough rule because the strikethrough rule in gfm is single `~`.
turndownService.addRule('strikethrough', {
filter: ['del', 's', 'strike'],
replacement (content) {
return '~~' + content + '~~'
}
})
turndownService.addRule('paragraph', {
filter: 'p',
replacement: function (content, node) {
const isTaskListItemParagraph = node.previousElementSibling && node.previousElementSibling.tagName === 'INPUT'
return isTaskListItemParagraph ? content + '\n\n' : '\n\n' + content + '\n\n'
}
})
turndownService.addRule('listItem', {
filter: 'li',
replacement: function (content, node, options) {
content = content
.replace(/^\n+/, '') // remove leading newlines
.replace(/\n+$/, '\n') // replace trailing newlines with just a single one
.replace(/\n/gm, '\n ') // indent
let prefix = options.bulletListMarker + ' '
const parent = node.parentNode
if (parent.nodeName === 'OL') {
const start = parent.getAttribute('start')
const index = Array.prototype.indexOf.call(parent.children, node)
prefix = (start ? Number(start) + index : index + 1) + '. '
}
return (
prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
)
}
})
// Handle multiple math lines
turndownService.addRule('multiplemath', {
filter (node, options) {
return node.nodeName === 'PRE' && node.classList.contains('multiple-math')
},
replacement (content, node, options) {
return `$$\n${content}\n$$`
}
})
turndownService.escape = identity
turndownService.keep(keeps)
}
export default TurndownService
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/markdownFile.js | src/muya/lib/utils/markdownFile.js | // __MARKTEXT_ONLY__
const MARKDOWN_EXTENSIONS = Object.freeze([
'markdown',
'mdown',
'mkdn',
'md',
'mkd',
'mdwn',
'mdtxt',
'mdtext',
'mdx',
'text',
'txt'
])
/**
* Returns true if the filename matches one of the markdown extensions allowed in MarkText.
*
* @param {string} filename Path or filename
*/
export const hasMarkdownExtension = filename => {
if (!filename || typeof filename !== 'string') return false
return MARKDOWN_EXTENSIONS.some(ext => filename.toLowerCase().endsWith(`.${ext}`))
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/hash.js | src/muya/lib/utils/hash.js | /**
* generate constants map hash, the value is lowercase of the key,
* also translate `_` to `-`]
*/
export const genUpper2LowerKeyHash = keys => {
return keys.reduce((acc, key) => {
const value = key.toLowerCase().replace(/_/g, '-')
return Object.assign(acc, { [key]: value })
}, {})
}
/**
* generate constants map, the value is the key.
*/
export const generateKeyHash = keys => {
return keys.reduce((acc, key) => {
return Object.assign(acc, { [key]: key })
}, {})
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/getParentCheckBox.js | src/muya/lib/utils/getParentCheckBox.js | import { CLASS_OR_ID } from '../config'
export const getParentCheckBox = function (checkbox) {
const parent = checkbox.parentElement.parentElement.parentElement
if (parent.id !== CLASS_OR_ID.AG_EDITOR_ID) {
return parent.firstElementChild
} else {
return null
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/dompurify.js | src/muya/lib/utils/dompurify.js | import { sanitize, isValidAttribute } from 'dompurify'
export { isValidAttribute }
export default sanitize
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/exportMarkdown.js | src/muya/lib/utils/exportMarkdown.js | /**
* Hi contributors!
*
* Before you edit or update codes in this file,
* make sure you have read this below:
* Commonmark Spec: https://spec.commonmark.org/0.29/
* GitHub Flavored Markdown Spec: https://github.github.com/gfm/
* Pandoc Markdown: https://pandoc.org/MANUAL.html#pandocs-markdown
* The output markdown needs to obey the standards of these Spec.
*/
class ExportMarkdown {
constructor (blocks, listIndentation = 1, isGitlabCompatibilityEnabled = false) {
this.blocks = blocks
this.listType = [] // 'ul' or 'ol'
// helper to translate the first tight item in a nested list
this.isLooseParentList = true
this.isGitlabCompatibilityEnabled = !!isGitlabCompatibilityEnabled
// set and validate settings
this.listIndentation = 'number'
if (listIndentation === 'dfm') {
this.listIndentation = 'dfm'
this.listIndentationCount = 4
} else if (typeof listIndentation === 'number') {
this.listIndentationCount = Math.min(Math.max(listIndentation, 1), 4)
} else {
this.listIndentationCount = 1
}
}
generate () {
return this.translateBlocks2Markdown(this.blocks)
}
translateBlocks2Markdown (blocks, indent = '', listIndent = '') {
const result = []
// helper for CommonMark 264
let lastListBullet = ''
for (const block of blocks) {
if (block.type !== 'ul' && block.type !== 'ol') {
lastListBullet = ''
}
switch (block.type) {
case 'p':
case 'hr': {
this.insertLineBreak(result, indent)
result.push(this.translateBlocks2Markdown(block.children, indent))
break
}
case 'span': {
result.push(this.normalizeParagraphText(block, indent))
break
}
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6': {
this.insertLineBreak(result, indent)
result.push(this.normalizeHeaderText(block, indent))
break
}
case 'figure': {
this.insertLineBreak(result, indent)
switch (block.functionType) {
case 'table': {
const table = block.children[0]
result.push(this.normalizeTable(table, indent))
break
}
case 'html': {
result.push(this.normalizeHTML(block, indent))
break
}
case 'footnote': {
result.push(this.normalizeFootnote(block, indent))
break
}
case 'multiplemath': {
result.push(this.normalizeMultipleMath(block, indent))
break
}
case 'mermaid':
case 'flowchart':
case 'sequence':
case 'plantuml':
case 'vega-lite': {
result.push(this.normalizeContainer(block, indent))
break
}
}
break
}
case 'li': {
const insertNewLine = block.isLooseListItem
// helper variable to correct the first tight item in a nested list
this.isLooseParentList = insertNewLine
if (insertNewLine) {
this.insertLineBreak(result, indent)
}
result.push(this.normalizeListItem(block, indent + listIndent))
this.isLooseParentList = true
break
}
case 'ul': {
let insertNewLine = this.isLooseParentList
this.isLooseParentList = true
// Start a new list without separation due changing the bullet or ordered list delimiter starts a new list.
const { bulletMarkerOrDelimiter } = block.children[0]
if (lastListBullet && lastListBullet !== bulletMarkerOrDelimiter) {
insertNewLine = false
}
lastListBullet = bulletMarkerOrDelimiter
if (insertNewLine) {
this.insertLineBreak(result, indent)
}
this.listType.push({ type: 'ul' })
result.push(this.normalizeList(block, indent, listIndent))
this.listType.pop()
break
}
case 'ol': {
let insertNewLine = this.isLooseParentList
this.isLooseParentList = true
// Start a new list without separation due changing the bullet or ordered list delimiter starts a new list.
const { bulletMarkerOrDelimiter } = block.children[0]
if (lastListBullet && lastListBullet !== bulletMarkerOrDelimiter) {
insertNewLine = false
}
lastListBullet = bulletMarkerOrDelimiter
if (insertNewLine) {
this.insertLineBreak(result, indent)
}
const listCount = block.start !== undefined ? block.start : 1
this.listType.push({ type: 'ol', listCount })
result.push(this.normalizeList(block, indent, listIndent))
this.listType.pop()
break
}
case 'pre': {
this.insertLineBreak(result, indent)
if (block.functionType === 'frontmatter') {
result.push(this.normalizeFrontMatter(block, indent))
} else {
result.push(this.normalizeCodeBlock(block, indent))
}
break
}
case 'blockquote': {
this.insertLineBreak(result, indent)
result.push(this.normalizeBlockquote(block, indent))
break
}
default: {
console.warn('translateBlocks2Markdown: Unknown block type:', block.type)
break
}
}
}
return result.join('')
}
insertLineBreak (result, indent) {
if (!result.length) return
result.push(`${indent}\n`)
}
normalizeParagraphText (block, indent) {
const { text } = block
const lines = text.split('\n')
return lines.map(line => `${indent}${line}`).join('\n') + '\n'
}
normalizeHeaderText (block, indent) {
const { headingStyle, marker } = block
const { text } = block.children[0]
if (headingStyle === 'atx') {
const match = text.match(/(#{1,6})(.*)/)
const atxHeadingText = `${match[1]} ${match[2].trim()}`
return `${indent}${atxHeadingText}\n`
} else if (headingStyle === 'setext') {
const lines = text.trim().split('\n')
return lines.map(line => `${indent}${line}`).join('\n') + `\n${indent}${marker.trim()}\n`
}
}
normalizeBlockquote (block, indent) {
const { children } = block
const newIndent = `${indent}> `
return this.translateBlocks2Markdown(children, newIndent)
}
normalizeFrontMatter (block, indent) { // preBlock
let startToken
let endToken
switch (block.lang) {
case 'yaml':
startToken = '---\n'
endToken = '---\n'
break
case 'toml':
startToken = '+++\n'
endToken = '+++\n'
break
case 'json':
if (block.style === ';') {
startToken = ';;;\n'
endToken = ';;;\n'
} else {
startToken = '{\n'
endToken = '}\n'
}
break
}
const result = []
result.push(startToken)
for (const line of block.children[0].children) {
result.push(`${line.text}\n`)
}
result.push(endToken)
return result.join('')
}
normalizeMultipleMath (block, /* figure */ indent) {
const { isGitlabCompatibilityEnabled } = this
let startToken = '$$'
let endToken = '$$'
if (isGitlabCompatibilityEnabled && block.mathStyle === 'gitlab') {
startToken = '```math'
endToken = '```'
}
const result = []
result.push(`${indent}${startToken}\n`)
for (const line of block.children[0].children[0].children) {
result.push(`${indent}${line.text}\n`)
}
result.push(`${indent}${endToken}\n`)
return result.join('')
}
// `mermaid` `flowchart` `sequence` `plantuml` `vega-lite`
normalizeContainer (block, indent) {
const result = []
const diagramType = block.children[0].functionType
result.push('```' + diagramType + '\n')
for (const line of block.children[0].children[0].children) {
result.push(`${line.text}\n`)
}
result.push('```\n')
return result.join('')
}
normalizeCodeBlock (block, indent) {
const result = []
const codeContent = block.children[1].children[0]
const textList = codeContent.text.split('\n')
const { functionType } = block
if (functionType === 'fencecode') {
result.push(`${indent}${block.lang ? '```' + block.lang + '\n' : '```\n'}`)
textList.forEach(text => {
result.push(`${indent}${text}\n`)
})
result.push(indent + '```\n')
} else {
textList.forEach(text => {
result.push(`${indent} ${text}\n`)
})
}
return result.join('')
}
normalizeHTML (block, indent) { // figure
const result = []
const codeContentText = block.children[0].children[0].children[0].text
const lines = codeContentText.split('\n')
for (const line of lines) {
result.push(`${indent}${line}\n`)
}
return result.join('')
}
normalizeTable (table, indent) {
const result = []
const { row, column } = table
const tableData = []
const tHeader = table.children[0]
const tBody = table.children[1]
const escapeText = str => {
return str.replace(/([^\\])\|/g, '$1\\|')
}
tableData.push(tHeader.children[0].children.map(th => escapeText(th.children[0].text).trim()))
if (tBody) {
tBody.children.forEach(bodyRow => {
tableData.push(bodyRow.children.map(td => escapeText(td.children[0].text).trim()))
})
}
const columnWidth = tHeader.children[0].children.map(th => ({ width: 5, align: th.align }))
let i
let j
for (i = 0; i <= row; i++) {
for (j = 0; j <= column; j++) {
columnWidth[j].width = Math.max(columnWidth[j].width, tableData[i][j].length + 2) // add 2, because have two space around text
}
}
tableData.forEach((r, i) => {
const rs = indent + '|' + r.map((cell, j) => {
const raw = ` ${cell + ' '.repeat(columnWidth[j].width)}`
return raw.substring(0, columnWidth[j].width)
}).join('|') + '|'
result.push(rs)
if (i === 0) {
const cutOff = indent + '|' + columnWidth.map(({ width, align }) => {
let raw = '-'.repeat(width - 2)
switch (align) {
case 'left':
raw = `:${raw} `
break
case 'center':
raw = `:${raw}:`
break
case 'right':
raw = ` ${raw}:`
break
default:
raw = ` ${raw} `
break
}
return raw
}).join('|') + '|'
result.push(cutOff)
}
})
return result.join('\n') + '\n'
}
normalizeList (block, indent, listIndent) {
const { children } = block
return this.translateBlocks2Markdown(children, indent, listIndent)
}
normalizeListItem (block, indent) {
const result = []
const listInfo = this.listType[this.listType.length - 1]
const isUnorderedList = listInfo.type === 'ul'
let { children, bulletMarkerOrDelimiter } = block
let itemMarker
if (isUnorderedList) {
itemMarker = bulletMarkerOrDelimiter ? `${bulletMarkerOrDelimiter} ` : '- '
} else {
// NOTE: GitHub and Bitbucket limit the list count to 99 but this is nowhere defined.
// We limit the number to 99 for Daring Fireball Markdown to prevent indentation issues.
let n = listInfo.listCount
if ((this.listIndentation === 'dfm' && n > 99) || n > 999999999) {
n = 1
}
listInfo.listCount++
const delimiter = bulletMarkerOrDelimiter || '.'
itemMarker = `${n}${delimiter} `
}
// Subsequent paragraph indentation
const newIndent = indent + ' '.repeat(itemMarker.length)
// New list indentation. We already added one space to the indentation
let listIndent = ''
const { listIndentation } = this
if (listIndentation === 'dfm') {
listIndent = ' '.repeat(4 - itemMarker.length)
} else if (listIndentation === 'number') {
listIndent = ' '.repeat(this.listIndentationCount - 1)
}
// TODO: Indent subsequent paragraphs by one tab. - not important
// Problem: "translateBlocks2Markdown" use "indent" in spaces to indent elements. How should
// we integrate tabs in blockquotes and subsequent paragraphs and how to combine with spaces?
// I don't know how to combine tabs and spaces and it seems not specified, so work for another day.
if (isUnorderedList && block.listItemType === 'task') {
const firstChild = children[0]
itemMarker += firstChild.checked ? '[x] ' : '[ ] '
children = children.slice(1)
}
result.push(`${indent}${itemMarker}`)
result.push(this.translateBlocks2Markdown(children, newIndent, listIndent).substring(newIndent.length))
return result.join('')
}
normalizeFootnote (block, indent) {
const result = []
const identifier = block.children[0].text
result.push(`${indent}[^${identifier}]:`)
const hasMultipleBlocks = block.children.length > 2 || block.children[1].type !== 'p'
if (hasMultipleBlocks) {
result.push('\n')
const newIndent = indent + ' '.repeat(4)
result.push(this.translateBlocks2Markdown(block.children.slice(1), newIndent))
} else {
result.push(' ')
const paragraphContent = block.children[1].children[0]
result.push(this.normalizeParagraphText(paragraphContent, indent))
}
return result.join('')
}
}
export default ExportMarkdown
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/url.js | src/muya/lib/utils/url.js | import { isValidAttribute } from '../utils/dompurify'
import { isWin } from '../config' // __MARKTEXT_PATCH__
import { hasMarkdownExtension } from './markdownFile' // __MARKTEXT_PATCH__
export const sanitizeHyperlink = rawLink => {
if (rawLink && typeof rawLink === 'string') {
if (isValidAttribute('a', 'href', rawLink)) {
return rawLink
}
// __MARKTEXT_PATCH__
if (isWin && /^[a-zA-Z]:[/\\].+/.test(rawLink) && hasMarkdownExtension(rawLink)) {
// Create and try UNC path on Windows because "C:\file.md" isn't allowed.
const uncPath = `\\\\?\\${rawLink}`
if (isValidAttribute('a', 'href', uncPath)) {
return uncPath
}
}
// END __MARKTEXT_PATCH__
}
return ''
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/resizeCodeLineNumber.js | src/muya/lib/utils/resizeCodeLineNumber.js | /**
* This file copy from prismjs/plugins/prism-line-number
*/
/**
* Regular expression used for determining line breaks
* @type {RegExp}
*/
const NEW_LINE_EXP = /\n(?!$)/g
/**
* Returns style declarations for the element
* @param {Element} element
*/
const getStyles = function (element) {
if (!element) {
return null
}
return window.getComputedStyle ? getComputedStyle(element) : (element.currentStyle || null)
}
/**
* Resizes line numbers spans according to height of line of code
* @param {Element} element <pre> element
*/
const resizeCodeBlockLineNumber = function (element) {
// FIXME: Heavy performance issues with this function, please see #1648.
const codeStyles = getStyles(element)
const whiteSpace = codeStyles['white-space']
if (whiteSpace === 'pre' || whiteSpace === 'pre-wrap' || whiteSpace === 'pre-line') {
const codeElement = element.querySelector('code')
const lineNumbersWrapper = element.querySelector('.line-numbers-rows')
let lineNumberSizer = element.querySelector('.line-numbers-sizer')
const codeLines = codeElement.textContent.split(NEW_LINE_EXP)
if (!lineNumberSizer) {
lineNumberSizer = document.createElement('span')
lineNumberSizer.className = 'line-numbers-sizer'
codeElement.appendChild(lineNumberSizer)
}
lineNumberSizer.style.display = 'block'
codeLines.forEach(function (line, lineNumber) {
lineNumberSizer.textContent = line || '\n'
const lineSize = lineNumberSizer.getBoundingClientRect().height
lineNumbersWrapper.children[lineNumber].style.height = lineSize + 'px'
})
lineNumberSizer.textContent = ''
lineNumberSizer.style.display = 'none'
}
}
export default resizeCodeBlockLineNumber
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/domManipulate.js | src/muya/lib/utils/domManipulate.js |
/**
* [description `add` or `remove` className of element
*/
export const operateClassName = (element, ctrl, className) => {
element.classList[ctrl](className)
}
export const insertBefore = (newNode, originNode) => {
const parentNode = originNode.parentNode
parentNode.insertBefore(newNode, originNode)
}
// DOM operations
export const insertAfter = (newNode, originNode) => {
const parentNode = originNode.parentNode
if (originNode.nextSibling) {
parentNode.insertBefore(newNode, originNode.nextSibling)
} else {
parentNode.appendChild(newNode)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/random.js | src/muya/lib/utils/random.js | const ID_PREFIX = 'ag-'
let id = 0
export const getUniqueId = () => `${ID_PREFIX}${id++}`
export const getLongUniqueId = () => `${getUniqueId()}-${(+new Date()).toString(32)}`
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/utils/importMarkdown.js | src/muya/lib/utils/importMarkdown.js | /**
* translate markdown format to content state used by MarkText
* there is some difference when parse loose list item and tight lsit item.
* Both of them add a p block in li block, use the CSS style to distinguish loose and tight.
*/
import StateRender from '../parser/render'
import { tokenizer } from '../parser'
import { getImageInfo } from '../utils'
import { Lexer } from '../parser/marked'
import ExportMarkdown from './exportMarkdown'
import TurndownService, { usePluginAddRules } from './turndownService'
import { loadLanguage } from '../prism/index'
// To be disabled rules when parse markdown, Because content state don't need to parse inline rules
import { CURSOR_ANCHOR_DNA, CURSOR_FOCUS_DNA } from '../config'
const languageLoaded = new Set()
// Just because turndown change `\n`(soft line break) to space, So we add `span.ag-soft-line-break` to workaround.
const turnSoftBreakToSpan = html => {
const parser = new DOMParser()
const doc = parser.parseFromString(
`<x-mt id="turn-root">${html}</x-mt>`,
'text/html'
)
const root = doc.querySelector('#turn-root')
const travel = childNodes => {
for (const node of childNodes) {
if (node.nodeType === 3 && node.parentNode.tagName !== 'CODE') {
let startLen = 0
let endLen = 0
const text = node.nodeValue.replace(/^(\n+)/, (_, p) => {
startLen = p.length
return ''
}).replace(/(\n+)$/, (_, p) => {
endLen = p.length
return ''
})
if (/\n/.test(text)) {
const tokens = text.split('\n')
const params = []
let i = 0
const len = tokens.length
for (; i < len; i++) {
let text = tokens[i]
if (i === 0 && startLen !== 0) {
text = '\n'.repeat(startLen) + text
} else if (i === len - 1 && endLen !== 0) {
text = text + '\n'.repeat(endLen)
}
params.push(document.createTextNode(text))
if (i !== len - 1) {
const softBreak = document.createElement('span')
softBreak.classList.add('ag-soft-line-break')
params.push(softBreak)
}
}
node.replaceWith(...params)
}
} else if (node.nodeType === 1) {
travel(node.childNodes)
}
}
}
travel(root.childNodes)
return root.innerHTML.trim()
}
const importRegister = ContentState => {
// turn markdown to blocks
ContentState.prototype.markdownToState = function (markdown) {
// mock a root block...
const rootState = {
key: null,
type: 'root',
text: '',
parent: null,
preSibling: null,
nextSibling: null,
children: []
}
const {
footnote,
isGitlabCompatibilityEnabled,
superSubScript,
trimUnnecessaryCodeBlockEmptyLines
} = this.muya.options
const tokens = new Lexer({
disableInline: true,
footnote,
isGitlabCompatibilityEnabled,
superSubScript
}).lex(markdown)
let token
let block
let value
const parentList = [rootState]
while ((token = tokens.shift())) {
switch (token.type) {
case 'frontmatter': {
const { lang, style } = token
value = token.text
.replace(/^\s+/, '')
.replace(/\s$/, '')
block = this.createBlock('pre', {
functionType: token.type,
lang,
style
})
const codeBlock = this.createBlock('code', {
lang
})
const codeContent = this.createBlock('span', {
text: value,
lang,
functionType: 'codeContent'
})
this.appendChild(codeBlock, codeContent)
this.appendChild(block, codeBlock)
this.appendChild(parentList[0], block)
break
}
case 'hr': {
value = token.marker
block = this.createBlock('hr')
const thematicBreakContent = this.createBlock('span', {
text: value,
functionType: 'thematicBreakLine'
})
this.appendChild(block, thematicBreakContent)
this.appendChild(parentList[0], block)
break
}
case 'heading': {
const { headingStyle, depth, text, marker } = token
value = headingStyle === 'atx' ? '#'.repeat(+depth) + ` ${text}` : text
block = this.createBlock(`h${depth}`, {
headingStyle
})
const headingContent = this.createBlock('span', {
text: value,
functionType: headingStyle === 'atx' ? 'atxLine' : 'paragraphContent'
})
this.appendChild(block, headingContent)
if (marker) {
block.marker = marker
}
this.appendChild(parentList[0], block)
break
}
case 'multiplemath': {
value = token.text
block = this.createContainerBlock(token.type, value, token.mathStyle)
this.appendChild(parentList[0], block)
break
}
case 'code': {
const { codeBlockStyle, text, lang: infostring = '' } = token
// GH#697, markedjs#1387
const lang = (infostring || '').match(/\S*/)[0]
value = text
// Fix: #1265.
if (trimUnnecessaryCodeBlockEmptyLines && (value.endsWith('\n') || value.startsWith('\n'))) {
value = value.replace(/\n+$/, '')
.replace(/^\n+/, '')
}
if (/mermaid|flowchart|vega-lite|sequence|plantuml/.test(lang)) {
block = this.createContainerBlock(lang, value)
this.appendChild(parentList[0], block)
} else {
block = this.createBlock('pre', {
functionType: codeBlockStyle === 'fenced' ? 'fencecode' : 'indentcode',
lang
})
const codeBlock = this.createBlock('code', {
lang
})
const codeContent = this.createBlock('span', {
text: value,
lang,
functionType: 'codeContent'
})
const inputBlock = this.createBlock('span', {
text: lang,
functionType: 'languageInput'
})
if (lang && !languageLoaded.has(lang)) {
languageLoaded.add(lang)
loadLanguage(lang)
.then(infoList => {
if (!Array.isArray(infoList)) return
// There are three status `loaded`, `noexist` and `cached`.
// if the status is `loaded`, indicated that it's a new loaded language
const needRender = infoList.some(({ status }) => status === 'loaded')
if (needRender) {
this.render()
}
})
.catch(err => {
// if no parameter provided, will cause error.
console.warn(err)
})
}
this.appendChild(codeBlock, codeContent)
this.appendChild(block, inputBlock)
this.appendChild(block, codeBlock)
this.appendChild(parentList[0], block)
}
break
}
case 'table': {
const { header, align, cells } = token
const table = this.createBlock('table')
const thead = this.createBlock('thead')
const tbody = this.createBlock('tbody')
const theadRow = this.createBlock('tr')
const restoreTableEscapeCharacters = text => {
// NOTE: markedjs replaces all escaped "|" ("\|") characters inside a cell with "|".
// We have to re-escape the chraracter to not break the table.
return text.replace(/\|/g, '\\|')
}
let i
let j
const headerLen = header.length
for (i = 0; i < headerLen; i++) {
const headText = header[i]
const th = this.createBlock('th', {
align: align[i] || '',
column: i
})
const cellContent = this.createBlock('span', {
text: restoreTableEscapeCharacters(headText),
functionType: 'cellContent'
})
this.appendChild(th, cellContent)
this.appendChild(theadRow, th)
}
const rowLen = cells.length
for (i = 0; i < rowLen; i++) {
const rowBlock = this.createBlock('tr')
const rowContents = cells[i]
const colLen = rowContents.length
for (j = 0; j < colLen; j++) {
const cell = rowContents[j]
const td = this.createBlock('td', {
align: align[j] || '',
column: j
})
const cellContent = this.createBlock('span', {
text: restoreTableEscapeCharacters(cell),
functionType: 'cellContent'
})
this.appendChild(td, cellContent)
this.appendChild(rowBlock, td)
}
this.appendChild(tbody, rowBlock)
}
Object.assign(table, { row: cells.length, column: header.length - 1 }) // set row and column
block = this.createBlock('figure')
block.functionType = 'table'
this.appendChild(thead, theadRow)
this.appendChild(block, table)
this.appendChild(table, thead)
if (tbody.children.length) {
this.appendChild(table, tbody)
}
this.appendChild(parentList[0], block)
break
}
case 'html': {
const text = token.text.trim()
// TODO: Treat html block which only contains one img as paragraph, we maybe add image block in the future.
const isSingleImage = /^<img[^<>]+>$/.test(text)
if (isSingleImage) {
block = this.createBlock('p')
const contentBlock = this.createBlock('span', {
text
})
this.appendChild(block, contentBlock)
this.appendChild(parentList[0], block)
} else {
block = this.createHtmlBlock(text)
this.appendChild(parentList[0], block)
}
break
}
case 'text': {
value = token.text
while (tokens[0].type === 'text') {
token = tokens.shift()
value += `\n${token.text}`
}
block = this.createBlock('p')
const contentBlock = this.createBlock('span', {
text: value
})
this.appendChild(block, contentBlock)
this.appendChild(parentList[0], block)
break
}
case 'toc':
case 'paragraph': {
value = token.text
block = this.createBlock('p')
const contentBlock = this.createBlock('span', {
text: value
})
this.appendChild(block, contentBlock)
this.appendChild(parentList[0], block)
break
}
case 'blockquote_start': {
block = this.createBlock('blockquote')
this.appendChild(parentList[0], block)
parentList.unshift(block)
break
}
case 'blockquote_end': {
// Fix #1735 the blockquote maybe empty.
if (parentList[0].children.length === 0) {
const paragraphBlock = this.createBlockP()
this.appendChild(parentList[0], paragraphBlock)
}
parentList.shift()
break
}
case 'footnote_start': {
block = this.createBlock('figure', {
functionType: 'footnote'
})
const identifierInput = this.createBlock('span', {
text: token.identifier,
functionType: 'footnoteInput'
})
this.appendChild(block, identifierInput)
this.appendChild(parentList[0], block)
parentList.unshift(block)
break
}
case 'footnote_end': {
parentList.shift()
break
}
case 'list_start': {
const { ordered, listType, start } = token
block = this.createBlock(ordered === true ? 'ol' : 'ul')
block.listType = listType
if (listType === 'order') {
block.start = /^\d+$/.test(start) ? start : 1
}
this.appendChild(parentList[0], block)
parentList.unshift(block)
break
}
case 'list_end': {
parentList.shift()
break
}
case 'loose_item_start':
case 'list_item_start': {
const { listItemType, bulletMarkerOrDelimiter, checked, type } = token
block = this.createBlock('li', {
listItemType: checked !== undefined ? 'task' : listItemType,
bulletMarkerOrDelimiter,
isLooseListItem: type === 'loose_item_start'
})
if (checked !== undefined) {
const input = this.createBlock('input', {
checked
})
this.appendChild(block, input)
}
this.appendChild(parentList[0], block)
parentList.unshift(block)
break
}
case 'list_item_end': {
parentList.shift()
break
}
case 'space': {
break
}
default:
console.warn(`Unknown type ${token.type}`)
break
}
}
return rootState.children.length ? rootState.children : [this.createBlockP()]
}
ContentState.prototype.htmlToMarkdown = function (html, keeps = []) {
// turn html to markdown
const { turndownConfig } = this
const turndownService = new TurndownService(turndownConfig)
usePluginAddRules(turndownService, keeps)
// fix #752, but I don't know why the vanlished.
html = html.replace(/<span> <\/span>/g, String.fromCharCode(160))
html = turnSoftBreakToSpan(html)
const markdown = turndownService.turndown(html)
return markdown
}
// turn html to blocks
ContentState.prototype.html2State = function (html) {
const markdown = this.htmlToMarkdown(html, ['ruby', 'rt', 'u', 'br'])
return this.markdownToState(markdown)
}
ContentState.prototype.getCodeMirrorCursor = function () {
const blocks = this.getBlocks()
const { anchor, focus } = this.cursor
const anchorBlock = this.getBlock(anchor.key)
const focusBlock = this.getBlock(focus.key)
const { text: anchorText } = anchorBlock
const { text: focusText } = focusBlock
if (anchor.key === focus.key) {
const minOffset = Math.min(anchor.offset, focus.offset)
const maxOffset = Math.max(anchor.offset, focus.offset)
const firstTextPart = anchorText.substring(0, minOffset)
const secondTextPart = anchorText.substring(minOffset, maxOffset)
const thirdTextPart = anchorText.substring(maxOffset)
anchorBlock.text = firstTextPart +
(anchor.offset <= focus.offset ? CURSOR_ANCHOR_DNA : CURSOR_FOCUS_DNA) +
secondTextPart +
(anchor.offset <= focus.offset ? CURSOR_FOCUS_DNA : CURSOR_ANCHOR_DNA) +
thirdTextPart
} else {
anchorBlock.text = anchorText.substring(0, anchor.offset) + CURSOR_ANCHOR_DNA + anchorText.substring(anchor.offset)
focusBlock.text = focusText.substring(0, focus.offset) + CURSOR_FOCUS_DNA + focusText.substring(focus.offset)
}
const { isGitlabCompatibilityEnabled, listIndentation } = this
const markdown = new ExportMarkdown(blocks, listIndentation, isGitlabCompatibilityEnabled).generate()
const cursor = markdown.split('\n').reduce((acc, line, index) => {
const ach = line.indexOf(CURSOR_ANCHOR_DNA)
const fch = line.indexOf(CURSOR_FOCUS_DNA)
if (ach > -1 && fch > -1) {
if (ach <= fch) {
Object.assign(acc.anchor, { line: index, ch: ach })
Object.assign(acc.focus, { line: index, ch: fch - CURSOR_ANCHOR_DNA.length })
} else {
Object.assign(acc.focus, { line: index, ch: fch })
Object.assign(acc.anchor, { line: index, ch: ach - CURSOR_FOCUS_DNA.length })
}
} else if (ach > -1) {
Object.assign(acc.anchor, { line: index, ch: ach })
} else if (fch > -1) {
Object.assign(acc.focus, { line: index, ch: fch })
}
return acc
}, {
anchor: {
line: 0,
ch: 0
},
focus: {
line: 0,
ch: 0
}
})
// remove CURSOR_FOCUS_DNA and CURSOR_ANCHOR_DNA
anchorBlock.text = anchorText
focusBlock.text = focusText
return cursor
}
ContentState.prototype.addCursorToMarkdown = function (markdown, cursor) {
const { anchor, focus } = cursor
if (!anchor || !focus) {
return
}
const lines = markdown.split('\n')
const anchorText = lines[anchor.line]
const focusText = lines[focus.line]
if (!anchorText || !focusText) {
return {
markdown: lines.join('\n'),
isValid: false
}
}
if (anchor.line === focus.line) {
const minOffset = Math.min(anchor.ch, focus.ch)
const maxOffset = Math.max(anchor.ch, focus.ch)
const firstTextPart = anchorText.substring(0, minOffset)
const secondTextPart = anchorText.substring(minOffset, maxOffset)
const thirdTextPart = anchorText.substring(maxOffset)
lines[anchor.line] = firstTextPart +
(anchor.ch <= focus.ch ? CURSOR_ANCHOR_DNA : CURSOR_FOCUS_DNA) +
secondTextPart +
(anchor.ch <= focus.ch ? CURSOR_FOCUS_DNA : CURSOR_ANCHOR_DNA) +
thirdTextPart
} else {
lines[anchor.line] = anchorText.substring(0, anchor.ch) + CURSOR_ANCHOR_DNA + anchorText.substring(anchor.ch)
lines[focus.line] = focusText.substring(0, focus.ch) + CURSOR_FOCUS_DNA + focusText.substring(focus.ch)
}
return {
markdown: lines.join('\n'),
isValid: true
}
}
ContentState.prototype.importCursor = function (hasCursor) {
// set cursor
const cursor = {
anchor: null,
focus: null
}
let count = 0
const travel = blocks => {
for (const block of blocks) {
let { key, text, children, editable } = block
if (text) {
const offset = text.indexOf(CURSOR_ANCHOR_DNA)
if (offset > -1) {
block.text = text.substring(0, offset) + text.substring(offset + CURSOR_ANCHOR_DNA.length)
text = block.text
count++
if (editable) {
cursor.anchor = { key, offset }
}
}
const focusOffset = text.indexOf(CURSOR_FOCUS_DNA)
if (focusOffset > -1) {
block.text = text.substring(0, focusOffset) + text.substring(focusOffset + CURSOR_FOCUS_DNA.length)
count++
if (editable) {
cursor.focus = { key, offset: focusOffset }
}
}
if (count === 2) {
break
}
} else if (children.length) {
travel(children)
}
}
}
if (hasCursor) {
travel(this.blocks)
} else {
const lastBlock = this.getLastBlock()
const key = lastBlock.key
const offset = lastBlock.text.length
cursor.anchor = { key, offset }
cursor.focus = { key, offset }
}
if (cursor.anchor && cursor.focus) {
this.cursor = cursor
}
}
ContentState.prototype.importMarkdown = function (markdown) {
this.blocks = this.markdownToState(markdown)
}
ContentState.prototype.extractImages = function (markdown) {
const results = new Set()
const blocks = this.markdownToState(markdown)
const render = new StateRender(this.muya)
render.collectLabels(blocks)
const travelToken = token => {
const { type, attrs, children, tag, label, backlash } = token
if (/reference_image|image/.test(type) || type === 'html_tag' && tag === 'img') {
if ((type === 'image' || type === 'html_tag') && attrs.src) {
results.add(attrs.src)
} else {
const rawSrc = label + backlash.second
if (render.labels.has((rawSrc).toLowerCase())) {
const { href } = render.labels.get(rawSrc.toLowerCase())
const { src } = getImageInfo(href)
if (src) {
results.add(src)
}
}
}
} else if (children && children.length) {
for (const child of children) {
travelToken(child)
}
}
}
const travel = block => {
const { text, children, type, functionType } = block
if (children.length) {
for (const b of children) {
travel(b)
}
} else if (text && type === 'span' && /paragraphContent|atxLine|cellContent/.test(functionType)) {
const tokens = tokenizer(text, [], false, render.labels)
for (const token of tokens) {
travelToken(token)
}
}
}
for (const block of blocks) {
travel(block)
}
return Array.from(results)
}
}
export default importRegister
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/assets/libs/snap.svg-min.js | src/muya/lib/assets/libs/snap.svg-min.js | // Snap.svg 0.5.1
//
// Copyright (c) 2013 – 2017 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// build: 2017-02-07
!function(a){var b,c,d="0.5.0",e="hasOwnProperty",f=/[\.\/]/,g=/\s*,\s*/,h="*",i=function(a,b){return a-b},j={n:{}},k=function(){for(var a=0,b=this.length;b>a;a++)if("undefined"!=typeof this[a])return this[a]},l=function(){for(var a=this.length;--a;)if("undefined"!=typeof this[a])return this[a]},m=Object.prototype.toString,n=String,o=Array.isArray||function(a){return a instanceof Array||"[object Array]"==m.call(a)};eve=function(a,d){var e,f=c,g=Array.prototype.slice.call(arguments,2),h=eve.listeners(a),j=0,m=[],n={},o=[],p=b;o.firstDefined=k,o.lastDefined=l,b=a,c=0;for(var q=0,r=h.length;r>q;q++)"zIndex"in h[q]&&(m.push(h[q].zIndex),h[q].zIndex<0&&(n[h[q].zIndex]=h[q]));for(m.sort(i);m[j]<0;)if(e=n[m[j++]],o.push(e.apply(d,g)),c)return c=f,o;for(q=0;r>q;q++)if(e=h[q],"zIndex"in e)if(e.zIndex==m[j]){if(o.push(e.apply(d,g)),c)break;do if(j++,e=n[m[j]],e&&o.push(e.apply(d,g)),c)break;while(e)}else n[e.zIndex]=e;else if(o.push(e.apply(d,g)),c)break;return c=f,b=p,o},eve._events=j,eve.listeners=function(a){var b,c,d,e,g,i,k,l,m=o(a)?a:a.split(f),n=j,p=[n],q=[];for(e=0,g=m.length;g>e;e++){for(l=[],i=0,k=p.length;k>i;i++)for(n=p[i].n,c=[n[m[e]],n[h]],d=2;d--;)b=c[d],b&&(l.push(b),q=q.concat(b.f||[]));p=l}return q},eve.separator=function(a){a?(a=n(a).replace(/(?=[\.\^\]\[\-])/g,"\\"),a="["+a+"]",f=new RegExp(a)):f=/[\.\/]/},eve.on=function(a,b){if("function"!=typeof b)return function(){};for(var c=o(a)?o(a[0])?a:[a]:n(a).split(g),d=0,e=c.length;e>d;d++)!function(a){for(var c,d=o(a)?a:n(a).split(f),e=j,g=0,h=d.length;h>g;g++)e=e.n,e=e.hasOwnProperty(d[g])&&e[d[g]]||(e[d[g]]={n:{}});for(e.f=e.f||[],g=0,h=e.f.length;h>g;g++)if(e.f[g]==b){c=!0;break}!c&&e.f.push(b)}(c[d]);return function(a){+a==+a&&(b.zIndex=+a)}},eve.f=function(a){var b=[].slice.call(arguments,1);return function(){eve.apply(null,[a,null].concat(b).concat([].slice.call(arguments,0)))}},eve.stop=function(){c=1},eve.nt=function(a){var c=o(b)?b.join("."):b;return a?new RegExp("(?:\\.|\\/|^)"+a+"(?:\\.|\\/|$)").test(c):c},eve.nts=function(){return o(b)?b:b.split(f)},eve.off=eve.unbind=function(a,b){if(!a)return void(eve._events=j={n:{}});var c=o(a)?o(a[0])?a:[a]:n(a).split(g);if(c.length>1)for(var d=0,i=c.length;i>d;d++)eve.off(c[d],b);else{c=o(a)?a:n(a).split(f);var k,l,m,d,i,p,q,r=[j],s=[];for(d=0,i=c.length;i>d;d++)for(p=0;p<r.length;p+=m.length-2){if(m=[p,1],k=r[p].n,c[d]!=h)k[c[d]]&&(m.push(k[c[d]]),s.unshift({n:k,name:c[d]}));else for(l in k)k[e](l)&&(m.push(k[l]),s.unshift({n:k,name:l}));r.splice.apply(r,m)}for(d=0,i=r.length;i>d;d++)for(k=r[d];k.n;){if(b){if(k.f){for(p=0,q=k.f.length;q>p;p++)if(k.f[p]==b){k.f.splice(p,1);break}!k.f.length&&delete k.f}for(l in k.n)if(k.n[e](l)&&k.n[l].f){var t=k.n[l].f;for(p=0,q=t.length;q>p;p++)if(t[p]==b){t.splice(p,1);break}!t.length&&delete k.n[l].f}}else{delete k.f;for(l in k.n)k.n[e](l)&&k.n[l].f&&delete k.n[l].f}k=k.n}a:for(d=0,i=s.length;i>d;d++){k=s[d];for(l in k.n[k.name].f)continue a;for(l in k.n[k.name].n)continue a;delete k.n[k.name]}}},eve.once=function(a,b){var c=function(){return eve.off(a,c),b.apply(this,arguments)};return eve.on(a,c)},eve.version=d,eve.toString=function(){return"You are running Eve "+d},"undefined"!=typeof module&&module.exports?module.exports=eve:"function"==typeof define&&define.amd?define("eve",[],function(){return eve}):a.eve=eve}(this),function(a,b){if("function"==typeof define&&define.amd)define(["eve"],function(c){return b(a,c)});else if("undefined"!=typeof exports){var c=require("eve");module.exports=b(a,c)}else b(a,a.eve)}(window||this,function(a,b){var c=function(b){var c,d={},e=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame||a.msRequestAnimationFrame||function(a){return setTimeout(a,16,(new Date).getTime()),!0},f=Array.isArray||function(a){return a instanceof Array||"[object Array]"==Object.prototype.toString.call(a)},g=0,h="M"+(+new Date).toString(36),i=function(){return h+(g++).toString(36)},j=Date.now||function(){return+new Date},k=function(a){var b=this;if(null==a)return b.s;var c=b.s-a;b.b+=b.dur*c,b.B+=b.dur*c,b.s=a},l=function(a){var b=this;return null==a?b.spd:void(b.spd=a)},m=function(a){var b=this;return null==a?b.dur:(b.s=b.s*a/b.dur,void(b.dur=a))},n=function(){var a=this;delete d[a.id],a.update(),b("mina.stop."+a.id,a)},o=function(){var a=this;a.pdif||(delete d[a.id],a.update(),a.pdif=a.get()-a.b)},p=function(){var a=this;a.pdif&&(a.b=a.get()-a.pdif,delete a.pdif,d[a.id]=a,r())},q=function(){var a,b=this;if(f(b.start)){a=[];for(var c=0,d=b.start.length;d>c;c++)a[c]=+b.start[c]+(b.end[c]-b.start[c])*b.easing(b.s)}else a=+b.start+(b.end-b.start)*b.easing(b.s);b.set(a)},r=function(a){if(!a)return void(c||(c=e(r)));var f=0;for(var g in d)if(d.hasOwnProperty(g)){var h=d[g],i=h.get();f++,h.s=(i-h.b)/(h.dur/h.spd),h.s>=1&&(delete d[g],h.s=1,f--,function(a){setTimeout(function(){b("mina.finish."+a.id,a)})}(h)),h.update()}c=f?e(r):!1},s=function(a,b,c,e,f,g,h){var j={id:i(),start:a,end:b,b:c,s:0,dur:e-c,spd:1,get:f,set:g,easing:h||s.linear,status:k,speed:l,duration:m,stop:n,pause:o,resume:p,update:q};d[j.id]=j;var t,u=0;for(t in d)if(d.hasOwnProperty(t)&&(u++,2==u))break;return 1==u&&r(),j};return s.time=j,s.getById=function(a){return d[a]||null},s.linear=function(a){return a},s.easeout=function(a){return Math.pow(a,1.7)},s.easein=function(a){return Math.pow(a,.48)},s.easeinout=function(a){if(1==a)return 1;if(0==a)return 0;var b=.48-a/1.04,c=Math.sqrt(.1734+b*b),d=c-b,e=Math.pow(Math.abs(d),1/3)*(0>d?-1:1),f=-c-b,g=Math.pow(Math.abs(f),1/3)*(0>f?-1:1),h=e+g+.5;return 3*(1-h)*h*h+h*h*h},s.backin=function(a){if(1==a)return 1;var b=1.70158;return a*a*((b+1)*a-b)},s.backout=function(a){if(0==a)return 0;a-=1;var b=1.70158;return a*a*((b+1)*a+b)+1},s.elastic=function(a){return a==!!a?a:Math.pow(2,-10*a)*Math.sin((a-.075)*(2*Math.PI)/.3)+1},s.bounce=function(a){var b,c=7.5625,d=2.75;return 1/d>a?b=c*a*a:2/d>a?(a-=1.5/d,b=c*a*a+.75):2.5/d>a?(a-=2.25/d,b=c*a*a+.9375):(a-=2.625/d,b=c*a*a+.984375),b},a.mina=s,s}("undefined"==typeof b?function(){}:b),d=function(a){function c(a,b){if(a){if(a.nodeType)return w(a);if(e(a,"array")&&c.set)return c.set.apply(c,a);if(a instanceof s)return a;if(null==b)try{return a=y.doc.querySelector(String(a)),w(a)}catch(d){return null}}return a=null==a?"100%":a,b=null==b?"100%":b,new v(a,b)}function d(a,b){if(b){if("#text"==a&&(a=y.doc.createTextNode(b.text||b["#text"]||"")),"#comment"==a&&(a=y.doc.createComment(b.text||b["#text"]||"")),"string"==typeof a&&(a=d(a)),"string"==typeof b)return 1==a.nodeType?"xlink:"==b.substring(0,6)?a.getAttributeNS(T,b.substring(6)):"xml:"==b.substring(0,4)?a.getAttributeNS(U,b.substring(4)):a.getAttribute(b):"text"==b?a.nodeValue:null;if(1==a.nodeType){for(var c in b)if(b[z](c)){var e=A(b[c]);e?"xlink:"==c.substring(0,6)?a.setAttributeNS(T,c.substring(6),e):"xml:"==c.substring(0,4)?a.setAttributeNS(U,c.substring(4),e):a.setAttribute(c,e):a.removeAttribute(c)}}else"text"in b&&(a.nodeValue=b.text)}else a=y.doc.createElementNS(U,a);return a}function e(a,b){return b=A.prototype.toLowerCase.call(b),"finite"==b?isFinite(a):"array"==b&&(a instanceof Array||Array.isArray&&Array.isArray(a))?!0:"null"==b&&null===a||b==typeof a&&null!==a||"object"==b&&a===Object(a)||J.call(a).slice(8,-1).toLowerCase()==b}function f(a){if("function"==typeof a||Object(a)!==a)return a;var b=new a.constructor;for(var c in a)a[z](c)&&(b[c]=f(a[c]));return b}function h(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return a.push(a.splice(c,1)[0])}function i(a,b,c){function d(){var e=Array.prototype.slice.call(arguments,0),f=e.join("␀"),g=d.cache=d.cache||{},i=d.count=d.count||[];return g[z](f)?(h(i,f),c?c(g[f]):g[f]):(i.length>=1e3&&delete g[i.shift()],i.push(f),g[f]=a.apply(b,e),c?c(g[f]):g[f])}return d}function j(a,b,c,d,e,f){if(null==e){var g=a-c,h=b-d;return g||h?(180+180*D.atan2(-h,-g)/H+360)%360:0}return j(a,b,e,f)-j(c,d,e,f)}function k(a){return a%360*H/180}function l(a){return 180*a/H%360}function m(a){var b=[];return a=a.replace(/(?:^|\s)(\w+)\(([^)]+)\)/g,function(a,c,d){return d=d.split(/\s*,\s*|\s+/),"rotate"==c&&1==d.length&&d.push(0,0),"scale"==c&&(d.length>2?d=d.slice(0,2):2==d.length&&d.push(0,0),1==d.length&&d.push(d[0],0,0)),"skewX"==c?b.push(["m",1,0,D.tan(k(d[0])),1,0,0]):"skewY"==c?b.push(["m",1,D.tan(k(d[0])),0,1,0,0]):b.push([c.charAt(0)].concat(d)),a}),b}function n(a,b){var d=aa(a),e=new c.Matrix;if(d)for(var f=0,g=d.length;g>f;f++){var h,i,j,k,l,m=d[f],n=m.length,o=A(m[0]).toLowerCase(),p=m[0]!=o,q=p?e.invert():0;"t"==o&&2==n?e.translate(m[1],0):"t"==o&&3==n?p?(h=q.x(0,0),i=q.y(0,0),j=q.x(m[1],m[2]),k=q.y(m[1],m[2]),e.translate(j-h,k-i)):e.translate(m[1],m[2]):"r"==o?2==n?(l=l||b,e.rotate(m[1],l.x+l.width/2,l.y+l.height/2)):4==n&&(p?(j=q.x(m[2],m[3]),k=q.y(m[2],m[3]),e.rotate(m[1],j,k)):e.rotate(m[1],m[2],m[3])):"s"==o?2==n||3==n?(l=l||b,e.scale(m[1],m[n-1],l.x+l.width/2,l.y+l.height/2)):4==n?p?(j=q.x(m[2],m[3]),k=q.y(m[2],m[3]),e.scale(m[1],m[1],j,k)):e.scale(m[1],m[1],m[2],m[3]):5==n&&(p?(j=q.x(m[3],m[4]),k=q.y(m[3],m[4]),e.scale(m[1],m[2],j,k)):e.scale(m[1],m[2],m[3],m[4])):"m"==o&&7==n&&e.add(m[1],m[2],m[3],m[4],m[5],m[6])}return e}function o(a){var b=a.node.ownerSVGElement&&w(a.node.ownerSVGElement)||a.node.parentNode&&w(a.node.parentNode)||c.select("svg")||c(0,0),d=b.select("defs"),e=null==d?!1:d.node;return e||(e=u("defs",b.node).node),e}function p(a){return a.node.ownerSVGElement&&w(a.node.ownerSVGElement)||c.select("svg")}function q(a,b,c){function e(a){if(null==a)return I;if(a==+a)return a;d(j,{width:a});try{return j.getBBox().width}catch(b){return 0}}function f(a){if(null==a)return I;if(a==+a)return a;d(j,{height:a});try{return j.getBBox().height}catch(b){return 0}}function g(d,e){null==b?i[d]=e(a.attr(d)||0):d==b&&(i=e(null==c?a.attr(d)||0:c))}var h=p(a).node,i={},j=h.querySelector(".svg---mgr");switch(j||(j=d("rect"),d(j,{x:-9e9,y:-9e9,width:10,height:10,"class":"svg---mgr",fill:"none"}),h.appendChild(j)),a.type){case"rect":g("rx",e),g("ry",f);case"image":g("width",e),g("height",f);case"text":g("x",e),g("y",f);break;case"circle":g("cx",e),g("cy",f),g("r",e);break;case"ellipse":g("cx",e),g("cy",f),g("rx",e),g("ry",f);break;case"line":g("x1",e),g("x2",e),g("y1",f),g("y2",f);break;case"marker":g("refX",e),g("markerWidth",e),g("refY",f),g("markerHeight",f);break;case"radialGradient":g("fx",e),g("fy",f);break;case"tspan":g("dx",e),g("dy",f);break;default:g(b,e)}return h.removeChild(j),i}function r(a){e(a,"array")||(a=Array.prototype.slice.call(arguments,0));for(var b=0,c=0,d=this.node;this[b];)delete this[b++];for(b=0;b<a.length;b++)"set"==a[b].type?a[b].forEach(function(a){d.appendChild(a.node)}):d.appendChild(a[b].node);var f=d.childNodes;for(b=0;b<f.length;b++)this[c++]=w(f[b]);return this}function s(a){if(a.snap in V)return V[a.snap];var b;try{b=a.ownerSVGElement}catch(c){}this.node=a,b&&(this.paper=new v(b)),this.type=a.tagName||a.nodeName;var d=this.id=S(this);if(this.anims={},this._={transform:[]},a.snap=d,V[d]=this,"g"==this.type&&(this.add=r),this.type in{g:1,mask:1,pattern:1,symbol:1})for(var e in v.prototype)v.prototype[z](e)&&(this[e]=v.prototype[e])}function t(a){this.node=a}function u(a,b){var c=d(a);b.appendChild(c);var e=w(c);return e}function v(a,b){var c,e,f,g=v.prototype;if(a&&a.tagName&&"svg"==a.tagName.toLowerCase()){if(a.snap in V)return V[a.snap];var h=a.ownerDocument;c=new s(a),e=a.getElementsByTagName("desc")[0],f=a.getElementsByTagName("defs")[0],e||(e=d("desc"),e.appendChild(h.createTextNode("Created with Snap")),c.node.appendChild(e)),f||(f=d("defs"),c.node.appendChild(f)),c.defs=f;for(var i in g)g[z](i)&&(c[i]=g[i]);c.paper=c.root=c}else c=u("svg",y.doc.body),d(c.node,{height:b,version:1.1,width:a,xmlns:U});return c}function w(a){return a?a instanceof s||a instanceof t?a:a.tagName&&"svg"==a.tagName.toLowerCase()?new v(a):a.tagName&&"object"==a.tagName.toLowerCase()&&"image/svg+xml"==a.type?new v(a.contentDocument.getElementsByTagName("svg")[0]):new s(a):a}function x(a,b){for(var c=0,d=a.length;d>c;c++){var e={type:a[c].type,attr:a[c].attr()},f=a[c].children();b.push(e),f.length&&x(f,e.childNodes=[])}}c.version="0.5.1",c.toString=function(){return"Snap v"+this.version},c._={};var y={win:a.window,doc:a.window.document};c._.glob=y;var z="hasOwnProperty",A=String,B=parseFloat,C=parseInt,D=Math,E=D.max,F=D.min,G=D.abs,H=(D.pow,D.PI),I=(D.round,""),J=Object.prototype.toString,K=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\))\s*$/i,L=(c._.separator=/[,\s]+/,/[\s]*,[\s]*/),M={hs:1,rg:1},N=/([a-z])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/gi,O=/([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/gi,P=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\s]*,?[\s]*/gi,Q=0,R="S"+(+new Date).toString(36),S=function(a){return(a&&a.type?a.type:I)+R+(Q++).toString(36)},T="http://www.w3.org/1999/xlink",U="http://www.w3.org/2000/svg",V={};c.url=function(a){return"url('#"+a+"')"};c._.$=d,c._.id=S,c.format=function(){var a=/\{([^\}]+)\}/g,b=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,c=function(a,c,d){var e=d;return c.replace(b,function(a,b,c,d,f){b=b||d,e&&(b in e&&(e=e[b]),"function"==typeof e&&f&&(e=e()))}),e=(null==e||e==d?a:e)+""};return function(b,d){return A(b).replace(a,function(a,b){return c(a,b,d)})}}(),c._.clone=f,c._.cacher=i,c.rad=k,c.deg=l,c.sin=function(a){return D.sin(c.rad(a))},c.tan=function(a){return D.tan(c.rad(a))},c.cos=function(a){return D.cos(c.rad(a))},c.asin=function(a){return c.deg(D.asin(a))},c.acos=function(a){return c.deg(D.acos(a))},c.atan=function(a){return c.deg(D.atan(a))},c.atan2=function(a){return c.deg(D.atan2(a))},c.angle=j,c.len=function(a,b,d,e){return Math.sqrt(c.len2(a,b,d,e))},c.len2=function(a,b,c,d){return(a-c)*(a-c)+(b-d)*(b-d)},c.closestPoint=function(a,b,c){function d(a){var d=a.x-b,e=a.y-c;return d*d+e*e}for(var e,f,g,h,i=a.node,j=i.getTotalLength(),k=j/i.pathSegList.numberOfItems*.125,l=1/0,m=0;j>=m;m+=k)(h=d(g=i.getPointAtLength(m)))<l&&(e=g,f=m,l=h);for(k*=.5;k>.5;){var n,o,p,q,r,s;(p=f-k)>=0&&(r=d(n=i.getPointAtLength(p)))<l?(e=n,f=p,l=r):(q=f+k)<=j&&(s=d(o=i.getPointAtLength(q)))<l?(e=o,f=q,l=s):k*=.5}return e={x:e.x,y:e.y,length:f,distance:Math.sqrt(l)}},c.is=e,c.snapTo=function(a,b,c){if(c=e(c,"finite")?c:10,e(a,"array")){for(var d=a.length;d--;)if(G(a[d]-b)<=c)return a[d]}else{a=+a;var f=b%a;if(c>f)return b-f;if(f>a-c)return b-f+a}return b},c.getRGB=i(function(a){if(!a||(a=A(a)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:Z};if("none"==a)return{r:-1,g:-1,b:-1,hex:"none",toString:Z};if(!(M[z](a.toLowerCase().substring(0,2))||"#"==a.charAt())&&(a=W(a)),!a)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:Z};var b,d,f,g,h,i,j=a.match(K);return j?(j[2]&&(f=C(j[2].substring(5),16),d=C(j[2].substring(3,5),16),b=C(j[2].substring(1,3),16)),j[3]&&(f=C((h=j[3].charAt(3))+h,16),d=C((h=j[3].charAt(2))+h,16),b=C((h=j[3].charAt(1))+h,16)),j[4]&&(i=j[4].split(L),b=B(i[0]),"%"==i[0].slice(-1)&&(b*=2.55),d=B(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),f=B(i[2]),"%"==i[2].slice(-1)&&(f*=2.55),"rgba"==j[1].toLowerCase().slice(0,4)&&(g=B(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100)),j[5]?(i=j[5].split(L),b=B(i[0]),"%"==i[0].slice(-1)&&(b/=100),d=B(i[1]),"%"==i[1].slice(-1)&&(d/=100),f=B(i[2]),"%"==i[2].slice(-1)&&(f/=100),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(b/=360),"hsba"==j[1].toLowerCase().slice(0,4)&&(g=B(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),c.hsb2rgb(b,d,f,g)):j[6]?(i=j[6].split(L),b=B(i[0]),"%"==i[0].slice(-1)&&(b/=100),d=B(i[1]),"%"==i[1].slice(-1)&&(d/=100),f=B(i[2]),"%"==i[2].slice(-1)&&(f/=100),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(b/=360),"hsla"==j[1].toLowerCase().slice(0,4)&&(g=B(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),c.hsl2rgb(b,d,f,g)):(b=F(D.round(b),255),d=F(D.round(d),255),f=F(D.round(f),255),g=F(E(g,0),1),j={r:b,g:d,b:f,toString:Z},j.hex="#"+(16777216|f|d<<8|b<<16).toString(16).slice(1),j.opacity=e(g,"finite")?g:1,j)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:Z}},c),c.hsb=i(function(a,b,d){return c.hsb2rgb(a,b,d).hex}),c.hsl=i(function(a,b,d){return c.hsl2rgb(a,b,d).hex}),c.rgb=i(function(a,b,c,d){if(e(d,"finite")){var f=D.round;return"rgba("+[f(a),f(b),f(c),+d.toFixed(2)]+")"}return"#"+(16777216|c|b<<8|a<<16).toString(16).slice(1)});var W=function(a){var b=y.doc.getElementsByTagName("head")[0]||y.doc.getElementsByTagName("svg")[0],c="rgb(255, 0, 0)";return(W=i(function(a){if("red"==a.toLowerCase())return c;b.style.color=c,b.style.color=a;var d=y.doc.defaultView.getComputedStyle(b,I).getPropertyValue("color");return d==c?null:d}))(a)},X=function(){return"hsb("+[this.h,this.s,this.b]+")"},Y=function(){return"hsl("+[this.h,this.s,this.l]+")"},Z=function(){return 1==this.opacity||null==this.opacity?this.hex:"rgba("+[this.r,this.g,this.b,this.opacity]+")"},$=function(a,b,d){if(null==b&&e(a,"object")&&"r"in a&&"g"in a&&"b"in a&&(d=a.b,b=a.g,a=a.r),null==b&&e(a,string)){var f=c.getRGB(a);a=f.r,b=f.g,d=f.b}return(a>1||b>1||d>1)&&(a/=255,b/=255,d/=255),[a,b,d]},_=function(a,b,d,f){a=D.round(255*a),b=D.round(255*b),d=D.round(255*d);var g={r:a,g:b,b:d,opacity:e(f,"finite")?f:1,hex:c.rgb(a,b,d),toString:Z};return e(f,"finite")&&(g.opacity=f),g};c.color=function(a){var b;return e(a,"object")&&"h"in a&&"s"in a&&"b"in a?(b=c.hsb2rgb(a),a.r=b.r,a.g=b.g,a.b=b.b,a.opacity=1,a.hex=b.hex):e(a,"object")&&"h"in a&&"s"in a&&"l"in a?(b=c.hsl2rgb(a),a.r=b.r,a.g=b.g,a.b=b.b,a.opacity=1,a.hex=b.hex):(e(a,"string")&&(a=c.getRGB(a)),e(a,"object")&&"r"in a&&"g"in a&&"b"in a&&!("error"in a)?(b=c.rgb2hsl(a),a.h=b.h,a.s=b.s,a.l=b.l,b=c.rgb2hsb(a),a.v=b.b):(a={hex:"none"},a.r=a.g=a.b=a.h=a.s=a.v=a.l=-1,a.error=1)),a.toString=Z,a},c.hsb2rgb=function(a,b,c,d){e(a,"object")&&"h"in a&&"s"in a&&"b"in a&&(c=a.b,b=a.s,d=a.o,a=a.h),a*=360;var f,g,h,i,j;return a=a%360/60,j=c*b,i=j*(1-G(a%2-1)),f=g=h=c-j,a=~~a,f+=[j,i,0,0,i,j][a],g+=[i,j,j,i,0,0][a],h+=[0,0,i,j,j,i][a],_(f,g,h,d)},c.hsl2rgb=function(a,b,c,d){e(a,"object")&&"h"in a&&"s"in a&&"l"in a&&(c=a.l,b=a.s,a=a.h),(a>1||b>1||c>1)&&(a/=360,b/=100,c/=100),a*=360;var f,g,h,i,j;return a=a%360/60,j=2*b*(.5>c?c:1-c),i=j*(1-G(a%2-1)),f=g=h=c-j/2,a=~~a,f+=[j,i,0,0,i,j][a],g+=[i,j,j,i,0,0][a],h+=[0,0,i,j,j,i][a],_(f,g,h,d)},c.rgb2hsb=function(a,b,c){c=$(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g;return f=E(a,b,c),g=f-F(a,b,c),d=0==g?null:f==a?(b-c)/g:f==b?(c-a)/g+2:(a-b)/g+4,d=(d+360)%6*60/360,e=0==g?0:g/f,{h:d,s:e,b:f,toString:X}},c.rgb2hsl=function(a,b,c){c=$(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g,h,i;return g=E(a,b,c),h=F(a,b,c),i=g-h,d=0==i?null:g==a?(b-c)/i:g==b?(c-a)/i+2:(a-b)/i+4,d=(d+360)%6*60/360,f=(g+h)/2,e=0==i?0:.5>f?i/(2*f):i/(2-2*f),{h:d,s:e,l:f,toString:Y}},c.parsePathString=function(a){if(!a)return null;var b=c.path(a);if(b.arr)return c.path.clone(b.arr);var d={a:7,c:6,o:2,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,u:3,z:0},f=[];return e(a,"array")&&e(a[0],"array")&&(f=c.path.clone(a)),f.length||A(a).replace(N,function(a,b,c){var e=[],g=b.toLowerCase();if(c.replace(P,function(a,b){b&&e.push(+b)}),"m"==g&&e.length>2&&(f.push([b].concat(e.splice(0,2))),g="l",b="m"==b?"l":"L"),"o"==g&&1==e.length&&f.push([b,e[0]]),"r"==g)f.push([b].concat(e));else for(;e.length>=d[g]&&(f.push([b].concat(e.splice(0,d[g]))),d[g]););}),f.toString=c.path.toString,b.arr=c.path.clone(f),f};var aa=c.parseTransformString=function(a){if(!a)return null;var b=[];return e(a,"array")&&e(a[0],"array")&&(b=c.path.clone(a)),b.length||A(a).replace(O,function(a,c,d){var e=[];c.toLowerCase();d.replace(P,function(a,b){b&&e.push(+b)}),b.push([c].concat(e))}),b.toString=c.path.toString,b};c._.svgTransform2string=m,c._.rgTransform=/^[a-z][\s]*-?\.?\d/i,c._.transform2matrix=n,c._unit2px=q;y.doc.contains||y.doc.compareDocumentPosition?function(a,b){var c=9==a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a==d||!(!d||1!=d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b;)if(b=b.parentNode,b==a)return!0;return!1};c._.getSomeDefs=o,c._.getSomeSVG=p,c.select=function(a){return a=A(a).replace(/([^\\]):/g,"$1\\:"),w(y.doc.querySelector(a))},c.selectAll=function(a){for(var b=y.doc.querySelectorAll(a),d=(c.set||Array)(),e=0;e<b.length;e++)d.push(w(b[e]));return d},setInterval(function(){for(var a in V)if(V[z](a)){var b=V[a],c=b.node;("svg"!=b.type&&!c.ownerSVGElement||"svg"==b.type&&(!c.parentNode||"ownerSVGElement"in c.parentNode&&!c.ownerSVGElement))&&delete V[a]}},1e4),s.prototype.attr=function(a,c){var d=this,f=d.node;if(!a){if(1!=f.nodeType)return{text:f.nodeValue};for(var g=f.attributes,h={},i=0,j=g.length;j>i;i++)h[g[i].nodeName]=g[i].nodeValue;return h}if(e(a,"string")){if(!(arguments.length>1))return b("snap.util.getattr."+a,d).firstDefined();var k={};k[a]=c,a=k}for(var l in a)a[z](l)&&b("snap.util.attr."+l,d,a[l]);return d},c.parse=function(a){var b=y.doc.createDocumentFragment(),c=!0,d=y.doc.createElement("div");if(a=A(a),a.match(/^\s*<\s*svg(?:\s|>)/)||(a="<svg>"+a+"</svg>",c=!1),d.innerHTML=a,a=d.getElementsByTagName("svg")[0])if(c)b=a;else for(;a.firstChild;)b.appendChild(a.firstChild);return new t(b)},c.fragment=function(){for(var a=Array.prototype.slice.call(arguments,0),b=y.doc.createDocumentFragment(),d=0,e=a.length;e>d;d++){var f=a[d];f.node&&f.node.nodeType&&b.appendChild(f.node),f.nodeType&&b.appendChild(f),"string"==typeof f&&b.appendChild(c.parse(f).node)}return new t(b)},c._.make=u,c._.wrap=w,v.prototype.el=function(a,b){var c=u(a,this.node);return b&&c.attr(b),c},s.prototype.children=function(){for(var a=[],b=this.node.childNodes,d=0,e=b.length;e>d;d++)a[d]=c(b[d]);return a},s.prototype.toJSON=function(){var a=[];return x([this],a),a[0]},b.on("snap.util.getattr",function(){var a=b.nt();a=a.substring(a.lastIndexOf(".")+1);var c=a.replace(/[A-Z]/g,function(a){return"-"+a.toLowerCase()});return ba[z](c)?this.node.ownerDocument.defaultView.getComputedStyle(this.node,null).getPropertyValue(c):d(this.node,a)});var ba={"alignment-baseline":0,"baseline-shift":0,clip:0,"clip-path":0,"clip-rule":0,color:0,"color-interpolation":0,"color-interpolation-filters":0,"color-profile":0,"color-rendering":0,cursor:0,direction:0,display:0,"dominant-baseline":0,"enable-background":0,fill:0,"fill-opacity":0,"fill-rule":0,filter:0,"flood-color":0,"flood-opacity":0,font:0,"font-family":0,"font-size":0,"font-size-adjust":0,"font-stretch":0,"font-style":0,"font-variant":0,"font-weight":0,"glyph-orientation-horizontal":0,"glyph-orientation-vertical":0,"image-rendering":0,kerning:0,"letter-spacing":0,"lighting-color":0,marker:0,"marker-end":0,"marker-mid":0,"marker-start":0,mask:0,opacity:0,overflow:0,"pointer-events":0,"shape-rendering":0,"stop-color":0,"stop-opacity":0,stroke:0,"stroke-dasharray":0,"stroke-dashoffset":0,"stroke-linecap":0,"stroke-linejoin":0,"stroke-miterlimit":0,"stroke-opacity":0,"stroke-width":0,"text-anchor":0,"text-decoration":0,"text-rendering":0,"unicode-bidi":0,visibility:0,"word-spacing":0,"writing-mode":0};b.on("snap.util.attr",function(a){var c=b.nt(),e={};c=c.substring(c.lastIndexOf(".")+1),e[c]=a;var f=c.replace(/-(\w)/gi,function(a,b){return b.toUpperCase()}),g=c.replace(/[A-Z]/g,function(a){return"-"+a.toLowerCase()});ba[z](g)?this.node.style[f]=null==a?I:a:d(this.node,e)}),function(a){}(v.prototype),c.ajax=function(a,c,d,f){var g=new XMLHttpRequest,h=S();if(g){if(e(c,"function"))f=d,d=c,c=null;else if(e(c,"object")){var i=[];for(var j in c)c.hasOwnProperty(j)&&i.push(encodeURIComponent(j)+"="+encodeURIComponent(c[j]));c=i.join("&")}return g.open(c?"POST":"GET",a,!0),c&&(g.setRequestHeader("X-Requested-With","XMLHttpRequest"),g.setRequestHeader("Content-type","application/x-www-form-urlencoded")),d&&(b.once("snap.ajax."+h+".0",d),b.once("snap.ajax."+h+".200",d),b.once("snap.ajax."+h+".304",d)),g.onreadystatechange=function(){4==g.readyState&&b("snap.ajax."+h+"."+g.status,f,g)},4==g.readyState?g:(g.send(c),g)}},c.load=function(a,b,d){c.ajax(a,function(a){var e=c.parse(a.responseText);d?b.call(d,e):b(e)})};var ca=function(a){var b=a.getBoundingClientRect(),c=a.ownerDocument,d=c.body,e=c.documentElement,f=e.clientTop||d.clientTop||0,h=e.clientLeft||d.clientLeft||0,i=b.top+(g.win.pageYOffset||e.scrollTop||d.scrollTop)-f,j=b.left+(g.win.pageXOffset||e.scrollLeft||d.scrollLeft)-h;return{y:i,x:j}};return c.getElementByPoint=function(a,b){var c=this,d=(c.canvas,y.doc.elementFromPoint(a,b));if(y.win.opera&&"svg"==d.tagName){var e=ca(d),f=d.createSVGRect();f.x=a-e.x,f.y=b-e.y,f.width=f.height=1;var g=d.getIntersectionList(f,null);g.length&&(d=g[g.length-1])}return d?w(d):null},c.plugin=function(a){a(c,s,v,y,t)},y.win.Snap=c,c}(a||this);return d.plugin(function(c,d,e,f,g){function h(a,b){if(null==b){var d=!0;if(b="linearGradient"==a.type||"radialGradient"==a.type?a.node.getAttribute("gradientTransform"):"pattern"==a.type?a.node.getAttribute("patternTransform"):a.node.getAttribute("transform"),!b)return new c.Matrix;b=c._.svgTransform2string(b)}else b=c._.rgTransform.test(b)?m(b).replace(/\.{3}|\u2026/g,a._.transform||""):c._.svgTransform2string(b),l(b,"array")&&(b=c.path?c.path.toString.call(b):m(b)),a._.transform=b;var e=c._.transform2matrix(b,a.getBBox(1));return d?e:void(a.matrix=e)}function i(a){function b(a,b){var d=o(a.node,b);d=d&&d.match(g),d=d&&d[2],d&&"#"==d.charAt()&&(d=d.substring(1),d&&(i[d]=(i[d]||[]).concat(function(d){var e={};e[b]=c.url(d),o(a.node,e)})))}function d(a){var b=o(a.node,"xlink:href");b&&"#"==b.charAt()&&(b=b.substring(1),b&&(i[b]=(i[b]||[]).concat(function(b){a.attr("xlink:href","#"+b)})))}for(var e,f=a.selectAll("*"),g=/^\s*url\(("|'|)(.*)\1\)\s*$/,h=[],i={},j=0,k=f.length;k>j;j++){e=f[j],b(e,"fill"),b(e,"stroke"),b(e,"filter"),b(e,"mask"),b(e,"clip-path"),d(e);var l=o(e.node,"id");l&&(o(e.node,{id:e.id}),h.push({old:l,id:e.id}))}for(j=0,k=h.length;k>j;j++){var m=i[h[j].old];if(m)for(var n=0,p=m.length;p>n;n++)m[n](h[j].id)}}function j(a){return function(){var b=a?"<"+this.type:"",c=this.node.attributes,d=this.node.childNodes;if(a)for(var e=0,f=c.length;f>e;e++)b+=" "+c[e].name+'="'+c[e].value.replace(/"/g,'\\"')+'"';if(d.length){for(a&&(b+=">"),e=0,f=d.length;f>e;e++)3==d[e].nodeType?b+=d[e].nodeValue:1==d[e].nodeType&&(b+=s(d[e]).toString());a&&(b+="</"+this.type+">")}else a&&(b+="/>");return b}}var k=d.prototype,l=c.is,m=String,n=c._unit2px,o=c._.$,p=c._.make,q=c._.getSomeDefs,r="hasOwnProperty",s=c._.wrap;k.getBBox=function(a){if("tspan"==this.type)return c._.box(this.node.getClientRects().item(0));if(!c.Matrix||!c.path)return this.node.getBBox();var b=this,d=new c.Matrix;if(b.removed)return c._.box();for(;"use"==b.type;)if(a||(d=d.add(b.transform().localMatrix.translate(b.attr("x")||0,b.attr("y")||0))),b.original)b=b.original;else{var e=b.attr("xlink:href");b=b.original=b.node.ownerDocument.getElementById(e.substring(e.indexOf("#")+1))}var f=b._,g=c.path.get[b.type]||c.path.get.deflt;try{return a?(f.bboxwt=g?c.path.getBBox(b.realPath=g(b)):c._.box(b.node.getBBox()),c._.box(f.bboxwt)):(b.realPath=g(b),b.matrix=b.transform().localMatrix,f.bbox=c.path.getBBox(c.path.map(b.realPath,d.add(b.matrix))),c._.box(f.bbox))}catch(h){return c._.box()}};var t=function(){return this.string};k.transform=function(a){var b=this._;if(null==a){for(var d,e=this,f=new c.Matrix(this.node.getCTM()),g=h(this),i=[g],j=new c.Matrix,k=g.toTransformString(),l=m(g)==m(this.matrix)?m(b.transform):k;"svg"!=e.type&&(e=e.parent());)i.push(h(e));for(d=i.length;d--;)j.add(i[d]);return{string:l,globalMatrix:f,totalMatrix:j,localMatrix:g,diffMatrix:f.clone().add(g.invert()),global:f.toTransformString(),total:j.toTransformString(),local:k,toString:t}}return a instanceof c.Matrix?(this.matrix=a,this._.transform=a.toTransformString()):h(this,a),this.node&&("linearGradient"==this.type||"radialGradient"==this.type?o(this.node,{gradientTransform:this.matrix}):"pattern"==this.type?o(this.node,{patternTransform:this.matrix}):o(this.node,{transform:this.matrix})),this},k.parent=function(){return s(this.node.parentNode)},k.append=k.add=function(a){if(a){if("set"==a.type){var b=this;return a.forEach(function(a){b.add(a)}),this}a=s(a),this.node.appendChild(a.node),a.paper=this.paper}return this},k.appendTo=function(a){return a&&(a=s(a),a.append(this)),this},k.prepend=function(a){if(a){if("set"==a.type){var b,c=this;return a.forEach(function(a){b?b.after(a):c.prepend(a),b=a}),this}a=s(a);var d=a.parent();this.node.insertBefore(a.node,this.node.firstChild),this.add&&this.add(),a.paper=this.paper,this.parent()&&this.parent().add(),d&&d.add()}return this},k.prependTo=function(a){return a=s(a),a.prepend(this),this},k.before=function(a){if("set"==a.type){var b=this;return a.forEach(function(a){var c=a.parent();b.node.parentNode.insertBefore(a.node,b.node),c&&c.add()}),this.parent().add(),this}a=s(a);var c=a.parent();return this.node.parentNode.insertBefore(a.node,this.node),this.parent()&&this.parent().add(),c&&c.add(),a.paper=this.paper,this},k.after=function(a){a=s(a);var b=a.parent();return this.node.nextSibling?this.node.parentNode.insertBefore(a.node,this.node.nextSibling):this.node.parentNode.appendChild(a.node),this.parent()&&this.parent().add(),b&&b.add(),a.paper=this.paper,this},k.insertBefore=function(a){a=s(a);var b=this.parent();return a.node.parentNode.insertBefore(this.node,a.node),this.paper=a.paper,b&&b.add(),a.parent()&&a.parent().add(),this},k.insertAfter=function(a){a=s(a);var b=this.parent();return a.node.parentNode.insertBefore(this.node,a.node.nextSibling),this.paper=a.paper,b&&b.add(),a.parent()&&a.parent().add(),this},k.remove=function(){var a=this.parent();return this.node.parentNode&&this.node.parentNode.removeChild(this.node),delete this.paper,this.removed=!0,a&&a.add(),this},k.select=function(a){return s(this.node.querySelector(a))},k.selectAll=function(a){for(var b=this.node.querySelectorAll(a),d=(c.set||Array)(),e=0;e<b.length;e++)d.push(s(b[e]));return d},k.asPX=function(a,b){return null==b&&(b=this.attr(a)),+n(this,a,b)},k.use=function(){var a,b=this.node.id;return b||(b=this.id,o(this.node,{id:b})),a="linearGradient"==this.type||"radialGradient"==this.type||"pattern"==this.type?p(this.type,this.node.parentNode):p("use",this.node.parentNode),o(a.node,{"xlink:href":"#"+b}),a.original=this,a},k.clone=function(){var a=s(this.node.cloneNode(!0));return o(a.node,"id")&&o(a.node,{id:a.id}),i(a),a.insertAfter(this),a},k.toDefs=function(){var a=q(this);return a.appendChild(this.node),this},k.pattern=k.toPattern=function(a,b,c,d){var e=p("pattern",q(this));return null==a&&(a=this.getBBox()),l(a,"object")&&"x"in a&&(b=a.y,c=a.width,d=a.height,a=a.x),o(e.node,{x:a,y:b,width:c,height:d,patternUnits:"userSpaceOnUse",id:e.id,viewBox:[a,b,c,d].join(" ")}),e.node.appendChild(this.node),e},k.marker=function(a,b,c,d,e,f){var g=p("marker",q(this));return null==a&&(a=this.getBBox()),l(a,"object")&&"x"in a&&(b=a.y,c=a.width,d=a.height,e=a.refX||a.cx,f=a.refY||a.cy,a=a.x),o(g.node,{viewBox:[a,b,c,d].join(" "),markerWidth:c,markerHeight:d,orient:"auto",refX:e||0,refY:f||0,id:g.id}),g.node.appendChild(this.node),g};var u={};k.data=function(a,d){var e=u[this.id]=u[this.id]||{};if(0==arguments.length)return b("snap.data.get."+this.id,this,e,null),e;if(1==arguments.length){if(c.is(a,"object")){for(var f in a)a[r](f)&&this.data(f,a[f]);return this}return b("snap.data.get."+this.id,this,e[a],a),e[a]}return e[a]=d,b("snap.data.set."+this.id,this,d,a),this},k.removeData=function(a){return null==a?u[this.id]={}:u[this.id]&&delete u[this.id][a],this},k.outerSVG=k.toString=j(1),k.innerSVG=j(),k.toDataURL=function(){if(a&&a.btoa){var b=this.getBBox(),d=c.format('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}" viewBox="{x} {y} {width} {height}">{contents}</svg>',{x:+b.x.toFixed(3),y:+b.y.toFixed(3),width:+b.width.toFixed(3),height:+b.height.toFixed(3),
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | true |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/assets/libs/sequence-diagram-snap.js | src/muya/lib/assets/libs/sequence-diagram-snap.js | /** js sequence diagrams 2.0.1
* https://bramp.github.io/js-sequence-diagrams/
* (c) 2012-2017 Andrew Brampton (bramp.net)
* @license Simplified BSD license.
*/
import _ from 'underscore'
import Snap from 'snapsvg'
import WebFont from 'webfontloader'
function Diagram() {
this.title = undefined;
this.actors = [];
this.signals = [];
}
/*
* Return an existing actor with this alias, or creates a new one with alias and name.
*/
Diagram.prototype.getActor = function(alias, name) {
alias = alias.trim();
var i;
var actors = this.actors;
for (i in actors) {
if (actors[i].alias == alias) {
return actors[i];
}
}
i = actors.push(new Diagram.Actor(alias, (name || alias), actors.length));
return actors[ i - 1 ];
};
/*
* Parses the input as either a alias, or a "name as alias", and returns the corresponding actor.
*/
Diagram.prototype.getActorWithAlias = function(input) {
input = input.trim();
// We are lazy and do some of the parsing in javascript :(. TODO move into the .jison file.
var s = /([\s\S]+) as (\S+)$/im.exec(input);
var alias;
var name;
if (s) {
name = s[1].trim();
alias = s[2].trim();
} else {
name = alias = input;
}
return this.getActor(alias, name);
};
Diagram.prototype.setTitle = function(title) {
this.title = title;
};
Diagram.prototype.addSignal = function(signal) {
this.signals.push(signal);
};
Diagram.Actor = function(alias, name, index) {
this.alias = alias;
this.name = name;
this.index = index;
};
Diagram.Signal = function(actorA, signaltype, actorB, message) {
this.type = 'Signal';
this.actorA = actorA;
this.actorB = actorB;
this.linetype = signaltype & 3;
this.arrowtype = (signaltype >> 2) & 3;
this.message = message;
};
Diagram.Signal.prototype.isSelf = function() {
return this.actorA.index == this.actorB.index;
};
Diagram.Note = function(actor, placement, message) {
this.type = 'Note';
this.actor = actor;
this.placement = placement;
this.message = message;
if (this.hasManyActors() && actor[0] == actor[1]) {
throw new Error('Note should be over two different actors');
}
};
Diagram.Note.prototype.hasManyActors = function() {
return _.isArray(this.actor);
};
Diagram.unescape = function(s) {
// Turn "\\n" into "\n"
return s.trim().replace(/^"(.*)"$/m, '$1').replace(/\\n/gm, '\n');
};
Diagram.LINETYPE = {
SOLID: 0,
DOTTED: 1
};
Diagram.ARROWTYPE = {
FILLED: 0,
OPEN: 1
};
Diagram.PLACEMENT = {
LEFTOF: 0,
RIGHTOF: 1,
OVER: 2
};
// Some older browsers don't have getPrototypeOf, thus we polyfill it
// https://github.com/bramp/js-sequence-diagrams/issues/57
// https://github.com/zaach/jison/issues/194
// Taken from http://ejohn.org/blog/objectgetprototypeof/
if (typeof Object.getPrototypeOf !== 'function') {
/* jshint -W103 */
if (typeof 'test'.__proto__ === 'object') {
Object.getPrototypeOf = function(object) {
return object.__proto__;
};
} else {
Object.getPrototypeOf = function(object) {
// May break if the constructor has been tampered with
return object.constructor.prototype;
};
}
/* jshint +W103 */
}
/** The following is included by preprocessor */
/* parser generated by jison 0.4.15 */
/*
Returns a Parser object of the following structure:
Parser: {
yy: {}
}
Parser.prototype: {
yy: {},
trace: function(),
symbols_: {associative list: name ==> number},
terminals_: {associative list: number ==> name},
productions_: [...],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$),
table: [...],
defaultActions: {...},
parseError: function(str, hash),
parse: function(input),
lexer: {
EOF: 1,
parseError: function(str, hash),
setInput: function(input),
input: function(),
unput: function(str),
more: function(),
less: function(n),
pastInput: function(),
upcomingInput: function(),
showPosition: function(),
test_match: function(regex_match_array, rule_index),
next: function(),
lex: function(),
begin: function(condition),
popState: function(),
_currentRules: function(),
topState: function(),
pushState: function(condition),
options: {
ranges: boolean (optional: true ==> token location info will include a .range[] member)
flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match)
backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code)
},
performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
rules: [...],
conditions: {associative list: name ==> set},
}
}
token location info (@$, _$, etc.): {
first_line: n,
last_line: n,
first_column: n,
last_column: n,
range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based)
}
the parseError function receives a 'hash' object with these members for lexer and parser errors: {
text: (matched text)
token: (the produced terminal token, if any)
line: (yylineno)
}
while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: {
loc: (yylloc)
expected: (string describing the set of expected tokens)
recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error)
}
*/
var parser = function() {
function Parser() {
this.yy = {};
}
var o = function(k, v, o, l) {
for (o = o || {}, l = k.length; l--; o[k[l]] = v) ;
return o;
}, $V0 = [ 5, 8, 9, 13, 15, 24 ], $V1 = [ 1, 13 ], $V2 = [ 1, 17 ], $V3 = [ 24, 29, 30 ], parser = {
trace: function() {},
yy: {},
symbols_: {
error: 2,
start: 3,
document: 4,
EOF: 5,
line: 6,
statement: 7,
NL: 8,
participant: 9,
actor_alias: 10,
signal: 11,
note_statement: 12,
title: 13,
message: 14,
note: 15,
placement: 16,
actor: 17,
over: 18,
actor_pair: 19,
",": 20,
left_of: 21,
right_of: 22,
signaltype: 23,
ACTOR: 24,
linetype: 25,
arrowtype: 26,
LINE: 27,
DOTLINE: 28,
ARROW: 29,
OPENARROW: 30,
MESSAGE: 31,
$accept: 0,
$end: 1
},
terminals_: {
2: "error",
5: "EOF",
8: "NL",
9: "participant",
13: "title",
15: "note",
18: "over",
20: ",",
21: "left_of",
22: "right_of",
24: "ACTOR",
27: "LINE",
28: "DOTLINE",
29: "ARROW",
30: "OPENARROW",
31: "MESSAGE"
},
productions_: [ 0, [ 3, 2 ], [ 4, 0 ], [ 4, 2 ], [ 6, 1 ], [ 6, 1 ], [ 7, 2 ], [ 7, 1 ], [ 7, 1 ], [ 7, 2 ], [ 12, 4 ], [ 12, 4 ], [ 19, 1 ], [ 19, 3 ], [ 16, 1 ], [ 16, 1 ], [ 11, 4 ], [ 17, 1 ], [ 10, 1 ], [ 23, 2 ], [ 23, 1 ], [ 25, 1 ], [ 25, 1 ], [ 26, 1 ], [ 26, 1 ], [ 14, 1 ] ],
performAction: function(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
/* this == yyval */
var $0 = $$.length - 1;
switch (yystate) {
case 1:
return yy.parser.yy;
case 4:
break;
case 6:
$$[$0];
break;
case 7:
case 8:
yy.parser.yy.addSignal($$[$0]);
break;
case 9:
yy.parser.yy.setTitle($$[$0]);
break;
case 10:
this.$ = new Diagram.Note($$[$0 - 1], $$[$0 - 2], $$[$0]);
break;
case 11:
this.$ = new Diagram.Note($$[$0 - 1], Diagram.PLACEMENT.OVER, $$[$0]);
break;
case 12:
case 20:
this.$ = $$[$0];
break;
case 13:
this.$ = [ $$[$0 - 2], $$[$0] ];
break;
case 14:
this.$ = Diagram.PLACEMENT.LEFTOF;
break;
case 15:
this.$ = Diagram.PLACEMENT.RIGHTOF;
break;
case 16:
this.$ = new Diagram.Signal($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0]);
break;
case 17:
this.$ = yy.parser.yy.getActor(Diagram.unescape($$[$0]));
break;
case 18:
this.$ = yy.parser.yy.getActorWithAlias(Diagram.unescape($$[$0]));
break;
case 19:
this.$ = $$[$0 - 1] | $$[$0] << 2;
break;
case 21:
this.$ = Diagram.LINETYPE.SOLID;
break;
case 22:
this.$ = Diagram.LINETYPE.DOTTED;
break;
case 23:
this.$ = Diagram.ARROWTYPE.FILLED;
break;
case 24:
this.$ = Diagram.ARROWTYPE.OPEN;
break;
case 25:
this.$ = Diagram.unescape($$[$0].substring(1));
}
},
table: [ o($V0, [ 2, 2 ], {
3: 1,
4: 2
}), {
1: [ 3 ]
}, {
5: [ 1, 3 ],
6: 4,
7: 5,
8: [ 1, 6 ],
9: [ 1, 7 ],
11: 8,
12: 9,
13: [ 1, 10 ],
15: [ 1, 12 ],
17: 11,
24: $V1
}, {
1: [ 2, 1 ]
}, o($V0, [ 2, 3 ]), o($V0, [ 2, 4 ]), o($V0, [ 2, 5 ]), {
10: 14,
24: [ 1, 15 ]
}, o($V0, [ 2, 7 ]), o($V0, [ 2, 8 ]), {
14: 16,
31: $V2
}, {
23: 18,
25: 19,
27: [ 1, 20 ],
28: [ 1, 21 ]
}, {
16: 22,
18: [ 1, 23 ],
21: [ 1, 24 ],
22: [ 1, 25 ]
}, o([ 20, 27, 28, 31 ], [ 2, 17 ]), o($V0, [ 2, 6 ]), o($V0, [ 2, 18 ]), o($V0, [ 2, 9 ]), o($V0, [ 2, 25 ]), {
17: 26,
24: $V1
}, {
24: [ 2, 20 ],
26: 27,
29: [ 1, 28 ],
30: [ 1, 29 ]
}, o($V3, [ 2, 21 ]), o($V3, [ 2, 22 ]), {
17: 30,
24: $V1
}, {
17: 32,
19: 31,
24: $V1
}, {
24: [ 2, 14 ]
}, {
24: [ 2, 15 ]
}, {
14: 33,
31: $V2
}, {
24: [ 2, 19 ]
}, {
24: [ 2, 23 ]
}, {
24: [ 2, 24 ]
}, {
14: 34,
31: $V2
}, {
14: 35,
31: $V2
}, {
20: [ 1, 36 ],
31: [ 2, 12 ]
}, o($V0, [ 2, 16 ]), o($V0, [ 2, 10 ]), o($V0, [ 2, 11 ]), {
17: 37,
24: $V1
}, {
31: [ 2, 13 ]
} ],
defaultActions: {
3: [ 2, 1 ],
24: [ 2, 14 ],
25: [ 2, 15 ],
27: [ 2, 19 ],
28: [ 2, 23 ],
29: [ 2, 24 ],
37: [ 2, 13 ]
},
parseError: function(str, hash) {
if (!hash.recoverable) throw new Error(str);
this.trace(str);
},
parse: function(input) {
function lex() {
var token;
return token = lexer.lex() || EOF, "number" != typeof token && (token = self.symbols_[token] || token),
token;
}
var self = this, stack = [ 0 ], vstack = [ null ], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1, args = lstack.slice.call(arguments, 1), lexer = Object.create(this.lexer), sharedState = {
yy: {}
};
for (var k in this.yy) Object.prototype.hasOwnProperty.call(this.yy, k) && (sharedState.yy[k] = this.yy[k]);
lexer.setInput(input, sharedState.yy), sharedState.yy.lexer = lexer, sharedState.yy.parser = this,
"undefined" == typeof lexer.yylloc && (lexer.yylloc = {});
var yyloc = lexer.yylloc;
lstack.push(yyloc);
var ranges = lexer.options && lexer.options.ranges;
"function" == typeof sharedState.yy.parseError ? this.parseError = sharedState.yy.parseError : this.parseError = Object.getPrototypeOf(this).parseError;
for (var symbol, preErrorSymbol, state, action, r, p, len, newState, expected, yyval = {}; ;) {
if (state = stack[stack.length - 1], this.defaultActions[state] ? action = this.defaultActions[state] : (null !== symbol && "undefined" != typeof symbol || (symbol = lex()),
action = table[state] && table[state][symbol]), "undefined" == typeof action || !action.length || !action[0]) {
var errStr = "";
expected = [];
for (p in table[state]) this.terminals_[p] && p > TERROR && expected.push("'" + this.terminals_[p] + "'");
errStr = lexer.showPosition ? "Parse error on line " + (yylineno + 1) + ":\n" + lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'" : "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == EOF ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"),
this.parseError(errStr, {
text: lexer.match,
token: this.terminals_[symbol] || symbol,
line: lexer.yylineno,
loc: yyloc,
expected: expected
});
}
if (action[0] instanceof Array && action.length > 1) throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
switch (action[0]) {
case 1:
stack.push(symbol), vstack.push(lexer.yytext), lstack.push(lexer.yylloc), stack.push(action[1]),
symbol = null, preErrorSymbol ? (symbol = preErrorSymbol, preErrorSymbol = null) : (yyleng = lexer.yyleng,
yytext = lexer.yytext, yylineno = lexer.yylineno, yyloc = lexer.yylloc, recovering > 0 && recovering--);
break;
case 2:
if (len = this.productions_[action[1]][1], yyval.$ = vstack[vstack.length - len],
yyval._$ = {
first_line: lstack[lstack.length - (len || 1)].first_line,
last_line: lstack[lstack.length - 1].last_line,
first_column: lstack[lstack.length - (len || 1)].first_column,
last_column: lstack[lstack.length - 1].last_column
}, ranges && (yyval._$.range = [ lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1] ]),
r = this.performAction.apply(yyval, [ yytext, yyleng, yylineno, sharedState.yy, action[1], vstack, lstack ].concat(args)),
"undefined" != typeof r) return r;
len && (stack = stack.slice(0, -1 * len * 2), vstack = vstack.slice(0, -1 * len),
lstack = lstack.slice(0, -1 * len)), stack.push(this.productions_[action[1]][0]),
vstack.push(yyval.$), lstack.push(yyval._$), newState = table[stack[stack.length - 2]][stack[stack.length - 1]],
stack.push(newState);
break;
case 3:
return !0;
}
}
return !0;
}
}, lexer = function() {
var lexer = {
EOF: 1,
parseError: function(str, hash) {
if (!this.yy.parser) throw new Error(str);
this.yy.parser.parseError(str, hash);
},
// resets the lexer, sets new input
setInput: function(input, yy) {
return this.yy = yy || this.yy || {}, this._input = input, this._more = this._backtrack = this.done = !1,
this.yylineno = this.yyleng = 0, this.yytext = this.matched = this.match = "", this.conditionStack = [ "INITIAL" ],
this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
}, this.options.ranges && (this.yylloc.range = [ 0, 0 ]), this.offset = 0, this;
},
// consumes and returns one char from the input
input: function() {
var ch = this._input[0];
this.yytext += ch, this.yyleng++, this.offset++, this.match += ch, this.matched += ch;
var lines = ch.match(/(?:\r\n?|\n).*/g);
return lines ? (this.yylineno++, this.yylloc.last_line++) : this.yylloc.last_column++,
this.options.ranges && this.yylloc.range[1]++, this._input = this._input.slice(1),
ch;
},
// unshifts one char (or a string) into the input
unput: function(ch) {
var len = ch.length, lines = ch.split(/(?:\r\n?|\n)/g);
this._input = ch + this._input, this.yytext = this.yytext.substr(0, this.yytext.length - len),
//this.yyleng -= len;
this.offset -= len;
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
this.match = this.match.substr(0, this.match.length - 1), this.matched = this.matched.substr(0, this.matched.length - 1),
lines.length - 1 && (this.yylineno -= lines.length - 1);
var r = this.yylloc.range;
return this.yylloc = {
first_line: this.yylloc.first_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.first_column,
last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
}, this.options.ranges && (this.yylloc.range = [ r[0], r[0] + this.yyleng - len ]),
this.yyleng = this.yytext.length, this;
},
// When called from action, caches matched text and appends it on next action
more: function() {
return this._more = !0, this;
},
// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
reject: function() {
return this.options.backtrack_lexer ? (this._backtrack = !0, this) : this.parseError("Lexical error on line " + (this.yylineno + 1) + ". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n" + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
},
// retain first n characters of the match
less: function(n) {
this.unput(this.match.slice(n));
},
// displays already matched input, i.e. for error messages
pastInput: function() {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, "");
},
// displays upcoming input, i.e. for error messages
upcomingInput: function() {
var next = this.match;
return next.length < 20 && (next += this._input.substr(0, 20 - next.length)), (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(/\n/g, "");
},
// displays the character position where the lexing error occurred, i.e. for error messages
showPosition: function() {
var pre = this.pastInput(), c = new Array(pre.length + 1).join("-");
return pre + this.upcomingInput() + "\n" + c + "^";
},
// test the lexed token: return FALSE when not a match, otherwise return token
test_match: function(match, indexed_rule) {
var token, lines, backup;
if (this.options.backtrack_lexer && (// save context
backup = {
yylineno: this.yylineno,
yylloc: {
first_line: this.yylloc.first_line,
last_line: this.last_line,
first_column: this.yylloc.first_column,
last_column: this.yylloc.last_column
},
yytext: this.yytext,
match: this.match,
matches: this.matches,
matched: this.matched,
yyleng: this.yyleng,
offset: this.offset,
_more: this._more,
_input: this._input,
yy: this.yy,
conditionStack: this.conditionStack.slice(0),
done: this.done
}, this.options.ranges && (backup.yylloc.range = this.yylloc.range.slice(0))), lines = match[0].match(/(?:\r\n?|\n).*/g),
lines && (this.yylineno += lines.length), this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length
}, this.yytext += match[0], this.match += match[0], this.matches = match, this.yyleng = this.yytext.length,
this.options.ranges && (this.yylloc.range = [ this.offset, this.offset += this.yyleng ]),
this._more = !1, this._backtrack = !1, this._input = this._input.slice(match[0].length),
this.matched += match[0], token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]),
this.done && this._input && (this.done = !1), token) return token;
if (this._backtrack) {
// recover context
for (var k in backup) this[k] = backup[k];
return !1;
}
return !1;
},
// return next match in input
next: function() {
if (this.done) return this.EOF;
this._input || (this.done = !0);
var token, match, tempMatch, index;
this._more || (this.yytext = "", this.match = "");
for (var rules = this._currentRules(), i = 0; i < rules.length; i++) if (tempMatch = this._input.match(this.rules[rules[i]]),
tempMatch && (!match || tempMatch[0].length > match[0].length)) {
if (match = tempMatch, index = i, this.options.backtrack_lexer) {
if (token = this.test_match(tempMatch, rules[i]), token !== !1) return token;
if (this._backtrack) {
match = !1;
continue;
}
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return !1;
}
if (!this.options.flex) break;
}
return match ? (token = this.test_match(match, rules[index]), token !== !1 && token) : "" === this._input ? this.EOF : this.parseError("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
},
// return next match that has a token
lex: function() {
var r = this.next();
return r ? r : this.lex();
},
// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
begin: function(condition) {
this.conditionStack.push(condition);
},
// pop the previously active lexer condition state off the condition stack
popState: function() {
var n = this.conditionStack.length - 1;
return n > 0 ? this.conditionStack.pop() : this.conditionStack[0];
},
// produce the lexer rule set which is active for the currently active lexer condition state
_currentRules: function() {
return this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1] ? this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules : this.conditions.INITIAL.rules;
},
// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
topState: function(n) {
return n = this.conditionStack.length - 1 - Math.abs(n || 0), n >= 0 ? this.conditionStack[n] : "INITIAL";
},
// alias for begin(condition)
pushState: function(condition) {
this.begin(condition);
},
// return the number of states currently on the stack
stateStackSize: function() {
return this.conditionStack.length;
},
options: {
"case-insensitive": !0
},
performAction: function(yy, yy_, $avoiding_name_collisions, YY_START) {
switch ($avoiding_name_collisions) {
case 0:
return 8;
case 1:
/* skip whitespace */
break;
case 2:
/* skip comments */
break;
case 3:
return 9;
case 4:
return 21;
case 5:
return 22;
case 6:
return 18;
case 7:
return 15;
case 8:
return 13;
case 9:
return 20;
case 10:
return 24;
case 11:
return 24;
case 12:
return 28;
case 13:
return 27;
case 14:
return 30;
case 15:
return 29;
case 16:
return 31;
case 17:
return 5;
case 18:
return "INVALID";
}
},
rules: [ /^(?:[\r\n]+)/i, /^(?:\s+)/i, /^(?:#[^\r\n]*)/i, /^(?:participant\b)/i, /^(?:left of\b)/i, /^(?:right of\b)/i, /^(?:over\b)/i, /^(?:note\b)/i, /^(?:title\b)/i, /^(?:,)/i, /^(?:[^\->:,\r\n"]+)/i, /^(?:"[^"]+")/i, /^(?:--)/i, /^(?:-)/i, /^(?:>>)/i, /^(?:>)/i, /^(?:[^\r\n]+)/i, /^(?:$)/i, /^(?:.)/i ],
conditions: {
INITIAL: {
rules: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ],
inclusive: !0
}
}
};
return lexer;
}();
return parser.lexer = lexer, Parser.prototype = parser, parser.Parser = Parser,
new Parser();
}();
"undefined" != typeof require && "undefined" != typeof exports && (exports.parser = parser,
exports.Parser = parser.Parser, exports.parse = function() {
return parser.parse.apply(parser, arguments);
}, exports.main = function(args) {
args[1] || (console.log("Usage: " + args[0] + " FILE"), process.exit(1));
var source = require("fs").readFileSync(require("path").normalize(args[1]), "utf8");
return exports.parser.parse(source);
}, "undefined" != typeof module && require.main === module && exports.main(process.argv.slice(1)));
/**
* jison doesn't have a good exception, so we make one.
* This is brittle as it depends on jison internals
*/
function ParseError(message, hash) {
_.extend(this, hash);
this.name = 'ParseError';
this.message = (message || '');
}
ParseError.prototype = new Error();
Diagram.ParseError = ParseError;
Diagram.parse = function(input) {
// TODO jison v0.4.17 changed their API slightly, so parser is no longer defined:
// Create the object to track state and deal with errors
parser.yy = new Diagram();
parser.yy.parseError = function(message, hash) {
throw new ParseError(message, hash);
};
// Parse
var diagram = parser.parse(input);
// Then clean up the parseError key that a user won't care about
delete diagram.parseError;
return diagram;
};
/** js sequence diagrams
* https://bramp.github.io/js-sequence-diagrams/
* (c) 2012-2017 Andrew Brampton (bramp.net)
* Simplified BSD license.
*/
/*global Diagram, _ */
// Following the CSS convention
// Margin is the gap outside the box
// Padding is the gap inside the box
// Each object has x/y/width/height properties
// The x/y should be top left corner
// width/height is with both margin and padding
// TODO
// Image width is wrong, when there is a note in the right hand col
// Title box could look better
// Note box could look better
var DIAGRAM_MARGIN = 10;
var ACTOR_MARGIN = 10; // Margin around a actor
var ACTOR_PADDING = 10; // Padding inside a actor
var SIGNAL_MARGIN = 5; // Margin around a signal
var SIGNAL_PADDING = 5; // Padding inside a signal
var NOTE_MARGIN = 10; // Margin around a note
var NOTE_PADDING = 5; // Padding inside a note
var NOTE_OVERLAP = 15; // Overlap when using a "note over A,B"
var TITLE_MARGIN = 0;
var TITLE_PADDING = 5;
var SELF_SIGNAL_WIDTH = 20; // How far out a self signal goes
var PLACEMENT = Diagram.PLACEMENT;
var LINETYPE = Diagram.LINETYPE;
var ARROWTYPE = Diagram.ARROWTYPE;
var ALIGN_LEFT = 0;
var ALIGN_CENTER = 1;
function AssertException(message) { this.message = message; }
AssertException.prototype.toString = function() {
return 'AssertException: ' + this.message;
};
function assert(exp, message) {
if (!exp) {
throw new AssertException(message);
}
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
Diagram.themes = {};
function registerTheme(name, theme) {
Diagram.themes[name] = theme;
}
/******************
* Drawing extras
******************/
function getCenterX(box) {
return box.x + box.width / 2;
}
function getCenterY(box) {
return box.y + box.height / 2;
}
/******************
* SVG Path extras
******************/
function clamp(x, min, max) {
if (x < min) {
return min;
}
if (x > max) {
return max;
}
return x;
}
function wobble(x1, y1, x2, y2) {
assert(_.all([x1,x2,y1,y2], _.isFinite), 'x1,x2,y1,y2 must be numeric');
// Wobble no more than 1/25 of the line length
var factor = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) / 25;
// Distance along line where the control points are
// Clamp between 20% and 80% so any arrow heads aren't angled too much
var r1 = clamp(Math.random(), 0.2, 0.8);
var r2 = clamp(Math.random(), 0.2, 0.8);
var xfactor = Math.random() > 0.5 ? factor : -factor;
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | true |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/dragDrop.js | src/muya/lib/eventHandler/dragDrop.js | class DragDrop {
constructor (muya) {
this.muya = muya
this.dragOverBinding()
this.dropBinding()
this.dragendBinding()
this.dragStartBinding()
}
dragStartBinding () {
const { container, eventCenter } = this.muya
const dragStartHandler = event => {
if (event.target.tagName === 'IMG') {
return event.preventDefault()
}
}
eventCenter.attachDOMEvent(container, 'dragstart', dragStartHandler)
}
dragOverBinding () {
const { container, eventCenter, contentState } = this.muya
const dragoverHandler = event => {
contentState.dragoverHandler(event)
}
eventCenter.attachDOMEvent(container, 'dragover', dragoverHandler)
}
dropBinding () {
const { container, eventCenter, contentState } = this.muya
const dropHandler = event => {
contentState.dropHandler(event)
}
eventCenter.attachDOMEvent(container, 'drop', dropHandler)
}
dragendBinding () {
const { eventCenter, contentState } = this.muya
const dragleaveHandler = event => {
contentState.dragleaveHandler(event)
}
eventCenter.attachDOMEvent(window, 'dragleave', dragleaveHandler)
}
}
export default DragDrop
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/clipboard.js | src/muya/lib/eventHandler/clipboard.js | class Clipboard {
constructor (muya) {
this.muya = muya
this._copyType = 'normal' // `normal` or `copyAsMarkdown` or `copyAsHtml`
this._pasteType = 'normal' // `normal` or `pasteAsPlainText`
this._copyInfo = null
this.listen()
}
listen () {
const { container, eventCenter, contentState } = this.muya
const docPasteHandler = event => {
contentState.docPasteHandler(event)
}
const docCopyCutHandler = event => {
contentState.docCopyHandler(event)
if (event.type === 'cut') {
// when user use `cut` function, the dom has been deleted by default.
// But should update content state manually.
contentState.docCutHandler(event)
}
}
const copyCutHandler = event => {
contentState.copyHandler(event, this._copyType, this._copyInfo)
if (event.type === 'cut') {
// when user use `cut` function, the dom has been deleted by default.
// But should update content state manually.
contentState.cutHandler()
}
this._copyType = 'normal'
}
const pasteHandler = event => {
contentState.pasteHandler(event, this._pasteType)
this._pasteType = 'normal'
this.muya.dispatchChange()
}
eventCenter.attachDOMEvent(document, 'paste', docPasteHandler)
eventCenter.attachDOMEvent(container, 'paste', pasteHandler)
eventCenter.attachDOMEvent(container, 'cut', copyCutHandler)
eventCenter.attachDOMEvent(container, 'copy', copyCutHandler)
eventCenter.attachDOMEvent(document.body, 'cut', docCopyCutHandler)
eventCenter.attachDOMEvent(document.body, 'copy', docCopyCutHandler)
}
// TODO: `document.execCommand` is deprecated!
copyAsMarkdown () {
this._copyType = 'copyAsMarkdown'
document.execCommand('copy')
}
copyAsHtml () {
this._copyType = 'copyAsHtml'
document.execCommand('copy')
}
pasteAsPlainText () {
this._pasteType = 'pasteAsPlainText'
document.execCommand('paste')
}
/**
* Copy the anchor block(table, paragraph, math block etc) with the info
* @param {string|object} type copyBlock or copyCodeContent
* @param {string|object} info is the block key if it's string, or block if it's object
*/
copy (type, info) {
this._copyType = type
this._copyInfo = info
document.execCommand('copy')
}
}
export default Clipboard
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/resize.js | src/muya/lib/eventHandler/resize.js | // import resizeCodeBlockLineNumber from '../utils/resizeCodeLineNumber'
// import { throttle } from '../utils'
class Resize {
constructor (muya) {
this.muya = muya
this.listen()
}
listen () {
// FIXME: Disabled due to #1648.
// const { codeBlockLineNumbers } = this.muya.options
// if (!codeBlockLineNumbers) {
// return
// }
//
// window.addEventListener('resize', throttle(() => {
// const codeBlocks = document.querySelectorAll('pre.line-numbers')
// if (codeBlocks.length) {
// for (const ele of codeBlocks) {
// resizeCodeBlockLineNumber(ele)
// }
// }
// }, 300))
}
}
export default Resize
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/clickEvent.js | src/muya/lib/eventHandler/clickEvent.js | import { operateClassName } from '../utils/domManipulate'
import { getImageInfo } from '../utils/getImageInfo'
import { CLASS_OR_ID } from '../config'
import selection from '../selection'
class ClickEvent {
constructor (muya) {
this.muya = muya
this.clickBinding()
this.contextClickBingding()
}
contextClickBingding () {
const { container, eventCenter, contentState } = this.muya
const handler = event => {
// Allow native context menu in MarkText.
if (!global || !global.marktext) { // __MARKTEXT_PATCH__
event.preventDefault()
event.stopPropagation()
}
// Hide all float box and image transformer
const { keyboard } = this.muya
if (keyboard) {
keyboard.hideAllFloatTools()
}
const { start, end } = selection.getCursorRange()
// Cursor out of editor
if (!start || !end) {
return
}
const startBlock = contentState.getBlock(start.key)
const nextTextBlock = contentState.findNextBlockInLocation(startBlock)
if (
nextTextBlock && nextTextBlock.key === end.key &&
end.offset === 0 &&
start.offset === startBlock.text.length
) {
// Set cursor at the end of start block and reset cursor
// Because if you right click at the end of one text block, the cursor.start will at the end of
// start block and the cursor.end will at the next text block beginning. So we reset the cursor
// at the end of start block.
contentState.cursor = {
start,
end: start
}
selection.setCursorRange(contentState.cursor)
} else {
// Commit native cursor position because right-clicking doesn't update the cursor postion.
contentState.cursor = {
start,
end
}
}
const sectionChanges = contentState.selectionChange(contentState.cursor)
eventCenter.dispatch('contextmenu', event, sectionChanges)
}
eventCenter.attachDOMEvent(container, 'contextmenu', handler)
}
clickBinding () {
const { container, eventCenter, contentState } = this.muya
const handler = event => {
const { target } = event
// handler table click
const toolItem = getToolItem(target)
contentState.selectedImage = null
contentState.selectedTableCells = null
if (toolItem) {
event.preventDefault()
event.stopPropagation()
const type = toolItem.getAttribute('data-label')
const grandPa = toolItem.parentNode.parentNode
if (grandPa.classList.contains('ag-tool-table')) {
contentState.tableToolBarClick(type)
}
}
// Handle table drag bar click
if (target.classList.contains('ag-drag-handler')) {
event.preventDefault()
event.stopPropagation()
const rect = target.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
return rect
},
width: rect.offsetWidth,
height: rect.offsetHeight
}
eventCenter.dispatch('muya-table-bar', {
reference,
tableInfo: {
barType: target.classList.contains('left') ? 'left' : 'bottom'
}
})
}
// Handle image and inline math preview click
const markedImageText = target.previousElementSibling
const mathRender = target.closest(`.${CLASS_OR_ID.AG_MATH_RENDER}`)
const rubyRender = target.closest(`.${CLASS_OR_ID.AG_RUBY_RENDER}`)
const imageWrapper = target.closest(`.${CLASS_OR_ID.AG_INLINE_IMAGE}`)
const codeCopy = target.closest('.ag-code-copy')
const footnoteBackLink = target.closest('.ag-footnote-backlink')
const imageDelete = target.closest('.ag-image-icon-delete') || target.closest('.ag-image-icon-close')
const mathText = mathRender && mathRender.previousElementSibling
const rubyText = rubyRender && rubyRender.previousElementSibling
if (markedImageText && markedImageText.classList.contains(CLASS_OR_ID.AG_IMAGE_MARKED_TEXT)) {
eventCenter.dispatch('format-click', {
event,
formatType: 'image',
data: event.target.getAttribute('src')
})
selectionText(markedImageText)
} else if (mathText) {
selectionText(mathText)
} else if (rubyText) {
selectionText(rubyText)
}
if (codeCopy) {
event.stopPropagation()
event.preventDefault()
return this.muya.contentState.copyCodeBlock(event)
}
// Handle delete inline iamge by click delete icon.
if (imageDelete && imageWrapper) {
const imageInfo = getImageInfo(imageWrapper)
event.preventDefault()
event.stopPropagation()
// hide image selector if needed.
eventCenter.dispatch('muya-image-selector', { reference: null })
return contentState.deleteImage(imageInfo)
}
if (footnoteBackLink) {
event.preventDefault()
event.stopPropagation()
const figure = event.target.closest('figure')
const identifier = figure.querySelector('span.ag-footnote-input').textContent
if (identifier) {
const footnoteIdentifier = document.querySelector(`#noteref-${identifier}`)
if (footnoteIdentifier) {
footnoteIdentifier.scrollIntoView({ behavior: 'smooth' })
}
}
return
}
// Handle image click, to select the current image
if (target.tagName === 'IMG' && imageWrapper) {
// Handle select image
const imageInfo = getImageInfo(imageWrapper)
event.preventDefault()
eventCenter.dispatch('select-image', imageInfo)
// Handle show image toolbar
const rect = imageWrapper.querySelector('.ag-image-container').getBoundingClientRect()
const reference = {
getBoundingClientRect () {
return rect
},
width: imageWrapper.offsetWidth,
height: imageWrapper.offsetHeight
}
eventCenter.dispatch('muya-image-toolbar', {
reference,
imageInfo
})
contentState.selectImage(imageInfo)
// Handle show image transformer
const imageSelector = imageInfo.imageId.indexOf('_') > -1
? `#${imageInfo.imageId}`
: `#${imageInfo.key}_${imageInfo.imageId}_${imageInfo.token.range.start}`
const imageContainer = document.querySelector(`${imageSelector} .ag-image-container`)
eventCenter.dispatch('muya-transformer', {
reference: imageContainer,
imageInfo
})
return
}
// Handle click imagewrapper when it's empty or image load failed.
if (
(imageWrapper &&
(
imageWrapper.classList.contains('ag-empty-image') ||
imageWrapper.classList.contains('ag-image-fail')
))
) {
const rect = imageWrapper.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
return rect
}
}
const imageInfo = getImageInfo(imageWrapper)
eventCenter.dispatch('muya-image-selector', {
reference,
imageInfo,
cb: () => {}
})
event.preventDefault()
return event.stopPropagation()
}
if (target.closest('div.ag-container-preview') || target.closest('div.ag-html-preview')) {
event.stopPropagation()
if (target.closest('div.ag-container-preview')) {
event.preventDefault()
const figureEle = target.closest('figure')
contentState.handleContainerBlockClick(figureEle)
}
return
}
// handler container preview click
const editIcon = target.closest('.ag-container-icon')
if (editIcon) {
event.preventDefault()
event.stopPropagation()
if (editIcon.parentNode.classList.contains('ag-container-block')) {
contentState.handleContainerBlockClick(editIcon.parentNode)
}
}
// handler to-do checkbox click
if (target.tagName === 'INPUT' && target.classList.contains(CLASS_OR_ID.AG_TASK_LIST_ITEM_CHECKBOX)) {
contentState.listItemCheckBoxClick(target)
}
contentState.clickHandler(event)
}
eventCenter.attachDOMEvent(container, 'click', handler)
}
}
function getToolItem (target) {
return target.closest('[data-label]')
}
function selectionText (node) {
const textLen = node.textContent.length
operateClassName(node, 'remove', CLASS_OR_ID.AG_HIDE)
operateClassName(node, 'add', CLASS_OR_ID.AG_GRAY)
selection.importSelection({
start: textLen,
end: textLen
}, node)
}
export default ClickEvent
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/event.js | src/muya/lib/eventHandler/event.js | import { getUniqueId } from '../utils'
class EventCenter {
constructor () {
this.events = []
this.listeners = {}
}
/**
* [attachDOMEvent] bind event listener to target, and return a unique ID,
* this ID
*/
attachDOMEvent (target, event, listener, capture) {
if (this.checkHasBind(target, event, listener, capture)) return false
const eventId = getUniqueId()
target.addEventListener(event, listener, capture)
this.events.push({
eventId,
target,
event,
listener,
capture
})
return eventId
}
/**
* [detachDOMEvent removeEventListener]
* @param {[type]} eventId [unique eventId]
*/
detachDOMEvent (eventId) {
if (!eventId) return false
const index = this.events.findIndex(e => e.eventId === eventId)
if (index > -1) {
const { target, event, listener, capture } = this.events[index]
target.removeEventListener(event, listener, capture)
this.events.splice(index, 1)
}
}
/**
* [detachAllDomEvents remove all the DOM events handler]
*/
detachAllDomEvents () {
this.events.forEach(event => this.detachDOMEvent(event.eventId))
}
/**
* inner method for subscribe and subscribeOnce
*/
_subscribe (event, listener, once = false) {
const listeners = this.listeners[event]
const handler = { listener, once }
if (listeners && Array.isArray(listeners)) {
listeners.push(handler)
} else {
this.listeners[event] = [handler]
}
}
/**
* [subscribe] subscribe custom event
*/
subscribe (event, listener) {
this._subscribe(event, listener)
}
/**
* [unsubscribe] unsubscribe custom event
*/
unsubscribe (event, listener) {
const listeners = this.listeners[event]
if (Array.isArray(listeners) && listeners.find(l => l.listener === listener)) {
const index = listeners.findIndex(l => l.listener === listener)
listeners.splice(index, 1)
}
}
/**
* [subscribeOnce] usbscribe event and listen once
*/
subscribeOnce (event, listener) {
this._subscribe(event, listener, true)
}
/**
* dispatch custom event
*/
dispatch (event, ...data) {
const eventListener = this.listeners[event]
if (eventListener && Array.isArray(eventListener)) {
eventListener.forEach(({ listener, once }) => {
listener(...data)
if (once) {
this.unsubscribe(event, listener)
}
})
}
}
// Determine whether the event has been bind
checkHasBind (cTarget, cEvent, cListener, cCapture) {
for (const { target, event, listener, capture } of this.events) {
if (target === cTarget && event === cEvent && listener === cListener && capture === cCapture) {
return true
}
}
return false
}
}
export default EventCenter
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/mouseEvent.js | src/muya/lib/eventHandler/mouseEvent.js | import { getLinkInfo } from '../utils/getLinkInfo'
import { collectFootnotes } from '../utils'
class MouseEvent {
constructor (muya) {
this.muya = muya
this.mouseBinding()
this.mouseDown()
}
mouseBinding () {
const { container, eventCenter } = this.muya
const handler = event => {
const target = event.target
const parent = target.parentNode
const preSibling = target.previousElementSibling
const parentPreSibling = parent ? parent.previousElementSibling : null
const { hideLinkPopup, footnote } = this.muya.options
const rect = parent.getBoundingClientRect()
const reference = {
getBoundingClientRect () {
return rect
}
}
if (
!hideLinkPopup &&
parent &&
parent.tagName === 'A' &&
parent.classList.contains('ag-inline-rule') &&
parentPreSibling &&
parentPreSibling.classList.contains('ag-hide')
) {
eventCenter.dispatch('muya-link-tools', {
reference,
linkInfo: getLinkInfo(parent)
})
}
if (
footnote &&
parent &&
parent.tagName === 'SUP' &&
parent.classList.contains('ag-inline-footnote-identifier') &&
preSibling &&
preSibling.classList.contains('ag-hide')
) {
const identifier = target.textContent
eventCenter.dispatch('muya-footnote-tool', {
reference,
identifier,
footnotes: collectFootnotes(this.muya.contentState.blocks)
})
}
}
const leaveHandler = event => {
const target = event.target
const parent = target.parentNode
const preSibling = target.previousElementSibling
const { footnote } = this.muya.options
if (parent && parent.tagName === 'A' && parent.classList.contains('ag-inline-rule')) {
eventCenter.dispatch('muya-link-tools', {
reference: null
})
}
if (
footnote &&
parent &&
parent.tagName === 'SUP' &&
parent.classList.contains('ag-inline-footnote-identifier') &&
preSibling &&
preSibling.classList.contains('ag-hide')
) {
eventCenter.dispatch('muya-footnote-tool', {
reference: null
})
}
}
eventCenter.attachDOMEvent(container, 'mouseover', handler)
eventCenter.attachDOMEvent(container, 'mouseout', leaveHandler)
}
mouseDown () {
const { container, eventCenter, contentState } = this.muya
const handler = event => {
const target = event.target
if (target.classList && target.classList.contains('ag-drag-handler')) {
contentState.handleMouseDown(event)
} else if (target && target.closest('tr')) {
contentState.handleCellMouseDown(event)
}
}
eventCenter.attachDOMEvent(container, 'mousedown', handler)
}
}
export default MouseEvent
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/eventHandler/keyboard.js | src/muya/lib/eventHandler/keyboard.js | import { EVENT_KEYS } from '../config'
import selection from '../selection'
import { findNearestParagraph } from '../selection/dom'
import { getParagraphReference, getImageInfo } from '../utils'
import { checkEditEmoji } from '../ui/emojis'
class Keyboard {
constructor (muya) {
this.muya = muya
this.isComposed = false
this.shownFloat = new Set()
this.recordIsComposed()
this.dispatchEditorState()
this.keydownBinding()
this.keyupBinding()
this.inputBinding()
this.listen()
}
listen () {
// cache shown float box
this.muya.eventCenter.subscribe('muya-float', (tool, status) => {
status ? this.shownFloat.add(tool) : this.shownFloat.delete(tool)
if (tool.name === 'ag-front-menu' && !status) {
const seletedParagraph = this.muya.container.querySelector('.ag-selected')
if (seletedParagraph) {
this.muya.contentState.selectedBlock = null
// prevent rerender, so change the class manually.
seletedParagraph.classList.toggle('ag-selected')
}
}
})
}
hideAllFloatTools () {
for (const tool of this.shownFloat) {
tool.hide()
}
}
recordIsComposed () {
const { container, eventCenter, contentState } = this.muya
const handler = event => {
if (event.type === 'compositionstart') {
this.isComposed = true
} else if (event.type === 'compositionend') {
this.isComposed = false
// Because the compose event will not cause `input` event, So need call `inputHandler` by ourself
contentState.inputHandler(event)
eventCenter.dispatch('stateChange')
}
}
eventCenter.attachDOMEvent(container, 'compositionend', handler)
// eventCenter.attachDOMEvent(container, 'compositionupdate', handler)
eventCenter.attachDOMEvent(container, 'compositionstart', handler)
}
dispatchEditorState () {
const { container, eventCenter } = this.muya
let timer = null
const changeHandler = event => {
if (
event.type === 'keyup' &&
(event.key === EVENT_KEYS.ArrowUp || event.key === EVENT_KEYS.ArrowDown) &&
this.shownFloat.size > 0
) {
return
}
// Cursor outside editor area or over not editable elements.
if (event.target.closest('[contenteditable=false]')) {
return
}
// We need check cursor is null, because we may copy the html preview content,
// and no need to dispatch change.
const { start, end } = selection.getCursorRange()
if (!start || !end) {
return
}
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
this.muya.dispatchSelectionChange()
this.muya.dispatchSelectionFormats()
if (!this.isComposed && event.type === 'click') {
this.muya.dispatchChange()
}
})
}
eventCenter.attachDOMEvent(container, 'click', changeHandler)
eventCenter.attachDOMEvent(container, 'keyup', changeHandler)
}
keydownBinding () {
const { container, eventCenter, contentState } = this.muya
const docHandler = event => {
switch (event.code) {
case EVENT_KEYS.Enter:
return contentState.docEnterHandler(event)
case EVENT_KEYS.Space: {
if (contentState.selectedImage) {
const { token } = contentState.selectedImage
const { src } = getImageInfo(token.src || token.attrs.src)
if (src) {
eventCenter.dispatch('preview-image', {
data: src
})
}
}
break
}
case EVENT_KEYS.Backspace: {
return contentState.docBackspaceHandler(event)
}
case EVENT_KEYS.Delete: {
return contentState.docDeleteHandler(event)
}
case EVENT_KEYS.ArrowUp: // fallthrough
case EVENT_KEYS.ArrowDown: // fallthrough
case EVENT_KEYS.ArrowLeft: // fallthrough
case EVENT_KEYS.ArrowRight: // fallthrough
return contentState.docArrowHandler(event)
}
}
const handler = event => {
if (event.metaKey || event.ctrlKey) {
container.classList.add('ag-meta-or-ctrl')
}
if (
this.shownFloat.size > 0 &&
(
event.key === EVENT_KEYS.Enter ||
event.key === EVENT_KEYS.Escape ||
event.key === EVENT_KEYS.Tab ||
event.key === EVENT_KEYS.ArrowUp ||
event.key === EVENT_KEYS.ArrowDown
)
) {
let needPreventDefault = false
for (const tool of this.shownFloat) {
if (
tool.name === 'ag-format-picker' ||
tool.name === 'ag-table-picker' ||
tool.name === 'ag-quick-insert' ||
tool.name === 'ag-emoji-picker' ||
tool.name === 'ag-front-menu' ||
tool.name === 'ag-list-picker' ||
tool.name === 'ag-image-selector'
) {
needPreventDefault = true
break
}
}
if (needPreventDefault) {
event.preventDefault()
}
// event.stopPropagation()
return
}
switch (event.key) {
case EVENT_KEYS.Backspace:
contentState.backspaceHandler(event)
break
case EVENT_KEYS.Delete:
contentState.deleteHandler(event)
break
case EVENT_KEYS.Enter:
if (!this.isComposed) {
contentState.enterHandler(event)
this.muya.dispatchChange()
}
break
case EVENT_KEYS.ArrowUp: // fallthrough
case EVENT_KEYS.ArrowDown: // fallthrough
case EVENT_KEYS.ArrowLeft: // fallthrough
case EVENT_KEYS.ArrowRight: // fallthrough
if (!this.isComposed) {
contentState.arrowHandler(event)
}
break
case EVENT_KEYS.Tab:
contentState.tabHandler(event)
break
default:
break
}
}
eventCenter.attachDOMEvent(container, 'keydown', handler)
eventCenter.attachDOMEvent(document, 'keydown', docHandler)
}
inputBinding () {
const { container, eventCenter, contentState } = this.muya
const inputHandler = event => {
if (!this.isComposed) {
contentState.inputHandler(event)
this.muya.dispatchChange()
}
const { lang, paragraph } = contentState.checkEditLanguage()
if (lang) {
eventCenter.dispatch('muya-code-picker', {
reference: getParagraphReference(paragraph, paragraph.id),
lang,
cb: item => {
contentState.selectLanguage(paragraph, item.name)
}
})
} else {
// hide code picker float box
eventCenter.dispatch('muya-code-picker', { reference: null })
}
}
eventCenter.attachDOMEvent(container, 'input', inputHandler)
}
keyupBinding () {
const { container, eventCenter, contentState } = this.muya
const handler = event => {
container.classList.remove('ag-meta-or-ctrl')
// check if edit emoji
const node = selection.getSelectionStart()
const paragraph = findNearestParagraph(node)
const emojiNode = checkEditEmoji(node)
contentState.selectedImage = null
if (
paragraph &&
emojiNode &&
event.key !== EVENT_KEYS.Enter &&
event.key !== EVENT_KEYS.ArrowDown &&
event.key !== EVENT_KEYS.ArrowUp &&
event.key !== EVENT_KEYS.Tab &&
event.key !== EVENT_KEYS.Escape
) {
const reference = getParagraphReference(emojiNode, paragraph.id)
eventCenter.dispatch('muya-emoji-picker', {
reference,
emojiNode
})
}
if (!emojiNode) {
eventCenter.dispatch('muya-emoji-picker', {
emojiNode
})
}
const { anchor, focus, start, end } = selection.getCursorRange()
if (!anchor || !focus) {
return
}
if (
!this.isComposed
) {
const { anchor: oldAnchor, focus: oldFocus } = contentState.cursor
if (
anchor.key !== oldAnchor.key ||
anchor.offset !== oldAnchor.offset ||
focus.key !== oldFocus.key ||
focus.offset !== oldFocus.offset
) {
const needRender = contentState.checkNeedRender(contentState.cursor) || contentState.checkNeedRender({ start, end })
contentState.cursor = { anchor, focus }
if (needRender) {
return contentState.partialRender()
}
}
}
const block = contentState.getBlock(anchor.key)
if (
anchor.key === focus.key &&
anchor.offset !== focus.offset &&
block.functionType !== 'codeContent' &&
block.functionType !== 'languageInput'
) {
const reference = contentState.getPositionReference()
const { formats } = contentState.selectionFormats()
eventCenter.dispatch('muya-format-picker', { reference, formats })
} else {
eventCenter.dispatch('muya-format-picker', { reference: null })
}
}
eventCenter.attachDOMEvent(container, 'keyup', handler) // temp use input event
}
}
export default Keyboard
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/selection/index.js | src/muya/lib/selection/index.js | /**
* This file is copy from [medium-editor](https://github.com/yabwe/medium-editor)
* and customize for specialized use.
*/
import Cursor from './cursor'
import { CLASS_OR_ID } from '../config'
import {
isBlockContainer,
traverseUp,
getFirstSelectableLeafNode,
getClosestBlockContainer,
getCursorPositionWithinMarkedText,
findNearestParagraph,
getTextContent,
getOffsetOfParagraph
} from './dom'
const filterOnlyParentElements = node => {
return isBlockContainer(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP
}
class Selection {
constructor (doc) {
this.doc = doc // document
}
findMatchingSelectionParent (testElementFunction, contentWindow) {
const selection = contentWindow.getSelection()
let range
let current
if (selection.rangeCount === 0) {
return false
}
range = selection.getRangeAt(0)
current = range.commonAncestorContainer
return traverseUp(current, testElementFunction)
}
// https://stackoverflow.com/questions/17678843/cant-restore-selection-after-html-modify-even-if-its-the-same-html
// Tim Down
//
// {object} selectionState - the selection to import
// {DOMElement} root - the root element the selection is being restored inside of
// {boolean} [favorLaterSelectionAnchor] - defaults to false. If true, import the cursor immediately
// subsequent to an anchor tag if it would otherwise be placed right at the trailing edge inside the
// anchor. This cursor positioning, even though visually equivalent to the user, can affect behavior
// in MS IE.
importSelection (selectionState, root, favorLaterSelectionAnchor) {
if (!selectionState || !root) {
throw new Error('your must provide a [selectionState] and a [root] element')
}
let range = this.doc.createRange()
range.setStart(root, 0)
range.collapse(true)
let node = root
const nodeStack = []
let charIndex = 0
let foundStart = false
let foundEnd = false
let trailingImageCount = 0
let stop = false
let nextCharIndex
let allowRangeToStartAtEndOfNode = false
let lastTextNode = null
// When importing selection, the start of the selection may lie at the end of an element
// or at the beginning of an element. Since visually there is no difference between these 2
// we will try to move the selection to the beginning of an element since this is generally
// what users will expect and it's a more predictable behavior.
//
// However, there are some specific cases when we don't want to do this:
// 1) We're attempting to move the cursor outside of the end of an anchor [favorLaterSelectionAnchor = true]
// 2) The selection starts with an image, which is special since an image doesn't have any 'content'
// as far as selection and ranges are concerned
// 3) The selection starts after a specified number of empty block elements (selectionState.emptyBlocksIndex)
//
// For these cases, we want the selection to start at a very specific location, so we should NOT
// automatically move the cursor to the beginning of the first actual chunk of text
if (favorLaterSelectionAnchor || selectionState.startsWithImage || typeof selectionState.emptyBlocksIndex !== 'undefined') {
allowRangeToStartAtEndOfNode = true
}
while (!stop && node) {
// Only iterate over elements and text nodes
if (node.nodeType > 3) {
node = nodeStack.pop()
continue
}
// If we hit a text node, we need to add the amount of characters to the overall count
if (node.nodeType === 3 && !foundEnd) {
nextCharIndex = charIndex + node.length
// Check if we're at or beyond the start of the selection we're importing
if (!foundStart && selectionState.start >= charIndex && selectionState.start <= nextCharIndex) {
// NOTE: We only want to allow a selection to start at the END of an element if
// allowRangeToStartAtEndOfNode is true
if (allowRangeToStartAtEndOfNode || selectionState.start < nextCharIndex) {
range.setStart(node, selectionState.start - charIndex)
foundStart = true
} else {
// We're at the end of a text node where the selection could start but we shouldn't
// make the selection start here because allowRangeToStartAtEndOfNode is false.
// However, we should keep a reference to this node in case there aren't any more
// text nodes after this, so that we have somewhere to import the selection to
lastTextNode = node
}
}
// We've found the start of the selection, check if we're at or beyond the end of the selection we're importing
if (foundStart && selectionState.end >= charIndex && selectionState.end <= nextCharIndex) {
if (!selectionState.trailingImageCount) {
range.setEnd(node, selectionState.end - charIndex)
stop = true
} else {
foundEnd = true
}
}
charIndex = nextCharIndex
} else {
if (selectionState.trailingImageCount && foundEnd) {
if (node.nodeName.toLowerCase() === 'img') {
trailingImageCount++
}
if (trailingImageCount === selectionState.trailingImageCount) {
// Find which index the image is in its parent's children
let endIndex = 0
while (node.parentNode.childNodes[endIndex] !== node) {
endIndex++
}
range.setEnd(node.parentNode, endIndex + 1)
stop = true
}
}
if (!stop && node.nodeType === 1) {
// this is an element
// add all its children to the stack
let i = node.childNodes.length - 1
while (i >= 0) {
nodeStack.push(node.childNodes[i])
i -= 1
}
}
}
if (!stop) {
node = nodeStack.pop()
}
}
// If we've gone through the entire text but didn't find the beginning of a text node
// to make the selection start at, we should fall back to starting the selection
// at the END of the last text node we found
if (!foundStart && lastTextNode) {
range.setStart(lastTextNode, lastTextNode.length)
range.setEnd(lastTextNode, lastTextNode.length)
}
if (typeof selectionState.emptyBlocksIndex !== 'undefined') {
range = this.importSelectionMoveCursorPastBlocks(root, selectionState.emptyBlocksIndex, range)
}
// If the selection is right at the ending edge of a link, put it outside the anchor tag instead of inside.
if (favorLaterSelectionAnchor) {
range = this.importSelectionMoveCursorPastAnchor(selectionState, range)
}
this.selectRange(range)
}
// Utility method called from importSelection only
importSelectionMoveCursorPastAnchor (selectionState, range) {
const nodeInsideAnchorTagFunction = function (node) {
return node.nodeName.toLowerCase() === 'a'
}
if (selectionState.start === selectionState.end &&
range.startContainer.nodeType === 3 &&
range.startOffset === range.startContainer.nodeValue.length &&
traverseUp(range.startContainer, nodeInsideAnchorTagFunction)) {
let prevNode = range.startContainer
let currentNode = range.startContainer.parentNode
while (currentNode !== null && currentNode.nodeName.toLowerCase() !== 'a') {
if (currentNode.childNodes[currentNode.childNodes.length - 1] !== prevNode) {
currentNode = null
} else {
prevNode = currentNode
currentNode = currentNode.parentNode
}
}
if (currentNode !== null && currentNode.nodeName.toLowerCase() === 'a') {
let currentNodeIndex = null
for (let i = 0; currentNodeIndex === null && i < currentNode.parentNode.childNodes.length; i++) {
if (currentNode.parentNode.childNodes[i] === currentNode) {
currentNodeIndex = i
}
}
range.setStart(currentNode.parentNode, currentNodeIndex + 1)
range.collapse(true)
}
}
return range
}
// Uses the emptyBlocksIndex calculated by getIndexRelativeToAdjacentEmptyBlocks
// to move the cursor back to the start of the correct paragraph
importSelectionMoveCursorPastBlocks (root, index = 1, range) {
const treeWalker = this.doc.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, filterOnlyParentElements, false)
const startContainer = range.startContainer
let startBlock
let targetNode
let currIndex = 0
// If index is 0, we still want to move to the next block
// Chrome counts newlines and spaces that separate block elements as actual elements.
// If the selection is inside one of these text nodes, and it has a previous sibling
// which is a block element, we want the treewalker to start at the previous sibling
// and NOT at the parent of the textnode
if (startContainer.nodeType === 3 && isBlockContainer(startContainer.previousSibling)) {
startBlock = startContainer.previousSibling
} else {
startBlock = getClosestBlockContainer(startContainer)
}
// Skip over empty blocks until we hit the block we want the selection to be in
while (treeWalker.nextNode()) {
if (!targetNode) {
// Loop through all blocks until we hit the starting block element
if (startBlock === treeWalker.currentNode) {
targetNode = treeWalker.currentNode
}
} else {
targetNode = treeWalker.currentNode
currIndex++
// We hit the target index, bail
if (currIndex === index) {
break
}
// If we find a non-empty block, ignore the emptyBlocksIndex and just put selection here
if (targetNode.textContent.length > 0) {
break
}
}
}
if (!targetNode) {
targetNode = startBlock
}
// We're selecting a high-level block node, so make sure the cursor gets moved into the deepest
// element at the beginning of the block
range.setStart(getFirstSelectableLeafNode(targetNode), 0)
return range
}
// https://stackoverflow.com/questions/4176923/html-of-selected-text
// by Tim Down
getSelectionHtml () {
const sel = this.doc.getSelection()
let i
let html = ''
let len
let container
if (sel.rangeCount) {
container = this.doc.createElement('div')
for (i = 0, len = sel.rangeCount; i < len; i += 1) {
container.appendChild(sel.getRangeAt(i).cloneContents())
}
html = container.innerHTML
}
return html
}
chopHtmlByCursor (root) {
const { left } = this.getCaretOffsets(root)
const markedText = root.textContent
const { type, info } = getCursorPositionWithinMarkedText(markedText, left)
const pre = markedText.slice(0, left)
const post = markedText.slice(left)
switch (type) {
case 'OUT':
return {
pre,
post
}
case 'IN':
return {
pre: `${pre}${info}`,
post: `${info}${post}`
}
case 'LEFT':
return {
pre: markedText.slice(0, left - info),
post: markedText.slice(left - info)
}
case 'RIGHT':
return {
pre: markedText.slice(0, left + info),
post: markedText.slice(left + info)
}
}
}
/**
* Find the caret position within an element irrespective of any inline tags it may contain.
*
* @param {DOMElement} An element containing the cursor to find offsets relative to.
* @param {Range} A Range representing cursor position. Will window.getSelection if none is passed.
* @return {Object} 'left' and 'right' attributes contain offsets from beginning and end of Element
*/
getCaretOffsets (element, range) {
let preCaretRange
let postCaretRange
if (!range) {
range = window.getSelection().getRangeAt(0)
}
preCaretRange = range.cloneRange()
postCaretRange = range.cloneRange()
preCaretRange.selectNodeContents(element)
preCaretRange.setEnd(range.endContainer, range.endOffset)
postCaretRange.selectNodeContents(element)
postCaretRange.setStart(range.endContainer, range.endOffset)
return {
left: preCaretRange.toString().length,
right: postCaretRange.toString().length
}
}
selectNode (node) {
const range = this.doc.createRange()
range.selectNodeContents(node)
this.selectRange(range)
}
select (startNode, startOffset, endNode, endOffset) {
const range = this.doc.createRange()
range.setStart(startNode, startOffset)
if (endNode) {
range.setEnd(endNode, endOffset)
} else {
range.collapse(true)
}
this.selectRange(range)
return range
}
setFocus (focusNode, focusOffset) {
const selection = this.doc.getSelection()
selection.extend(focusNode, focusOffset)
}
/**
* Clear the current highlighted selection and set the caret to the start or the end of that prior selection, defaults to end.
*
* @param {boolean} moveCursorToStart A boolean representing whether or not to set the caret to the beginning of the prior selection.
*/
clearSelection (moveCursorToStart) {
const { rangeCount } = this.doc.getSelection()
if (!rangeCount) return
if (moveCursorToStart) {
this.doc.getSelection().collapseToStart()
} else {
this.doc.getSelection().collapseToEnd()
}
}
/**
* Move cursor to the given node with the given offset.
*
* @param {DomElement} node Element where to jump
* @param {integer} offset Where in the element should we jump, 0 by default
*/
moveCursor (node, offset) {
this.select(node, offset)
}
getSelectionRange () {
const selection = this.doc.getSelection()
if (selection.rangeCount === 0) {
return null
}
return selection.getRangeAt(0)
}
selectRange (range) {
const selection = this.doc.getSelection()
selection.removeAllRanges()
selection.addRange(range)
}
// https://stackoverflow.com/questions/1197401/
// how-can-i-get-the-element-the-caret-is-in-with-javascript-when-using-contenteditable
// by You
getSelectionStart () {
const node = this.doc.getSelection().anchorNode
const startNode = (node && node.nodeType === 3 ? node.parentNode : node)
return startNode
}
setCursorRange (cursorRange) {
const { anchor, focus } = cursorRange
const anchorParagraph = document.querySelector(`#${anchor.key}`)
const focusParagraph = document.querySelector(`#${focus.key}`)
const getNodeAndOffset = (node, offset) => {
if (node.nodeType === 3) {
return {
node,
offset
}
}
const childNodes = node.childNodes
const len = childNodes.length
let i
let count = 0
for (i = 0; i < len; i++) {
const child = childNodes[i]
const textContent = getTextContent(child, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER])
const textLength = textContent.length
if (child.classList && child.classList.contains(CLASS_OR_ID.AG_FRONT_ICON)) {
continue
}
// Fix #1460 - put the cursor at the next text node or element if it can be put at the last of /^\n$/ or the next text node/element.
if (/^\n$/.test(textContent) && i !== len - 1 ? count + textLength > offset : count + textLength >= offset) {
if (
child.classList && child.classList.contains('ag-inline-image')
) {
const imageContainer = child.querySelector('.ag-image-container')
const hasImg = imageContainer.querySelector('img')
if (!hasImg) {
return {
node: child,
offset: 0
}
}
if (count + textLength === offset) {
if (child.nextElementSibling) {
return {
node: child.nextElementSibling,
offset: 0
}
} else {
return {
node: imageContainer,
offset: 1
}
}
} else if (count === offset && count === 0) {
return {
node: imageContainer,
offset: 0
}
} else {
return {
node: child,
offset: 0
}
}
} else {
return getNodeAndOffset(child, offset - count)
}
} else {
count += textLength
}
}
return { node, offset }
}
let { node: anchorNode, offset: anchorOffset } = getNodeAndOffset(anchorParagraph, anchor.offset)
let { node: focusNode, offset: focusOffset } = getNodeAndOffset(focusParagraph, focus.offset)
if (anchorNode.nodeType === 3 || anchorNode.nodeType === 1 && !anchorNode.classList.contains('ag-image-container')) {
anchorOffset = Math.min(anchorOffset, anchorNode.textContent.length)
focusOffset = Math.min(focusOffset, focusNode.textContent.length)
}
// First set the anchor node and anchor offset, make it collapsed
this.select(anchorNode, anchorOffset)
// Secondly, set the focus node and focus offset.
this.setFocus(focusNode, focusOffset)
}
isValidCursorNode (node) {
if (!node) return false
if (node.nodeType === 3) {
node = node.parentNode
}
return node.closest('span.ag-paragraph')
}
getCursorRange () {
let { anchorNode, anchorOffset, focusNode, focusOffset } = this.doc.getSelection()
const isAnchorValid = this.isValidCursorNode(anchorNode)
const isFocusValid = this.isValidCursorNode(focusNode)
let needFix = false
if (!isAnchorValid && isFocusValid) {
needFix = true
anchorNode = focusNode
anchorOffset = focusOffset
} else if (isAnchorValid && !isFocusValid) {
needFix = true
focusNode = anchorNode
focusOffset = anchorOffset
} else if (!isAnchorValid && !isFocusValid) {
const editor = document.querySelector('#ag-editor-id').parentNode
editor.blur()
return new Cursor({
start: null,
end: null,
anchor: null,
focus: null
})
}
// fix bug click empty line, the cursor will jump to the end of pre line.
if (
anchorNode === focusNode &&
anchorOffset === focusOffset &&
anchorNode.textContent === '\n' &&
focusOffset === 0
) {
focusOffset = anchorOffset = 1
}
const anchorParagraph = findNearestParagraph(anchorNode)
const focusParagraph = findNearestParagraph(focusNode)
let aOffset = getOffsetOfParagraph(anchorNode, anchorParagraph) + anchorOffset
let fOffset = getOffsetOfParagraph(focusNode, focusParagraph) + focusOffset
// fix input after image.
if (
anchorNode === focusNode &&
anchorOffset === focusOffset &&
anchorNode.parentNode.classList.contains('ag-image-container') &&
anchorNode.previousElementSibling &&
anchorNode.previousElementSibling.nodeName === 'IMG'
) {
const imageWrapper = anchorNode.parentNode.parentNode
const preElement = imageWrapper.previousElementSibling
aOffset = 0
if (preElement) {
aOffset += getOffsetOfParagraph(preElement, anchorParagraph)
aOffset += getTextContent(preElement, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER]).length
}
aOffset += getTextContent(imageWrapper, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER]).length
fOffset = aOffset
}
if (
anchorNode === focusNode &&
anchorNode.nodeType === 1 &&
anchorNode.classList.contains('ag-image-container')
) {
const imageWrapper = anchorNode.parentNode
const preElement = imageWrapper.previousElementSibling
aOffset = 0
if (preElement) {
aOffset += getOffsetOfParagraph(preElement, anchorParagraph)
aOffset += getTextContent(preElement, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER]).length
}
if (anchorOffset === 1) {
aOffset += getTextContent(imageWrapper, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER]).length
}
fOffset = aOffset
}
const anchor = { key: anchorParagraph.id, offset: aOffset }
const focus = { key: focusParagraph.id, offset: fOffset }
const result = new Cursor({ anchor, focus })
if (needFix) {
this.setCursorRange(result)
}
return result
}
// topOffset is the line counts above cursor, and bottomOffset is line counts below cursor.
getCursorYOffset (paragraph) {
const { y } = this.getCursorCoords()
const { height, top } = paragraph.getBoundingClientRect()
const lineHeight = parseFloat(getComputedStyle(paragraph).lineHeight)
const topOffset = Math.round((y - top) / lineHeight)
const bottomOffset = Math.round((top + height - lineHeight - y) / lineHeight)
return {
topOffset,
bottomOffset
}
}
getCursorCoords () {
const sel = this.doc.getSelection()
let range
let x = 0
let y = 0
let width = 0
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange()
if (range.getClientRects) {
// range.collapse(true)
let rects = range.getClientRects()
if (rects.length === 0 && range.startContainer && (range.startContainer.nodeType === Node.ELEMENT_NODE || range.startContainer.nodeType === Node.TEXT_NODE)) {
rects = range.startContainer.parentElement.getClientRects()
// prevent tiny vibrations
if (rects.length) {
const rect = rects[0]
rect.y = rect.y + 1
}
}
if (rects.length) {
const { left, top, x: rectX, y: rectY, width: rWidth } = rects[0]
x = rectX || left
y = rectY || top
width = rWidth
}
}
}
return { x, y, width }
}
getSelectionEnd () {
const node = this.doc.getSelection().focusNode
const endNode = (node && node.nodeType === 3 ? node.parentNode : node)
return endNode
}
}
export default new Selection(document)
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/selection/dom.js | src/muya/lib/selection/dom.js | import {
LOWERCASE_TAGS, CLASS_OR_ID, blockContainerElementNames, emptyElementNames
} from '../config'
const CHOP_TEXT_REG = /(\*{1,3})([^*]+)(\1)/g
export const getTextContent = (node, blackList) => {
if (node.nodeType === 3) {
return node.textContent
} else if (!blackList) {
return node.textContent
}
let text = ''
if (blackList.some(className => node.classList && node.classList.contains(className))) {
return text
}
// Handle inline image
if (node.nodeType === 1 && node.classList.contains('ag-inline-image')) {
const raw = node.getAttribute('data-raw')
const imageContainer = node.querySelector('.ag-image-container')
const hasImg = imageContainer.querySelector('img')
const childNodes = imageContainer.childNodes
if (childNodes.length && hasImg) {
for (const child of childNodes) {
if (child.nodeType === 1 && child.nodeName === 'IMG') {
text += raw
} else if (child.nodeType === 3) {
text += child.textContent
}
}
return text
}
return text + raw
}
const childNodes = node.childNodes
for (const n of childNodes) {
text += getTextContent(n, blackList)
}
return text
}
export const getOffsetOfParagraph = (node, paragraph) => {
let offset = 0
let preSibling = node
if (node === paragraph) return offset
do {
preSibling = preSibling.previousSibling
if (preSibling) {
offset += getTextContent(preSibling, [CLASS_OR_ID.AG_MATH_RENDER, CLASS_OR_ID.AG_RUBY_RENDER]).length
}
} while (preSibling)
return (node === paragraph || node.parentNode === paragraph)
? offset
: offset + getOffsetOfParagraph(node.parentNode, paragraph)
}
export const findNearestParagraph = node => {
if (!node) {
return null
}
do {
if (isAganippeParagraph(node)) return node
node = node.parentNode
} while (node)
return null
}
export const findOutMostParagraph = node => {
do {
const parentNode = node.parentNode
if (isMuyaEditorElement(parentNode) && isAganippeParagraph(node)) return node
node = parentNode
} while (node)
}
export const isAganippeParagraph = element => {
return element && element.classList && element.classList.contains(CLASS_OR_ID.AG_PARAGRAPH)
}
export const isBlockContainer = element => {
return element && element.nodeType !== 3 &&
blockContainerElementNames.indexOf(element.nodeName.toLowerCase()) !== -1
}
export const isMuyaEditorElement = element => {
return element && element.id === CLASS_OR_ID.AG_EDITOR_ID
}
export const traverseUp = (current, testElementFunction) => {
if (!current) {
return false
}
do {
if (current.nodeType === 1) {
if (testElementFunction(current)) {
return current
}
// do not traverse upwards past the nearest containing editor
if (isMuyaEditorElement(current)) {
return false
}
}
current = current.parentNode
} while (current)
return false
}
export const getFirstSelectableLeafNode = element => {
while (element && element.firstChild) {
element = element.firstChild
}
// We don't want to set the selection to an element that can't have children, this messes up Gecko.
element = traverseUp(element, el => {
return emptyElementNames.indexOf(el.nodeName.toLowerCase()) === -1
})
// Selecting at the beginning of a table doesn't work in PhantomJS.
if (element.nodeName.toLowerCase() === LOWERCASE_TAGS.table) {
const firstCell = element.querySelector('th, td')
if (firstCell) {
element = firstCell
}
}
return element
}
export const getClosestBlockContainer = node => {
return traverseUp(node, node => {
return isBlockContainer(node) || isMuyaEditorElement(node)
})
}
export const getCursorPositionWithinMarkedText = (markedText, cursorOffset) => {
const chunks = []
let match
let result = { type: 'OUT' }
do {
match = CHOP_TEXT_REG.exec(markedText)
if (match) {
chunks.push({
index: match.index + match[1].length,
leftSymbol: match[1],
rightSymbol: match[3],
lastIndex: CHOP_TEXT_REG.lastIndex - match[3].length
})
}
} while (match)
chunks.forEach(chunk => {
const { index, leftSymbol, rightSymbol, lastIndex } = chunk
if (cursorOffset > index && cursorOffset < lastIndex) {
result = { type: 'IN', info: leftSymbol } // rightSymbol is also ok
} else if (cursorOffset === index) {
result = { type: 'LEFT', info: leftSymbol.length }
} else if (cursorOffset === lastIndex) {
result = { type: 'RIGHT', info: rightSymbol.length }
}
})
return result
}
export const compareParagraphsOrder = (paragraph1, paragraph2) => {
return paragraph1.compareDocumentPosition(paragraph2) & Node.DOCUMENT_POSITION_FOLLOWING
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/selection/cursor.js | src/muya/lib/selection/cursor.js | import { compareParagraphsOrder } from './dom'
class Cursor {
// You need to provide either `anchor`&&`focus` or `start`&&`end` or all.
constructor ({ anchor, focus, start, end, noHistory = false }) {
if (anchor && focus && start && end) {
this.anchor = anchor
this.focus = focus
this.start = start
this.end = end
} else if (anchor && focus) {
this.anchor = anchor
this.focus = focus
if (anchor.key === focus.key) {
if (anchor.offset <= focus.offset) {
this.start = this.anchor
this.end = this.focus
} else {
this.start = this.focus
this.end = this.anchor
}
} else {
const anchorParagraph = document.querySelector(`#${anchor.key}`)
const focusParagraph = document.querySelector(`#${focus.key}`)
let order = true
if (anchorParagraph && focusParagraph) {
order = compareParagraphsOrder(anchorParagraph, focusParagraph)
}
if (order) {
this.start = this.anchor
this.end = this.focus
} else {
this.start = this.focus
this.end = this.anchor
}
}
} else {
this.anchor = this.start = start
this.focus = this.end = end
}
this.noHistory = noHistory
}
}
export default Cursor
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/config/index.js | src/muya/lib/config/index.js | import htmlTags from 'html-tags'
import voidHtmlTags from 'html-tags/void'
import { generateKeyHash, genUpper2LowerKeyHash } from '../utils/hash'
import { getLongUniqueId } from '../utils/random'
// [0.25, 0.5, 1, 2, 4, 8] <—?—> [256M, 500M/768M, 1G/1000M, 2G, 4G, 8G]
// Electron 2.0.2 not support yet! So give a default value 4
export const DEVICE_MEMORY = navigator.deviceMemory || 4 // Get the device memory number(Chrome >= 63)
export const UNDO_DEPTH = DEVICE_MEMORY >= 4 ? 100 : 50
export const HAS_TEXT_BLOCK_REG = /^span$/i
export const VOID_HTML_TAGS = Object.freeze(voidHtmlTags)
export const HTML_TAGS = Object.freeze(htmlTags)
// TYPE1 ~ TYPE7 according to https://github.github.com/gfm/#html-blocks
export const BLOCK_TYPE1 = Object.freeze([
'script', 'pre', 'style'
])
export const BLOCK_TYPE2_REG = /^<!--(?=\s).*\s+-->$/
export const BLOCK_TYPE6 = Object.freeze([
'address', 'article', 'aside', 'base', 'basefont', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd',
'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html', 'iframe', 'legend', 'li', 'link', 'main', 'menu',
'menuitem', 'meta', 'nav', 'noframes', 'ol', 'optgroup', 'option', 'p', 'param', 'section', 'source', 'summary', 'table',
'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul'
])
export const BLOCK_TYPE7 = Object.freeze(htmlTags.filter(tag => {
return !BLOCK_TYPE1.find(t => t === tag) && !BLOCK_TYPE6.find(t => t === tag)
}))
export const IMAGE_EXT_REG = /\.(?:jpeg|jpg|png|gif|svg|webp)(?=\?|$)/i
export const PARAGRAPH_TYPES = Object.freeze(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'figure'])
export const blockContainerElementNames = Object.freeze([
// elements our editor generates
...PARAGRAPH_TYPES,
// all other known block elements
'address', 'article', 'aside', 'audio', 'canvas', 'dd', 'dl', 'dt', 'fieldset',
'figcaption', 'footer', 'form', 'header', 'hgroup', 'main', 'nav',
'noscript', 'output', 'section', 'video',
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'
])
export const emptyElementNames = Object.freeze(['br', 'col', 'colgroup', 'hr', 'img', 'input', 'source', 'wbr'])
export const EVENT_KEYS = Object.freeze(generateKeyHash([
'Enter',
'Backspace',
'Space',
'Delete',
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
'Tab',
'Escape'
]))
export const LOWERCASE_TAGS = Object.freeze(generateKeyHash([
...blockContainerElementNames, ...emptyElementNames, 'div'
]))
export const CLASS_OR_ID = Object.freeze(genUpper2LowerKeyHash([
'AG_ACTIVE',
'AG_AUTO_LINK',
'AG_AUTO_LINK_EXTENSION',
'AG_BACKLASH',
'AG_BUG',
'AG_BULLET_LIST',
'AG_BULLET_LIST_ITEM',
'AG_CHECKBOX_CHECKED',
'AG_CONTAINER_BLOCK',
'AG_CONTAINER_PREVIEW',
'AG_CONTAINER_ICON',
'AG_COPY_REMOVE',
'AG_EDITOR_ID',
'AG_EMOJI_MARKED_TEXT',
'AG_EMOJI_MARKER',
'AG_EMPTY',
'AG_FENCE_CODE',
'AG_FLOWCHART',
'AG_FOCUS_MODE',
'AG_FRONT_MATTER',
'AG_FRONT_ICON',
'AG_GRAY',
'AG_HARD_LINE_BREAK',
'AG_HARD_LINE_BREAK_SPACE',
'AG_LINE_END',
'AG_HEADER_TIGHT_SPACE',
'AG_HIDE',
'AG_HIGHLIGHT',
'AG_HTML_BLOCK',
'AG_HTML_ESCAPE',
'AG_HTML_PREVIEW',
'AG_HTML_TAG',
'AG_IMAGE_FAIL',
'AG_IMAGE_BUTTONS',
'AG_IMAGE_LOADING',
'AG_EMPTY_IMAGE',
'AG_IMAGE_MARKED_TEXT',
'AG_IMAGE_SRC',
'AG_IMAGE_CONTAINER',
'AG_INLINE_IMAGE',
'AG_IMAGE_SUCCESS',
'AG_IMAGE_UPLOADING',
'AG_INLINE_IMAGE_SELECTED',
'AG_INLINE_IMAGE_IS_EDIT',
'AG_INDENT_CODE',
'AG_INLINE_FOOTNOTE_IDENTIFIER',
'AG_INLINE_RULE',
'AG_LANGUAGE',
'AG_LANGUAGE_INPUT',
'AG_LINK',
'AG_LINK_IN_BRACKET',
'AG_LIST_ITEM',
'AG_LOOSE_LIST_ITEM',
'AG_MATH',
'AG_MATH_TEXT',
'AG_MATH_RENDER',
'AG_RUBY',
'AG_RUBY_TEXT',
'AG_RUBY_RENDER',
'AG_SELECTED',
'AG_SOFT_LINE_BREAK',
'AG_MATH_ERROR',
'AG_MATH_MARKER',
'AG_MATH_RENDER',
'AG_MATH_TEXT',
'AG_MERMAID',
'AG_MULTIPLE_MATH',
'AG_NOTEXT_LINK',
'AG_ORDER_LIST',
'AG_ORDER_LIST_ITEM',
'AG_OUTPUT_REMOVE',
'AG_PARAGRAPH',
'AG_RAW_HTML',
'AG_REFERENCE_LABEL',
'AG_REFERENCE_LINK',
'AG_REFERENCE_MARKER',
'AG_REFERENCE_TITLE',
'AG_REMOVE',
'AG_RUBY',
'AG_RUBY_RENDER',
'AG_RUBY_TEXT',
'AG_SELECTION',
'AG_SEQUENCE',
'AG_PLANTUML',
'AG_SHOW_PREVIEW',
'AG_SOFT_LINE_BREAK',
'AG_TASK_LIST',
'AG_TASK_LIST_ITEM',
'AG_TASK_LIST_ITEM_CHECKBOX',
'AG_TIGHT_LIST_ITEM',
'AG_TOOL_BAR',
'AG_VEGA_LITE',
'AG_WARN'
]))
export const DAED_REMOVE_SELECTOR = Object.freeze(new Set([
'.ag-image-marked-text::before',
'.ag-image-marked-text.ag-image-fail::before',
'.ag-hide',
'.ag-gray',
'.ag-warn'
]))
export const CURSOR_ANCHOR_DNA = getLongUniqueId()
export const CURSOR_FOCUS_DNA = getLongUniqueId()
export const DEFAULT_TURNDOWN_CONFIG = Object.freeze({
headingStyle: 'atx', // setext or atx
hr: '---',
bulletListMarker: '-', // -, +, or *
codeBlockStyle: 'fenced', // fenced or indented
fence: '```', // ``` or ~~~
emDelimiter: '*', // _ or *
strongDelimiter: '**', // ** or __
linkStyle: 'inlined',
linkReferenceStyle: 'full',
blankReplacement (content, node, options) {
if (node && node.classList.contains('ag-soft-line-break')) {
return LINE_BREAK
} else if (node && node.classList.contains('ag-hard-line-break')) {
return ' ' + LINE_BREAK
} else if (node && node.classList.contains('ag-hard-line-break-sapce')) {
return ''
} else {
return node.isBlock ? '\n\n' : ''
}
}
})
export const FORMAT_MARKER_MAP = Object.freeze({
em: '*',
inline_code: '`',
strong: '**',
del: '~~',
inline_math: '$',
u: {
open: '<u>',
close: '</u>'
},
sub: {
open: '<sub>',
close: '</sub>'
},
sup: {
open: '<sup>',
close: '</sup>'
},
mark: {
open: '<mark>',
close: '</mark>'
}
})
export const FORMAT_TYPES = Object.freeze(['strong', 'em', 'del', 'inline_code', 'link', 'image', 'inline_math'])
export const LINE_BREAK = '\n'
export const PREVIEW_DOMPURIFY_CONFIG = Object.freeze({
// do not forbit `class` because `code` element use class to present language
FORBID_ATTR: ['style', 'contenteditable'],
ALLOW_DATA_ATTR: false,
USE_PROFILES: {
html: true,
svg: true,
svgFilters: true,
mathMl: false
},
RETURN_TRUSTED_TYPE: false
})
export const EXPORT_DOMPURIFY_CONFIG = Object.freeze({
FORBID_ATTR: ['contenteditable'],
ALLOW_DATA_ATTR: false,
ADD_ATTR: ['data-align'],
USE_PROFILES: {
html: true,
svg: true,
svgFilters: true,
mathMl: false
},
RETURN_TRUSTED_TYPE: false,
// Allow "file" protocol to export images on Windows (#1997).
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
})
export const MUYA_DEFAULT_OPTION = Object.freeze({
fontSize: 16,
lineHeight: 1.6,
focusMode: false,
markdown: '',
// Whether to trim the beginning and ending empty line in code block when open markdown.
trimUnnecessaryCodeBlockEmptyLines: false,
preferLooseListItem: true,
autoPairBracket: true,
autoPairMarkdownSyntax: true,
autoPairQuote: true,
bulletListMarker: '-',
orderListDelimiter: '.',
tabSize: 4,
codeBlockLineNumbers: false,
// bullet/list marker width + listIndentation, tab or Daring Fireball Markdown (4 spaces) --> list indentation
listIndentation: 1,
frontmatterType: '-',
sequenceTheme: 'hand', // hand or simple
mermaidTheme: 'default', // dark / forest / default
vegaTheme: 'latimes', // excel / ggplot2 / quartz / vox / fivethirtyeight / dark / latimes
hideQuickInsertHint: false,
hideLinkPopup: false,
autoCheck: false,
// Whether we should set spellcheck attribute on our container to highlight misspelled words.
// NOTE: The browser is not able to correct misspelled words words without a custom
// implementation like in MarkText.
spellcheckEnabled: false,
// transform the image to local folder, cloud or just return the local path
imageAction: null,
// Call Electron open dialog or input element type is file.
imagePathPicker: null,
clipboardFilePath: () => {},
// image path auto completed when you input in image selector.
imagePathAutoComplete: () => [],
// Markdown extensions
superSubScript: false,
footnote: false,
isGitlabCompatibilityEnabled: false,
// Whether HTML rendering is disabled or not.
disableHtml: true
})
// export const DIAGRAM_TEMPLATE = Object.freeze({
// 'mermaid': `graph LR;\nYou-->|MarkText|Me;`
// })
export const isOsx = window && window.navigator && /Mac/.test(window.navigator.platform)
export const isWin = window && window.navigator.userAgent && /win32|wow32|win64|wow64/i.test(window.navigator.userAgent)
// http[s] (domain or IPv4 or localhost or IPv6) [port] /not-white-space
export const URL_REG = /^http(s)?:\/\/([a-z0-9\-._~]+\.[a-z]{2,}|[0-9.]+|localhost|\[[a-f0-9.:]+\])(:[0-9]{1,5})?\/[\S]+/i
// data:[<MIME-type>][;charset=<encoding>][;base64],<data>
export const DATA_URL_REG = /^data:image\/[\w+-]+(;[\w-]+=[\w-]+|;base64)*,[a-zA-Z0-9+/]+={0,2}$/
// The smallest transparent gif base64 image.
// export const SMALLEST_BASE64 = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
// export const isIOS = /(?:iPhone|iPad|iPod|iOS)/i.test(window.navigator.userAgent)
export const defaultSearchOption = Object.freeze({
isCaseSensitive: false,
isWholeWord: false,
isRegexp: false,
selectHighlight: false,
highlightIndex: -1
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/emojiPicker/index.js | src/muya/lib/ui/emojiPicker/index.js | import BaseScrollFloat from '../baseScrollFloat'
import Emoji from '../emojis'
import { patch, h } from '../../parser/render/snabbdom'
import './index.css'
class EmojiPicker extends BaseScrollFloat {
static pluginName = 'emojiPicker'
constructor (muya) {
const name = 'ag-emoji-picker'
super(muya, name)
this._renderObj = null
this.renderArray = null
this.activeItem = null
this.oldVnode = null
this.emoji = new Emoji()
this.listen()
}
get renderObj () {
return this._renderObj
}
set renderObj (obj) {
this._renderObj = obj
const renderArray = []
Object.keys(obj).forEach(key => {
renderArray.push(...obj[key])
})
this.renderArray = renderArray
if (this.renderArray.length > 0) {
this.activeItem = this.renderArray[0]
const activeEle = this.getItemElement(this.activeItem)
this.activeEleScrollIntoView(activeEle)
}
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-emoji-picker', ({ reference, emojiNode }) => {
if (!emojiNode) return this.hide()
const text = emojiNode.textContent.trim()
if (text) {
const renderObj = this.emoji.search(text)
this.renderObj = renderObj
const cb = item => {
this.muya.contentState.setEmoji(item)
}
if (this.renderArray.length) {
this.show(reference, cb)
this.render()
} else {
this.hide()
}
}
})
}
render () {
const { scrollElement, _renderObj, activeItem, oldVnode } = this
const children = Object.keys(_renderObj).map(category => {
const title = h('div.title', category)
const emojis = _renderObj[category].map(e => {
const selector = activeItem === e ? 'div.item.active' : 'div.item'
return h(selector, {
dataset: { label: e.aliases[0] },
props: { title: e.description },
on: {
click: () => {
this.selectItem(e)
}
}
}, h('span', e.emoji))
})
return h('section', [title, h('div.emoji-wrapper', emojis)])
})
const vnode = h('div', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(scrollElement, vnode)
}
this.oldVnode = vnode
}
getItemElement (item) {
const label = item.aliases[0]
return this.floatBox.querySelector(`[data-label="${label}"]`)
}
destroy () {
super.destroy()
this.emoji.destroy()
}
}
export default EmojiPicker
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/tooltip/index.js | src/muya/lib/ui/tooltip/index.js | import './index.css'
const position = (source, ele) => {
const rect = source.getBoundingClientRect()
const { top, right, height } = rect
Object.assign(ele.style, {
top: `${top + height + 15}px`,
left: `${right - ele.offsetWidth / 2 - 10}px`
})
}
class Tooltip {
constructor (muya) {
this.muya = muya
this.cache = new WeakMap()
const { container, eventCenter } = this.muya
eventCenter.attachDOMEvent(container, 'mouseover', this.mouseOver.bind(this))
}
mouseOver (event) {
const { target } = event
const toolTipTarget = target.closest('[data-tooltip]')
const { eventCenter } = this.muya
if (toolTipTarget && !this.cache.has(toolTipTarget)) {
const tooltip = toolTipTarget.getAttribute('data-tooltip')
const tooltipEle = document.createElement('div')
tooltipEle.textContent = tooltip
tooltipEle.classList.add('ag-tooltip')
document.body.appendChild(tooltipEle)
position(toolTipTarget, tooltipEle)
this.cache.set(toolTipTarget, tooltipEle)
setTimeout(() => {
tooltipEle.classList.add('active')
})
const timer = setInterval(() => {
if (!document.body.contains(toolTipTarget)) {
this.mouseLeave({ target: toolTipTarget })
clearInterval(timer)
}
}, 300)
eventCenter.attachDOMEvent(toolTipTarget, 'mouseleave', this.mouseLeave.bind(this))
}
}
mouseLeave (event) {
const { target } = event
if (this.cache.has(target)) {
const tooltipEle = this.cache.get(target)
tooltipEle.remove()
this.cache.delete(target)
}
}
}
export default Tooltip
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/tablePicker/index.js | src/muya/lib/ui/tablePicker/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import './index.css'
import { EVENT_KEYS } from '../../config'
class TablePicker extends BaseFloat {
static pluginName = 'tablePicker'
constructor (muya) {
const name = 'ag-table-picker'
super(muya, name)
this.checkerCount = {
row: 6,
column: 8
}
this.oldVnode = null
this.current = null
this.select = null
const tableContainer = this.tableContainer = document.createElement('div')
this.container.appendChild(tableContainer)
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-table-picker', (data, reference, cb) => {
if (!this.status) {
this.show(data, reference, cb)
this.render()
} else {
this.hide()
}
})
}
render () {
const { row, column } = this.checkerCount
const { row: cRow, column: cColumn } = this.current
const { row: sRow, column: sColumn } = this.select
const { tableContainer, oldVnode } = this
const tableRows = []
let i
let j
for (i = 0; i < row; i++) {
let rowSelector = 'div.ag-table-picker-row'
const cells = []
for (j = 0; j < column; j++) {
let cellSelector = 'span.ag-table-picker-cell'
if (i <= cRow && j <= cColumn) {
cellSelector += '.current'
}
if (i <= sRow && j <= sColumn) {
cellSelector += '.selected'
}
cells.push(h(cellSelector, {
key: j.toString(),
dataset: {
row: i.toString(),
column: j.toString()
},
on: {
mouseenter: event => {
const { target } = event
const r = target.getAttribute('data-row')
const c = target.getAttribute('data-column')
this.select = { row: r, column: c }
this.render()
},
click: _ => {
this.selectItem()
}
}
}))
}
tableRows.push(h(rowSelector, cells))
}
const tableFooter = h('div.footer', [
h('input.row-input', {
props: {
type: 'text',
value: +this.select.row + 1
},
on: {
keyup: event => {
this.keyupHandler(event, 'row')
}
}
}),
'x',
h('input.column-input', {
props: {
type: 'text',
value: +this.select.column + 1
},
on: {
keyup: event => {
this.keyupHandler(event, 'column')
}
}
}),
h('button', {
on: {
click: _ => {
this.selectItem()
}
}
}, 'OK')
])
const vnode = h('div', [h('div.checker', tableRows), tableFooter])
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(tableContainer, vnode)
}
this.oldVnode = vnode
}
keyupHandler (event, type) {
let number = +this.select[type]
const value = +event.target.value
if (event.key === EVENT_KEYS.ArrowUp) {
number++
} else if (event.key === EVENT_KEYS.ArrowDown) {
number--
} else if (event.key === EVENT_KEYS.Enter) {
this.selectItem()
} else if (typeof value === 'number') {
number = value - 1
}
if (number !== +this.select[type]) {
this.select[type] = Math.max(number, 0)
this.render()
}
}
show (current, reference, cb) { // current { row, column } zero base
this.current = this.select = current
super.show(reference, cb)
}
selectItem () {
const { cb } = this
const { row, column } = this.select
cb(Math.max(row, 0), Math.max(column, 0))
this.hide()
}
}
export default TablePicker
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/emojis/index.js | src/muya/lib/ui/emojis/index.js | import { filter } from 'fuzzaldrin'
import emojis from './emojisJson'
import { CLASS_OR_ID } from '../../config'
const emojisForSearch = {}
for (const emoji of emojis) {
const newEmoji = Object.assign({}, emoji, { search: [...emoji.aliases, ...emoji.tags].join(' ') })
if (emojisForSearch[newEmoji.category]) {
emojisForSearch[newEmoji.category].push(newEmoji)
} else {
emojisForSearch[newEmoji.category] = [newEmoji]
}
}
/**
* check if one emoji code is in emojis, return undefined or found emoji
*/
export const validEmoji = text => {
return emojis.find(emoji => {
return emoji.aliases.includes(text)
})
}
/**
* check edit emoji
*/
export const checkEditEmoji = node => {
if (node && node.classList.contains(CLASS_OR_ID.AG_EMOJI_MARKED_TEXT)) {
return node
}
return false
}
class Emoji {
constructor () {
this.cache = new Map()
}
search (text) {
const { cache } = this
if (cache.has(text)) return cache.get(text)
const result = {}
Object.keys(emojisForSearch).forEach(category => {
const list = filter(emojisForSearch[category], text, { key: 'search' })
if (list.length) {
result[category] = list
}
})
cache.set(text, result)
return result
}
destroy () {
return this.cache.clear()
}
}
export default Emoji
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/fileIcons/index.js | src/muya/lib/ui/fileIcons/index.js | // Because the sidebar also use the file icons, So I put this file out of floatBox directory.
import '@marktext/file-icons/build/index.css'
import fileIcons from '@marktext/file-icons'
fileIcons.getClassByName = function (name) {
const icon = fileIcons.matchName(name)
return icon ? icon.getClass(0, false) : null
}
fileIcons.getClassByLanguage = function (lang) {
const icon = fileIcons.matchLanguage(lang)
return icon ? icon.getClass(0, false) : null
}
export default fileIcons
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/quickInsert/index.js | src/muya/lib/ui/quickInsert/index.js | import { filter } from 'fuzzaldrin'
import { patch, h } from '../../parser/render/snabbdom'
import { deepCopy } from '../../utils'
import BaseScrollFloat from '../baseScrollFloat'
import { quickInsertObj } from './config'
import './index.css'
class QuickInsert extends BaseScrollFloat {
static pluginName = 'quickInsert'
constructor (muya) {
const name = 'ag-quick-insert'
super(muya, name)
this.reference = null
this.oldVnode = null
this._renderObj = null
this.renderArray = null
this.activeItem = null
this.block = null
this.renderObj = quickInsertObj
this.render()
this.listen()
}
get renderObj () {
return this._renderObj
}
set renderObj (obj) {
this._renderObj = obj
const renderArray = []
Object.keys(obj).forEach(key => {
renderArray.push(...obj[key])
})
this.renderArray = renderArray
if (this.renderArray.length > 0) {
this.activeItem = this.renderArray[0]
const activeEle = this.getItemElement(this.activeItem)
this.activeEleScrollIntoView(activeEle)
}
}
render () {
const { scrollElement, activeItem, _renderObj } = this
let children = Object.keys(_renderObj).filter(key => {
return _renderObj[key].length !== 0
})
.map(key => {
const titleVnode = h('div.title', key.toUpperCase())
const items = []
for (const item of _renderObj[key]) {
const { title, subTitle, label, icon, shortCut } = item
const iconVnode = h('div.icon-container', h('i.icon', h(`i.icon-${label.replace(/\s/g, '-')}`, {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, '')))
const description = h('div.description', [
h('div.big-title', title),
h('div.sub-title', subTitle)
])
const shortCutVnode = h('div.short-cut', [
h('span', shortCut)
])
const selector = activeItem.label === label ? 'div.item.active' : 'div.item'
items.push(h(selector, {
dataset: { label },
on: {
click: () => {
this.selectItem(item)
}
}
}, [iconVnode, description, shortCutVnode]))
}
return h('section', [titleVnode, ...items])
})
if (children.length === 0) {
children = h('div.no-result', 'No result')
}
const vnode = h('div', children)
if (this.oldVnode) {
patch(this.oldVnode, vnode)
} else {
patch(scrollElement, vnode)
}
this.oldVnode = vnode
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-quick-insert', (reference, block, status) => {
if (status) {
this.block = block
this.show(reference)
this.search(block.text.substring(1)) // remove `@` char
} else {
this.hide()
}
})
}
search (text) {
const { contentState } = this.muya
const canInserFrontMatter = contentState.canInserFrontMatter(this.block)
const obj = deepCopy(quickInsertObj)
if (!canInserFrontMatter) {
obj['basic block'].splice(2, 1)
}
let result = obj
if (text !== '') {
result = {}
Object.keys(obj).forEach(key => {
result[key] = filter(obj[key], text, { key: 'title' })
})
}
this.renderObj = result
this.render()
}
selectItem (item) {
const { contentState } = this.muya
this.block.text = ''
const { key } = this.block
const offset = 0
contentState.cursor = {
start: { key, offset },
end: { key, offset }
}
switch (item.label) {
case 'paragraph':
contentState.partialRender()
break
default:
contentState.updateParagraph(item.label, true)
break
}
// delay hide to avoid dispatch enter hander
setTimeout(this.hide.bind(this))
}
getItemElement (item) {
const { label } = item
return this.scrollElement.querySelector(`[data-label="${label}"]`)
}
}
export default QuickInsert
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/quickInsert/config.js | src/muya/lib/ui/quickInsert/config.js | import paragraphIcon from '../../assets/pngicon/paragraph/2.png'
import htmlIcon from '../../assets/pngicon/html/2.png'
import hrIcon from '../../assets/pngicon/horizontal_line/2.png'
import frontMatterIcon from '../../assets/pngicon/front_matter/2.png'
import header1Icon from '../../assets/pngicon/heading_1/2.png'
import header2Icon from '../../assets/pngicon/heading_2/2.png'
import header3Icon from '../../assets/pngicon/heading_3/2.png'
import header4Icon from '../../assets/pngicon/heading_4/2.png'
import header5Icon from '../../assets/pngicon/heading_5/2.png'
import header6Icon from '../../assets/pngicon/heading_6/2.png'
import newTableIcon from '../../assets/pngicon/new_table/2.png'
import bulletListIcon from '../../assets/pngicon/bullet_list/2.png'
import codeIcon from '../../assets/pngicon/code/2.png'
import quoteIcon from '../../assets/pngicon/quote_block/2.png'
import todoListIcon from '../../assets/pngicon/todolist/2.png'
import mathblockIcon from '../../assets/pngicon/math/2.png'
import orderListIcon from '../../assets/pngicon/order_list/2.png'
import flowchartIcon from '../../assets/pngicon/flowchart/2.png'
import sequenceIcon from '../../assets/pngicon/sequence/2.png'
import plantumlIcon from '../../assets/pngicon/plantuml/2.png'
import mermaidIcon from '../../assets/pngicon/mermaid/2.png'
import vegaIcon from '../../assets/pngicon/chart/2.png'
import { isOsx } from '../../config'
const COMMAND_KEY = isOsx ? '⌘' : 'Ctrl'
const OPTION_KEY = isOsx ? '⌥' : 'Alt'
const SHIFT_KEY = isOsx ? '⇧' : 'Shift'
// Command (or Cmd) ⌘
// Shift ⇧
// Option (or Alt) ⌥
// Control (or Ctrl) ⌃
// Caps Lock ⇪
// Fn
export const quickInsertObj = {
'basic block': [{
title: 'Paragraph',
subTitle: 'Lorem Ipsum is simply dummy text',
label: 'paragraph',
shortCut: `${COMMAND_KEY}+0`,
icon: paragraphIcon
}, {
title: 'Horizontal Line',
subTitle: '---',
label: 'hr',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+-`,
icon: hrIcon
}, {
title: 'Front Matter',
subTitle: '--- Lorem Ipsum ---',
label: 'front-matter',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+Y`,
icon: frontMatterIcon
}],
header: [{
title: 'Header 1',
subTitle: '# Lorem Ipsum is simply ...',
label: 'heading 1',
shortCut: `${COMMAND_KEY}+1`,
icon: header1Icon
}, {
title: 'Header 2',
subTitle: '## Lorem Ipsum is simply ...',
label: 'heading 2',
shortCut: `${COMMAND_KEY}+2`,
icon: header2Icon
}, {
title: 'Header 3',
subTitle: '### Lorem Ipsum is simply ...',
label: 'heading 3',
shortCut: `${COMMAND_KEY}+3`,
icon: header3Icon
}, {
title: 'Header 4',
subTitle: '#### Lorem Ipsum is simply ...',
label: 'heading 4',
shortCut: `${COMMAND_KEY}+4`,
icon: header4Icon
}, {
title: 'Header 5',
subTitle: '##### Lorem Ipsum is simply ...',
label: 'heading 5',
shortCut: `${COMMAND_KEY}+5`,
icon: header5Icon
}, {
title: 'Header 6',
subTitle: '###### Lorem Ipsum is simply ...',
label: 'heading 6',
shortCut: `${COMMAND_KEY}+6`,
icon: header6Icon
}],
'advanced block': [{
title: 'Table Block',
subTitle: '|Lorem | Ipsum is simply |',
label: 'table',
shortCut: `${SHIFT_KEY}+${COMMAND_KEY}+T`,
icon: newTableIcon
}, {
title: 'Display Math',
subTitle: '$$ Lorem Ipsum is simply $$',
label: 'mathblock',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+M`,
icon: mathblockIcon
}, {
title: 'HTML Block',
subTitle: '<div> Lorem Ipsum is simply </div>',
label: 'html',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+J`,
icon: htmlIcon
}, {
title: 'Code Block',
subTitle: '```java Lorem Ipsum is simply ```',
label: 'pre',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+C`,
icon: codeIcon
}, {
title: 'Quote Block',
subTitle: '>Lorem Ipsum is simply ...',
label: 'blockquote',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+Q`,
icon: quoteIcon
}],
'list block': [{
title: 'Order List',
subTitle: '1. Lorem Ipsum is simply ...',
label: 'ol-order',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+O`,
icon: orderListIcon
}, {
title: 'Bullet List',
subTitle: '- Lorem Ipsum is simply ...',
label: 'ul-bullet',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+U`,
icon: bulletListIcon
}, {
title: 'To-do List',
subTitle: '- [x] Lorem Ipsum is simply ...',
label: 'ul-task',
shortCut: `${OPTION_KEY}+${COMMAND_KEY}+X`,
icon: todoListIcon
}],
diagram: [{
title: 'Vega Chart',
subTitle: 'Render flow chart by vega-lite.js.',
label: 'vega-lite',
icon: vegaIcon
}, {
title: 'Flow Chart',
subTitle: 'Render flow chart by flowchart.js.',
label: 'flowchart',
icon: flowchartIcon
}, {
title: 'Sequence Diagram',
subTitle: 'Render sequence diagram by js-sequence.',
label: 'sequence',
icon: sequenceIcon
}, {
title: 'PlantUML Diagram',
subTitle: 'Render PlantUML diagrams',
label: 'plantuml',
icon: plantumlIcon
}, {
title: 'Mermaid',
subTitle: 'Render Diagram by mermaid.',
label: 'mermaid',
icon: mermaidIcon
}]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/linkTools/index.js | src/muya/lib/ui/linkTools/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import icons from './config'
import './index.css'
const defaultOptions = {
placement: 'bottom',
modifiers: {
offset: {
offset: '0, 5'
}
},
showArrow: false
}
class LinkTools extends BaseFloat {
static pluginName = 'linkTools'
constructor (muya, options = {}) {
const name = 'ag-link-tools'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.oldVnode = null
this.linkInfo = null
this.options = opts
this.icons = icons
this.hideTimer = null
const linkContainer = this.linkContainer = document.createElement('div')
this.container.appendChild(linkContainer)
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-link-tools', ({ reference, linkInfo }) => {
if (reference) {
this.linkInfo = linkInfo
setTimeout(() => {
this.show(reference)
this.render()
}, 0)
} else {
if (this.hideTimer) {
clearTimeout(this.hideTimer)
}
this.hideTimer = setTimeout(() => {
this.hide()
}, 500)
}
})
const mouseOverHandler = () => {
if (this.hideTimer) {
clearTimeout(this.hideTimer)
}
}
const mouseOutHandler = () => {
this.hide()
}
eventCenter.attachDOMEvent(this.container, 'mouseover', mouseOverHandler)
eventCenter.attachDOMEvent(this.container, 'mouseleave', mouseOutHandler)
}
render () {
const { icons, oldVnode, linkContainer } = this
const children = icons.map(i => {
let icon
let iconWrapperSelector
if (i.icon) {
// SVG icon Asset
iconWrapperSelector = 'div.icon-wrapper'
icon = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${i.icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
}
const iconWrapper = h(iconWrapperSelector, icon)
let itemSelector = `li.item.${i.type}`
return h(itemSelector, {
on: {
click: event => {
this.selectItem(event, i)
}
}
}, iconWrapper)
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(linkContainer, vnode)
}
this.oldVnode = vnode
}
selectItem (event, item) {
event.preventDefault()
event.stopPropagation()
const { contentState } = this.muya
switch (item.type) {
case 'unlink':
contentState.unlink(this.linkInfo)
this.hide()
break
case 'jump':
this.options.jumpClick(this.linkInfo)
this.hide()
break
}
}
}
export default LinkTools
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/linkTools/config.js | src/muya/lib/ui/linkTools/config.js | import unlinkIcon from '../../assets/pngicon/unlink/2.png'
import linkJumpIcon from '../../assets/pngicon/link_jump/2.png'
const icons = [
{
type: 'unlink',
icon: unlinkIcon
}, {
type: 'jump',
icon: linkJumpIcon
}
]
export default icons
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/tableTools/index.js | src/muya/lib/ui/tableTools/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import { toolList } from './config'
import './index.css'
const defaultOptions = {
placement: 'right-start',
modifiers: {
offset: {
offset: '0, 5'
}
},
showArrow: false
}
class TableBarTools extends BaseFloat {
static pluginName = 'tableBarTools'
constructor (muya, options = {}) {
const name = 'ag-table-bar-tools'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.options = opts
this.oldVnode = null
this.tableInfo = null
this.floatBox.classList.add('ag-table-bar-tools')
const tableBarContainer = this.tableBarContainer = document.createElement('div')
this.container.appendChild(tableBarContainer)
this.listen()
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-table-bar', ({ reference, tableInfo }) => {
if (reference) {
this.tableInfo = tableInfo
this.show(reference)
this.render()
} else {
this.hide()
}
})
}
render () {
const { tableInfo, oldVnode, tableBarContainer } = this
const renderArray = toolList[tableInfo.barType]
const children = renderArray.map((item) => {
const { label } = item
const selector = 'li.item'
return h(selector, {
dataset: {
label: item.action
},
on: {
click: event => {
this.selectItem(event, item)
}
}
}, label)
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(tableBarContainer, vnode)
}
this.oldVnode = vnode
}
selectItem (event, item) {
event.preventDefault()
event.stopPropagation()
const { contentState } = this.muya
contentState.editTable(item)
this.hide()
}
}
export default TableBarTools
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/tableTools/config.js | src/muya/lib/ui/tableTools/config.js | export const toolList = {
left: [{
label: 'Insert Row Above',
action: 'insert',
location: 'previous',
target: 'row'
}, {
label: 'Insert Row Below',
action: 'insert',
location: 'next',
target: 'row'
}, {
label: 'Remove Row',
action: 'remove',
location: 'current',
target: 'row'
}],
bottom: [{
label: 'Insert Column Left',
action: 'insert',
location: 'left',
target: 'column'
}, {
label: 'Insert Column Right',
action: 'insert',
location: 'right',
target: 'column'
}, {
label: 'Remove Column',
action: 'remove',
location: 'current',
target: 'column'
}]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/codePicker/index.js | src/muya/lib/ui/codePicker/index.js | import BaseScrollFloat from '../baseScrollFloat'
import { patch, h } from '../../parser/render/snabbdom'
import { search } from '../../prism/index'
import fileIcons from '../fileIcons'
import './index.css'
const defaultOptions = {
placement: 'bottom-start',
modifiers: {
offset: {
offset: '0, 0'
}
},
showArrow: false
}
class CodePicker extends BaseScrollFloat {
static pluginName = 'codePicker'
constructor (muya, options = {}) {
const name = 'ag-list-picker'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.renderArray = []
this.oldVnode = null
this.activeItem = null
this.listen()
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-code-picker', ({ reference, lang, cb }) => {
const modes = search(lang)
if (modes.length && reference) {
this.show(reference, cb)
this.renderArray = modes
this.activeItem = modes[0]
this.render()
} else {
this.hide()
}
})
}
render () {
const { renderArray, oldVnode, scrollElement, activeItem } = this
let children = renderArray.map(item => {
let iconClassNames
if (item.name) {
iconClassNames = fileIcons.getClassByLanguage(item.name)
}
// Because `markdown mode in Codemirror` don't have extensions.
// if still can not get the className, add a common className 'atom-icon light-cyan'
if (!iconClassNames) {
iconClassNames = item.name === 'markdown' ? fileIcons.getClassByName('fackname.md') : 'atom-icon light-cyan'
}
const iconSelector = 'span' + iconClassNames.split(/\s/).map(s => `.${s}`).join('')
const icon = h('div.icon-wrapper', h(iconSelector))
const text = h('div.language', item.name)
const selector = activeItem === item ? 'li.item.active' : 'li.item'
return h(selector, {
dataset: {
label: item.name
},
on: {
click: () => {
this.selectItem(item)
}
}
}, [icon, text])
})
if (children.length === 0) {
children = h('div.no-result', 'No result')
}
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(scrollElement, vnode)
}
this.oldVnode = vnode
}
getItemElement (item) {
const { name } = item
return this.floatBox.querySelector(`[data-label="${name}"]`)
}
}
export default CodePicker
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/imageSelector/index.js | src/muya/lib/ui/imageSelector/index.js | import { createApi } from 'unsplash-js'
import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import { EVENT_KEYS, URL_REG, isWin } from '../../config'
import { getUniqueId, getImageInfo as getImageSrc } from '../../utils'
import { getImageInfo } from '../../utils/getImageInfo'
import './index.css'
const toJson = res => {
if (res.type === 'success') {
return Promise.resolve(res.response)
} else {
return Promise.reject(new Error(res.type))
}
}
class ImageSelector extends BaseFloat {
static pluginName = 'imageSelector'
constructor (muya, options) {
const name = 'ag-image-selector'
const { unsplashAccessKey } = options
options = Object.assign(options, {
placement: 'bottom-center',
modifiers: {
offset: {
offset: '0, 0'
}
},
showArrow: false
})
super(muya, name, options)
this.renderArray = []
this.oldVnode = null
this.imageInfo = null
if (!unsplashAccessKey) {
this.unsplash = null
} else {
this.unsplash = createApi({
accessKey: unsplashAccessKey
})
}
this.photoList = []
this.loading = false
this.tab = 'link' // select or link
this.isFullMode = false // is show title and alt input
this.state = {
alt: '',
src: '',
title: ''
}
const imageSelectorContainer = this.imageSelectorContainer = document.createElement('div')
this.container.appendChild(imageSelectorContainer)
this.floatBox.classList.add('ag-image-selector-wrapper')
this.listen()
}
listen () {
super.listen()
const { eventCenter } = this.muya
eventCenter.subscribe('muya-image-selector', ({ reference, cb, imageInfo }) => {
if (reference) {
// Unselected image.
const { contentState } = this.muya
if (contentState.selectedImage) {
contentState.selectedImage = null
}
Object.assign(this.state, imageInfo.token.attrs)
// Remove file protocol to allow autocomplete.
const imageSrc = this.state.src
if (imageSrc && /^file:\/\//.test(imageSrc)) {
let protocolLen = 7
if (isWin && /^file:\/\/\//.test(imageSrc)) {
protocolLen = 8
}
this.state.src = imageSrc.substring(protocolLen)
}
if (this.unsplash) {
// Load latest unsplash photos.
this.loading = true
this.unsplash.photos.list({
perPage: 40
})
.then(toJson)
.then(json => {
this.loading = false
if (Array.isArray(json.results)) {
this.photoList = json.results
if (this.tab === 'unsplash') {
this.render()
}
}
})
}
this.imageInfo = imageInfo
this.show(reference, cb)
this.render()
// Auto focus and select all content of the `src.input` element.
const input = this.imageSelectorContainer.querySelector('input.src')
if (input) {
input.focus()
input.select()
}
} else {
this.hide()
}
})
}
searchPhotos = (keyword) => {
if (!this.unsplash) {
return
}
this.loading = true
this.photoList = []
this.unsplash.search.getPhotos({
query: keyword,
page: 1,
perPage: 40
})
.then(toJson)
.then(json => {
this.loading = false
if (Array.isArray(json.results)) {
this.photoList = json.results
if (this.tab === 'unsplash') {
this.render()
}
}
})
return this.render()
}
tabClick (event, tab) {
const { value } = tab
this.tab = value
return this.render()
}
toggleMode () {
this.isFullMode = !this.isFullMode
return this.render()
}
inputHandler (event, type) {
const value = event.target.value
this.state[type] = value
}
handleKeyDown (event) {
if (event.key === EVENT_KEYS.Enter) {
event.stopPropagation()
this.handleLinkButtonClick()
}
}
srcInputKeyDown (event) {
const { imagePathPicker } = this.muya
if (!imagePathPicker.status) {
if (event.key === EVENT_KEYS.Enter) {
event.stopPropagation()
this.handleLinkButtonClick()
}
return
}
switch (event.key) {
case EVENT_KEYS.ArrowUp:
event.preventDefault()
imagePathPicker.step('previous')
break
case EVENT_KEYS.ArrowDown:
case EVENT_KEYS.Tab:
event.preventDefault()
imagePathPicker.step('next')
break
case EVENT_KEYS.Enter:
event.preventDefault()
imagePathPicker.selectItem(imagePathPicker.activeItem)
break
default:
break
}
}
async handleKeyUp (event) {
const { key } = event
if (
key === EVENT_KEYS.ArrowUp ||
key === EVENT_KEYS.ArrowDown ||
key === EVENT_KEYS.Tab ||
key === EVENT_KEYS.Enter
) {
return
}
const value = event.target.value
const { eventCenter } = this.muya
const reference = this.imageSelectorContainer.querySelector('input.src')
const cb = item => {
const { text } = item
let basePath = ''
const pathSep = value.match(/(\/|\\)(?:[^/\\]+)$/)
if (pathSep && pathSep[0]) {
basePath = value.substring(0, pathSep.index + 1)
}
const newValue = basePath + text
const len = newValue.length
reference.value = newValue
this.state.src = newValue
reference.focus()
reference.setSelectionRange(
len,
len
)
}
let list
if (!value) {
list = []
} else {
list = await this.muya.options.imagePathAutoComplete(value)
}
eventCenter.dispatch('muya-image-picker', { reference, list, cb })
}
handleLinkButtonClick () {
return this.replaceImageAsync(this.state)
}
replaceImageAsync = async ({ alt, src, title }) => {
if (!this.muya.options.imageAction || URL_REG.test(src)) {
const { alt: oldAlt, src: oldSrc, title: oldTitle } = this.imageInfo.token.attrs
if (alt !== oldAlt || src !== oldSrc || title !== oldTitle) {
this.muya.contentState.replaceImage(this.imageInfo, { alt, src, title })
}
this.hide()
} else {
if (src) {
const id = `loading-${getUniqueId()}`
this.muya.contentState.replaceImage(this.imageInfo, {
alt: id,
src,
title
})
this.hide()
try {
const newSrc = await this.muya.options.imageAction(src, id, alt)
const { src: localPath } = getImageSrc(src)
if (localPath) {
this.muya.contentState.stateRender.urlMap.set(newSrc, localPath)
}
const imageWrapper = this.muya.container.querySelector(`span[data-id=${id}]`)
if (imageWrapper) {
const imageInfo = getImageInfo(imageWrapper)
this.muya.contentState.replaceImage(imageInfo, {
alt,
src: newSrc,
title
})
}
} catch (error) {
// TODO: Notify user about an error.
console.error('Unexpected error on image action:', error)
}
} else {
this.hide()
}
}
this.muya.eventCenter.dispatch('stateChange')
}
async handleSelectButtonClick () {
if (!this.muya.options.imagePathPicker) {
console.warn('You need to add a imagePathPicker option')
return
}
const path = await this.muya.options.imagePathPicker()
const { alt, title } = this.state
return this.replaceImageAsync({
alt,
title,
src: path
})
}
renderHeader () {
const tabs = [{
label: 'Select',
value: 'select'
}, {
label: 'Embed link',
value: 'link'
}]
if (this.unsplash) {
tabs.push({
label: 'Unsplash',
value: 'unsplash'
})
}
const children = tabs.map(tab => {
const itemSelector = this.tab === tab.value ? 'li.active' : 'li'
return h(itemSelector, h('span', {
on: {
click: event => {
this.tabClick(event, tab)
}
}
}, tab.label))
})
return h('ul.header', children)
}
renderBody = () => {
const { tab, state, isFullMode } = this
const { alt, title, src } = state
let bodyContent = null
if (tab === 'select') {
bodyContent = [
h('button.muya-button.role-button.select', {
on: {
click: event => {
this.handleSelectButtonClick()
}
}
}, 'Choose an Image'),
h('span.description', 'Choose image from your computer.')
]
} else if (tab === 'link') {
const altInput = h('input.alt', {
props: {
placeholder: 'Alt text',
value: alt
},
on: {
input: event => {
this.inputHandler(event, 'alt')
},
paste: event => {
this.inputHandler(event, 'alt')
},
keydown: event => {
this.handleKeyDown(event)
}
}
})
const srcInput = h('input.src', {
props: {
placeholder: 'Image link or local path',
value: src
},
on: {
input: event => {
this.inputHandler(event, 'src')
},
paste: event => {
this.inputHandler(event, 'src')
},
keydown: event => {
this.srcInputKeyDown(event)
},
keyup: event => {
this.handleKeyUp(event)
}
}
})
const titleInput = h('input.title', {
props: {
placeholder: 'Image title',
value: title
},
on: {
input: event => {
this.inputHandler(event, 'title')
},
paste: event => {
this.inputHandler(event, 'title')
},
keydown: event => {
this.handleKeyDown(event)
}
}
})
const inputWrapper = isFullMode
? h('div.input-container', [altInput, srcInput, titleInput])
: h('div.input-container', [srcInput])
const embedButton = h('button.muya-button.role-button.link', {
on: {
click: event => {
this.handleLinkButtonClick()
}
}
}, 'Embed Image')
const bottomDes = h('span.description', [
h('span', 'Paste web image or local image path. Use '),
h('a', {
on: {
click: event => {
this.toggleMode()
}
}
}, `${isFullMode ? 'simple mode' : 'full mode'}.`)
])
bodyContent = [inputWrapper, embedButton, bottomDes]
} else {
const searchInput = h('input.search', {
props: {
placeholder: 'Search photos on Unsplash'
},
on: {
keydown: (event) => {
const value = event.target.value
if (event.key === EVENT_KEYS.Enter && value) {
event.preventDefault()
event.stopPropagation()
this.searchPhotos(value)
}
}
}
})
bodyContent = [searchInput]
if (this.loading) {
const loadingCom = h('div.ag-plugin-loading')
bodyContent.push(loadingCom)
} else if (this.photoList.length === 0) {
const noDataCom = h('div.no-data', 'No result...')
bodyContent.push(noDataCom)
} else {
const photos = this.photoList.map(photo => {
const imageWrapper = h('div.image-wrapper', {
props: {
style: `background: ${photo.color};`
},
on: {
click: () => {
const title = photo.user.name
const alt = photo.alt_description
const src = photo.urls.regular
const { id: photoId } = photo
this.unsplash.photos.get({ photoId })
.then(toJson)
.then(result => {
this.unsplash.photos.trackDownload({
downloadLocation: result.links.download_location
})
})
return this.replaceImageAsync({ alt, title, src })
}
}
}, h('img', {
props: {
src: photo.urls.thumb
}
}))
const desCom = h('div.des', ['By ', h('a', {
props: {
href: photo.links.html
},
on: {
click: () => {
if (this.options.photoCreatorClick) {
this.options.photoCreatorClick(photo.user.links.html)
}
}
}
}, photo.user.name)])
return h('div.photo', [imageWrapper, desCom])
})
const photoWrapper = h('div.photos-wrapper', photos)
const moreCom = h('div.more', 'Search for more photos...')
bodyContent.push(photoWrapper, moreCom)
}
}
return h('div.image-select-body', bodyContent)
}
render () {
const { oldVnode, imageSelectorContainer } = this
const selector = 'div'
const vnode = h(selector, [this.renderHeader(), this.renderBody()])
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(imageSelectorContainer, vnode)
}
this.oldVnode = vnode
}
}
export default ImageSelector
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/frontMenu/index.js | src/muya/lib/ui/frontMenu/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import { menu, getSubMenu, getLabel } from './config'
import './index.css'
const MAX_SUBMENU_HEIGHT = 400
const ITEM_HEIGHT = 28
const PADDING = 10
const defaultOptions = {
placement: 'bottom',
modifiers: {
offset: {
offset: '0, 10'
}
},
showArrow: false
}
class FrontMenu extends BaseFloat {
static pluginName = 'frontMenu'
constructor (muya, options = {}) {
const name = 'ag-front-menu'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.oldVnode = null
this.outmostBlock = null
this.startBlock = null
this.endBlock = null
this.options = opts
this.reference = null
const frontMenuContainer = this.frontMenuContainer = document.createElement('div')
Object.assign(this.container.parentNode.style, {
overflow: 'visible'
})
this.container.appendChild(frontMenuContainer)
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-front-menu', ({ reference, outmostBlock, startBlock, endBlock }) => {
if (reference) {
this.outmostBlock = outmostBlock
this.startBlock = startBlock
this.endBlock = endBlock
this.reference = reference
setTimeout(() => {
this.show(reference)
this.render()
}, 0)
} else {
this.hide()
this.reference = null
}
})
}
renderSubMenu (subMenu) {
const { reference } = this
const rect = reference.getBoundingClientRect()
const windowHeight = document.documentElement.clientHeight
const children = subMenu.map(menuItem => {
const { icon, title, label, shortCut } = menuItem
const iconWrapperSelector = 'div.icon-wrapper'
const iconWrapper = h(iconWrapperSelector, h('i.icon', h(`i.icon-${label.replace(/\s/g, '-')}`, {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, '')))
const textWrapper = h('span', title)
const shortCutWrapper = h('div.short-cut', [
h('span', shortCut)
])
let itemSelector = `li.item.${label}`
if (label === getLabel(this.outmostBlock)) {
itemSelector += '.active'
}
return h(itemSelector, {
on: {
click: event => {
this.selectItem(event, { label })
}
}
}, [iconWrapper, textWrapper, shortCutWrapper])
})
let subMenuSelector = 'div.submenu'
if (windowHeight - rect.bottom < MAX_SUBMENU_HEIGHT - (ITEM_HEIGHT + PADDING)) {
subMenuSelector += '.align-bottom'
}
return h(subMenuSelector, h('ul', children))
}
render () {
const { oldVnode, frontMenuContainer, outmostBlock, startBlock, endBlock } = this
const { type, functionType } = outmostBlock
const children = menu.map(({ icon, label, text, shortCut }) => {
const subMenu = getSubMenu(outmostBlock, startBlock, endBlock)
const iconWrapperSelector = 'div.icon-wrapper'
const iconWrapper = h(iconWrapperSelector, h('i.icon', h(`i.icon-${label.replace(/\s/g, '-')}`, {
style: {
background: `url(${icon}) no-repeat`,
'background-size': '100%'
}
}, '')))
const textWrapper = h('span', text)
const shortCutWrapper = h('div.short-cut', [
h('span', shortCut)
])
let itemSelector = `li.item.${label}`
const itemChildren = [iconWrapper, textWrapper, shortCutWrapper]
if (label === 'turnInto' && subMenu.length !== 0) {
itemChildren.push(this.renderSubMenu(subMenu))
}
if (label === 'turnInto' && subMenu.length === 0) {
itemSelector += '.disabled'
}
// front matter can not be duplicated.
if (label === 'duplicate' && type === 'pre' && functionType === 'frontmatter') {
itemSelector += '.disabled'
}
return h(itemSelector, {
on: {
click: event => {
this.selectItem(event, { label })
}
}
}, itemChildren)
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(frontMenuContainer, vnode)
}
this.oldVnode = vnode
}
selectItem (event, { label }) {
event.preventDefault()
event.stopPropagation()
const { type, functionType } = this.outmostBlock
// front matter can not be duplicated.
if (label === 'duplicate' && type === 'pre' && functionType === 'frontmatter') {
return
}
const { contentState } = this.muya
contentState.selectedBlock = null
switch (label) {
case 'duplicate': {
contentState.duplicate()
break
}
case 'delete': {
contentState.deleteParagraph()
break
}
case 'new': {
contentState.insertParagraph('after', '', true)
break
}
case 'turnInto':
// do nothing, do not hide float box.
return
default:
contentState.updateParagraph(label)
break
}
// delay hide to avoid dispatch enter hander
setTimeout(this.hide.bind(this))
}
}
export default FrontMenu
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/frontMenu/config.js | src/muya/lib/ui/frontMenu/config.js | import copyIcon from '../../assets/pngicon/copy/2.png'
import newIcon from '../../assets/pngicon/paragraph/2.png'
import deleteIcon from '../../assets/pngicon/delete/2.png'
import turnIcon from '../../assets/pngicon/turninto/2.png'
import { isOsx } from '../../config'
import { quickInsertObj } from '../quickInsert/config'
const wholeSubMenu = Object.keys(quickInsertObj).reduce((acc, key) => {
const items = quickInsertObj[key]
return [...acc, ...items]
}, [])
const COMMAND_KEY = isOsx ? '⌘' : '⌃'
export const menu = [{
icon: copyIcon,
label: 'duplicate',
text: 'Duplicate',
shortCut: `⇧${COMMAND_KEY}P`
}, {
icon: turnIcon,
label: 'turnInto',
text: 'Turn Into'
}, {
icon: newIcon,
label: 'new',
text: 'New Paragraph',
shortCut: `⇧${COMMAND_KEY}N`
}, {
icon: deleteIcon,
label: 'delete',
text: 'Delete',
shortCut: `⇧${COMMAND_KEY}D`
}]
export const getLabel = block => {
const { type, functionType, listType } = block
let label = ''
switch (type) {
case 'p': {
label = 'paragraph'
break
}
case 'figure': {
if (functionType === 'table') {
label = 'table'
} else if (functionType === 'html') {
label = 'html'
} else if (functionType === 'multiplemath') {
label = 'mathblock'
}
break
}
case 'pre': {
if (functionType === 'fencecode' || functionType === 'indentcode') {
label = 'pre'
} else if (functionType === 'frontmatter') {
label = 'front-matter'
}
break
}
case 'ul': {
if (listType === 'task') {
label = 'ul-task'
} else {
label = 'ul-bullet'
}
break
}
case 'ol': {
label = 'ol-order'
break
}
case 'blockquote': {
label = 'blockquote'
break
}
case 'h1': {
label = 'heading 1'
break
}
case 'h2': {
label = 'heading 2'
break
}
case 'h3': {
label = 'heading 3'
break
}
case 'h4': {
label = 'heading 4'
break
}
case 'h5': {
label = 'heading 5'
break
}
case 'h6': {
label = 'heading 6'
break
}
case 'hr': {
label = 'hr'
break
}
default:
label = 'paragraph'
break
}
return label
}
export const getSubMenu = (block, startBlock, endBlock) => {
const { type } = block
switch (type) {
case 'p': {
return wholeSubMenu.filter(menuItem => {
const REG_EXP = startBlock.key === endBlock.key
? /front-matter|hr|table/
: /front-matter|hr|table|heading/
return !REG_EXP.test(menuItem.label)
})
}
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6': {
return wholeSubMenu.filter(menuItem => {
return /heading|paragraph/.test(menuItem.label)
})
}
case 'ul':
case 'ol': {
return wholeSubMenu.filter(menuItem => {
return /ul|ol/.test(menuItem.label)
})
}
default:
return []
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/transformer/index.js | src/muya/lib/ui/transformer/index.js | import './index.css'
const CIRCLES = [
'top-left',
'top-right',
'bottom-left',
'bottom-right'
]
const CIRCLE_RADIO = 6
class Transformer {
static pluginName = 'transformer'
constructor (muya, options) {
this.muya = muya
this.options = options
this.reference = null
this.imageInfo = null
this.movingAnchor = null
this.status = false
this.width = null
this.eventId = []
this.lastScrollTop = null
this.resizing = false
const container = this.container = document.createElement('div')
container.classList.add('ag-transformer')
document.body.appendChild(container)
this.listen()
}
listen () {
const { eventCenter, container } = this.muya
const scrollHandler = event => {
if (typeof this.lastScrollTop !== 'number') {
this.lastScrollTop = event.target.scrollTop
return
}
// only when scoll distance great than 50px, then hide the float box.
if (!this.resizing && this.status && Math.abs(event.target.scrollTop - this.lastScrollTop) > 50) {
this.hide()
}
}
eventCenter.attachDOMEvent(document, 'click', this.hide.bind(this))
eventCenter.subscribe('muya-transformer', ({ reference, imageInfo }) => {
this.reference = reference
if (reference) {
this.imageInfo = imageInfo
setTimeout(() => {
this.render()
})
} else {
this.hide()
}
})
eventCenter.attachDOMEvent(container, 'scroll', scrollHandler)
eventCenter.attachDOMEvent(this.container, 'dragstart', event => event.preventDefault())
eventCenter.attachDOMEvent(document.body, 'mousedown', this.mouseDown)
}
render () {
const { eventCenter } = this.muya
if (this.status) {
this.hide()
}
this.status = true
this.createElements()
this.update()
eventCenter.dispatch('muya-float', this, true)
}
createElements () {
CIRCLES.forEach(c => {
const circle = document.createElement('div')
circle.classList.add('circle')
circle.classList.add(c)
circle.setAttribute('data-position', c)
this.container.appendChild(circle)
})
}
update () {
const rect = this.reference.getBoundingClientRect()
CIRCLES.forEach(c => {
const circle = this.container.querySelector(`.${c}`)
switch (c) {
case 'top-left':
circle.style.left = `${rect.left - CIRCLE_RADIO}px`
circle.style.top = `${rect.top - CIRCLE_RADIO}px`
break
case 'top-right':
circle.style.left = `${rect.left + rect.width - CIRCLE_RADIO}px`
circle.style.top = `${rect.top - CIRCLE_RADIO}px`
break
case 'bottom-left':
circle.style.left = `${rect.left - CIRCLE_RADIO}px`
circle.style.top = `${rect.top + rect.height - CIRCLE_RADIO}px`
break
case 'bottom-right':
circle.style.left = `${rect.left + rect.width - CIRCLE_RADIO}px`
circle.style.top = `${rect.top + rect.height - CIRCLE_RADIO}px`
break
}
})
}
mouseDown = (event) => {
const target = event.target
if (!target.closest('.circle')) return
const { eventCenter } = this.muya
this.movingAnchor = target.getAttribute('data-position')
const mouseMoveId = eventCenter.attachDOMEvent(document.body, 'mousemove', this.mouseMove)
const mouseUpId = eventCenter.attachDOMEvent(document.body, 'mouseup', this.mouseUp)
this.resizing = true
// Hide image toolbar
eventCenter.dispatch('muya-image-toolbar', { reference: null })
this.eventId.push(mouseMoveId, mouseUpId)
}
mouseMove = (event) => {
const clientX = event.clientX
let width
let relativeAnchor
const image = this.reference.querySelector('img')
if (!image) {
return
}
switch (this.movingAnchor) {
case 'top-left':
case 'bottom-left':
relativeAnchor = this.container.querySelector('.top-right')
width = Math.max(relativeAnchor.getBoundingClientRect().left + CIRCLE_RADIO - clientX, 50)
break
case 'top-right':
case 'bottom-right':
relativeAnchor = this.container.querySelector('.top-left')
width = Math.max(clientX - relativeAnchor.getBoundingClientRect().left - CIRCLE_RADIO, 50)
break
}
// Image width/height attribute must be an integer.
width = parseInt(width)
this.width = width
image.setAttribute('width', width)
this.update()
}
mouseUp = (event) => {
const { eventCenter } = this.muya
if (this.eventId.length) {
for (const id of this.eventId) {
eventCenter.detachDOMEvent(id)
}
this.eventId = []
}
// todo update data
if (typeof this.width === 'number') {
this.muya.contentState.updateImage(this.imageInfo, 'width', this.width)
this.width = null
this.hide()
}
this.resizing = false
this.movingAnchor = null
}
hide () {
const { eventCenter } = this.muya
const circles = this.container.querySelectorAll('.circle')
Array.from(circles).forEach(c => c.remove())
this.status = false
eventCenter.dispatch('muya-float', this, false)
}
}
export default Transformer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/formatPicker/index.js | src/muya/lib/ui/formatPicker/index.js | import BaseFloat from '../baseFloat'
import { patch, h } from '../../parser/render/snabbdom'
import icons from './config'
import './index.css'
const defaultOptions = {
placement: 'top',
modifiers: {
offset: {
offset: '0, 5'
}
},
showArrow: false
}
class FormatPicker extends BaseFloat {
static pluginName = 'formatPicker'
constructor (muya, options = {}) {
const name = 'ag-format-picker'
const opts = Object.assign({}, defaultOptions, options)
super(muya, name, opts)
this.oldVnode = null
this.formats = null
this.options = opts
this.icons = icons
const formatContainer = this.formatContainer = document.createElement('div')
this.container.appendChild(formatContainer)
this.floatBox.classList.add('ag-format-picker-container')
this.listen()
}
listen () {
const { eventCenter } = this.muya
super.listen()
eventCenter.subscribe('muya-format-picker', ({ reference, formats }) => {
if (reference) {
this.formats = formats
setTimeout(() => {
this.show(reference)
this.render()
}, 0)
} else {
this.hide()
}
})
}
render () {
const { icons, oldVnode, formatContainer, formats } = this
const children = icons.map(i => {
let icon
let iconWrapperSelector
if (i.icon) {
// SVG icon Asset
iconWrapperSelector = 'div.icon-wrapper'
icon = h('i.icon', h('i.icon-inner', {
style: {
background: `url(${i.icon}) no-repeat`,
'background-size': '100%'
}
}, ''))
}
const iconWrapper = h(iconWrapperSelector, icon)
let itemSelector = `li.item.${i.type}`
if (formats.some(f => f.type === i.type || f.type === 'html_tag' && f.tag === i.type)) {
itemSelector += '.active'
}
return h(itemSelector, {
attrs: {
title: `${i.tooltip} ${i.shortcut}`
},
on: {
click: event => {
this.selectItem(event, i)
}
}
}, [iconWrapper])
})
const vnode = h('ul', children)
if (oldVnode) {
patch(oldVnode, vnode)
} else {
patch(formatContainer, vnode)
}
this.oldVnode = vnode
}
selectItem (event, item) {
event.preventDefault()
event.stopPropagation()
const { contentState } = this.muya
contentState.render()
contentState.format(item.type)
if (/link|image/.test(item.type)) {
this.hide()
} else {
const { formats } = contentState.selectionFormats()
this.formats = formats
this.render()
}
}
}
export default FormatPicker
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/muya/lib/ui/formatPicker/config.js | src/muya/lib/ui/formatPicker/config.js | import { isOsx } from '../../config'
import strongIcon from '../../assets/pngicon/format_strong/2.png'
import emphasisIcon from '../../assets/pngicon/format_emphasis/2.png'
import underlineIcon from '../../assets/pngicon/format_underline/2.png'
import codeIcon from '../../assets/pngicon/code/2.png'
import imageIcon from '../../assets/pngicon/format_image/2.png'
import linkIcon from '../../assets/pngicon/format_link/2.png'
import strikeIcon from '../../assets/pngicon/format_strike/2.png'
import mathIcon from '../../assets/pngicon/format_math/2.png'
import highlightIcon from '../../assets/pngicon/highlight/2.png'
import clearIcon from '../../assets/pngicon/format_clear/2.png'
const COMMAND_KEY = isOsx ? '⌘' : 'Ctrl'
const icons = [
{
type: 'strong',
tooltip: 'Bold',
shortcut: `${COMMAND_KEY}+B`,
icon: strongIcon
}, {
type: 'em',
tooltip: 'Italic',
shortcut: `${COMMAND_KEY}+I`,
icon: emphasisIcon
}, {
type: 'u',
tooltip: 'Underline',
shortcut: `${COMMAND_KEY}+U`,
icon: underlineIcon
}, {
type: 'del',
tooltip: 'Strikethrough',
shortcut: `${COMMAND_KEY}+D`,
icon: strikeIcon
}, {
type: 'mark',
tooltip: 'Highlight',
shortcut: `⇧+${COMMAND_KEY}+H`,
icon: highlightIcon
}, {
type: 'inline_code',
tooltip: 'Inline Code',
shortcut: `${COMMAND_KEY}+\``,
icon: codeIcon
}, {
type: 'inline_math',
tooltip: 'Inline Math',
shortcut: `⇧+${COMMAND_KEY}+M`,
icon: mathIcon
}, {
type: 'link',
tooltip: 'Link',
shortcut: `${COMMAND_KEY}+L`,
icon: linkIcon
}, {
type: 'image',
tooltip: 'Image',
shortcut: `⇧+${COMMAND_KEY}+I`,
icon: imageIcon
}, {
type: 'clear',
tooltip: 'Clear Formatting',
shortcut: `⇧+${COMMAND_KEY}+R`,
icon: clearIcon
}
]
export default icons
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.