Browse Source

Convert old ndoc comments to new typedoc format

pull/1197/head
Vitaly Puzrin 3 months ago
parent
commit
cff92d9687
  1. 1
      eslint.config.mjs
  2. 351
      src/markdownit.ts
  3. 20
      src/parser_block.ts
  4. 22
      src/parser_core.ts
  5. 26
      src/parser_inline.ts
  6. 98
      src/renderer.ts
  7. 253
      src/ruler.ts
  8. 98
      src/token.ts

1
eslint.config.mjs

@ -4,6 +4,7 @@ export default [
...neostandard({
env: ['browser', 'node'],
ignores: [
'apidoc/**',
'benchmark/extra/**',
'demo/**',
'dist/**'

351
src/markdownit.ts

@ -108,44 +108,11 @@ function normalizeLinkText (url: string): string {
}
/**
* class MarkdownIt
*
* Main parser/renderer class.
*
* ##### Usage
*
* ```javascript
* // node.js, "classic" way:
* var MarkdownIt = require('markdown-it'),
* md = new MarkdownIt();
* var result = md.render('# markdown-it rulezz!');
*
* // node.js, the same, but with sugar:
* var md = require('markdown-it')();
* var result = md.render('# markdown-it rulezz!');
*
* // browser without AMD, added to "window" on script load
* // Note, there are no dash.
* var md = window.markdownit();
* var result = md.render('# markdown-it rulezz!');
* ```
*
* Single line rendering, without paragraph wrap:
*
* ```javascript
* var md = require('markdown-it')();
* var result = md.renderInline('__markdown-it__ rulezz!');
* ```
**/
/**
* new MarkdownIt([presetName, options])
* - presetName (String): optional, `commonmark` / `zero`
* - options (Object)
*
* Creates parser instanse with given config. Can be called without `new`.
* Creates a parser instance with the given config. Can be called without `new`.
*
* ##### presetName
* The optional `presetName` can be `commonmark` or `zero`.
*
* MarkdownIt provides named presets as a convenience to quickly
* enable/disable active syntax rules and options for common use cases.
@ -159,7 +126,7 @@ function normalizeLinkText (url: string): string {
* all rules disabled. Useful to quickly setup your config via `.enable()`.
* For example, when you need only `bold` and `italic` markup and nothing else.
*
* ##### options:
* Available options:
*
* - __html__ - `false`. Set `true` to enable HTML tags in source. Be careful!
* That's not safe! You may need external sanitizer to protect output from XSS.
@ -174,17 +141,39 @@ function normalizeLinkText (url: string): string {
* - __typographer__ - `false`. Set `true` to enable [some language-neutral
* replacement](https://github.com/markdown-it/markdown-it/blob/master/src/rules_core/replacements.ts) +
* quotes beautification (smartquotes).
* - __quotes__ - `“”‘’`, String or Array. Double + single quotes replacement
* pairs, when typographer enabled and smartquotes on. For example, you can
* use `'«»„“'` for Russian, `'„“‚‘'` for German, and
* - __quotes__ - `“”‘’`. Double + single quotes replacement pairs, when
* typographer enabled and smartquotes on. For example, you can use
* `'«»„“'` for Russian, `'„“‚‘'` for German, and
* `['«\xA0', '\xA0»', '‹\xA0', '\xA0›']` for French (including nbsp).
* - __highlight__ - `null`. Highlighter function for fenced code blocks.
* Highlighter `function (str, lang)` should return escaped HTML. It can also
* return empty string if the source was not changed and should be escaped
* externaly. If result starts with <pre... internal wrapper is skipped.
*
* ##### Example
* @example Basic usage
* ```javascript
* // node.js, "classic" way:
* var MarkdownIt = require('markdown-it'),
* md = new MarkdownIt();
* var result = md.render('# markdown-it rulezz!');
*
* // node.js, the same, but with sugar:
* var md = require('markdown-it')();
* var result = md.render('# markdown-it rulezz!');
*
* // browser without AMD, added to "window" on script load
* // Note, there are no dash.
* var md = window.markdownit();
* var result = md.render('# markdown-it rulezz!');
* ```
*
* @example Single line rendering, without paragraph wrap
* ```javascript
* var md = require('markdown-it')();
* var result = md.renderInline('__markdown-it__ rulezz!');
* ```
*
* @example Presets and options
* ```javascript
* // commonmark mode
* var md = require('markdown-it')('commonmark');
@ -200,8 +189,7 @@ function normalizeLinkText (url: string): string {
* });
* ```
*
* ##### Syntax highlighting
*
* @example Syntax highlighting
* ```js
* var hljs = require('highlight.js') // https://highlightjs.org/
*
@ -218,8 +206,8 @@ function normalizeLinkText (url: string): string {
* });
* ```
*
* Or with full wrapper override (if you need assign class to `<pre>` or `<code>`):
*
* @example Full wrapper override
* If you need assign class to `<pre>` or `<code>`:
* ```javascript
* var hljs = require('highlight.js') // https://highlightjs.org/
*
@ -236,44 +224,37 @@ function normalizeLinkText (url: string): string {
* }
* });
* ```
*
**/
*/
class MarkdownIt {
/**
* MarkdownIt#inline -> ParserInline
*
* Instance of [[ParserInline]]. You may need it to add new rules when
* writing plugins. For simple rules control use [[MarkdownIt.disable]] and
* [[MarkdownIt.enable]].
**/
* Instance of {@link ParserInline}. You may need it to add new rules when
* writing plugins. For simple rules control use {@link MarkdownIt.disable}
* and {@link MarkdownIt.enable}.
*/
inline = new ParserInline()
/**
* MarkdownIt#block -> ParserBlock
*
* Instance of [[ParserBlock]]. You may need it to add new rules when
* writing plugins. For simple rules control use [[MarkdownIt.disable]] and
* [[MarkdownIt.enable]].
**/
* Instance of {@link ParserBlock}. You may need it to add new rules when
* writing plugins. For simple rules control use {@link MarkdownIt.disable}
* and {@link MarkdownIt.enable}.
*/
block = new ParserBlock()
/**
* MarkdownIt#core -> ParserCore
*
* Instance of [[ParserCore]] chain executor. You may need it to add new rules when
* writing plugins. For simple rules control use [[MarkdownIt.disable]] and
* [[MarkdownIt.enable]].
**/
* Instance of {@link ParserCore} chain executor. You may need it to add new
* rules when writing plugins. For simple rules control use
* {@link MarkdownIt.disable} and {@link MarkdownIt.enable}.
*/
core = new ParserCore()
/**
* MarkdownIt#renderer -> Renderer
*
* Instance of [[Renderer]]. Use it to modify output look. Or to add rendering
* Instance of {@link Renderer}. Use it to modify output look. Or to add rendering
* rules for new token types, generated by plugins.
*
* ##### Example
* See {@link Renderer} docs and
* [source code](https://github.com/markdown-it/markdown-it/blob/master/src/renderer.ts).
*
* @example
* ```javascript
* var md = require('markdown-it')();
*
@ -284,68 +265,55 @@ class MarkdownIt {
*
* md.renderer.rules['my_token'] = myToken
* ```
*
* See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/src/renderer.ts).
**/
*/
renderer = new Renderer()
/**
* MarkdownIt#linkify -> LinkifyIt
*
* [linkify-it](https://github.com/markdown-it/linkify-it) instance.
* Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/src/rules_core/linkify.ts)
* rule.
**/
*/
linkify = new LinkifyIt()
/**
* MarkdownIt#validateLink(url) -> Boolean
*
* Link validation function. CommonMark allows too much in links. By default
* we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas
* except some embedded image types.
*
* You can change this behaviour:
*
* @example
* ```javascript
* var md = require('markdown-it')();
* // enable everything
* md.validateLink = function () { return true; }
* ```
**/
*/
validateLink = validateLink
/**
* MarkdownIt#normalizeLink(url) -> String
*
* Function used to encode link url to a machine-readable format,
* which includes url-encoding, punycode, etc.
**/
*/
normalizeLink = normalizeLink
/**
* MarkdownIt#normalizeLinkText(url) -> String
*
* Function used to decode link url to a human-readable format`
**/
*/
normalizeLinkText = normalizeLinkText
// Expose utils & helpers for easy acces from plugins
/**
* MarkdownIt#utils -> utils
*
* Assorted utility functions, useful to write plugins. See details
* [here](https://github.com/markdown-it/markdown-it/blob/master/src/common/utils.ts).
**/
*/
utils = utils
/**
* MarkdownIt#helpers -> helpers
*
* Link components parser functions, useful to write plugins. See details
* [here](https://github.com/markdown-it/markdown-it/blob/master/src/helpers).
**/
*/
helpers = Object.assign({}, helpers)
declare options: MarkdownItOptions
@ -367,40 +335,35 @@ class MarkdownIt {
}
}
/** chainable
* MarkdownIt.set(options)
*
* Set parser options (in the same format as in constructor). Probably, you
* will never need it, but you can change options after constructor call.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')()
* .set({ html: true, breaks: true })
* .set({ typographer: true });
* ```
*
* __Note:__ To achieve the best possible performance, don't modify a
* `markdown-it` instance options on the fly. If you need multiple configurations
* it's best to create multiple instances and initialize each with separate
* config.
**/
/**
* Set parser options (in the same format as in constructor). Probably, you
* will never need it, but you can change options after constructor call.
*
* __Note:__ To achieve the best possible performance, don't modify a
* `markdown-it` instance options on the fly. If you need multiple configurations
* it's best to create multiple instances and initialize each with separate
* config.
*
* @example
* ```javascript
* var md = require('markdown-it')()
* .set({ html: true, breaks: true })
* .set({ typographer: true });
* ```
*/
set (options: Partial<MarkdownItOptions>): this {
Object.assign(this.options, options)
return this
}
/** chainable, internal
* MarkdownIt.configure(presets)
*
* Batch load of all options and compenent settings. This is internal method,
* and you probably will not need it. But if you will - see available presets
* and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/src/presets)
*
* We strongly recommend to use presets instead of direct config loads. That
* will give better compatibility with next versions.
**/
/**
* Batch load of all options and compenent settings. This is internal method,
* and you probably will not need it. But if you will - see available presets
* and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/src/presets)
*
* We strongly recommend to use presets instead of direct config loads. That
* will give better compatibility with next versions.
*/
configure (presets: MarkdownItPresetName | MarkdownItPreset): this {
let p: MarkdownItPreset
@ -434,23 +397,21 @@ class MarkdownIt {
return this
}
/** chainable
* MarkdownIt.enable(list, ignoreInvalid)
* - list (String|Array): rule name or list of rule names to enable
* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
*
* Enable list or rules. It will automatically find appropriate components,
* containing rules with given names. If rule not found, and `ignoreInvalid`
* not set - throws exception.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')()
* .enable(['sub', 'sup'])
* .disable('smartquotes');
* ```
**/
/**
* Enable list or rules. It will automatically find appropriate components,
* containing rules with given names. If rule not found, and `ignoreInvalid`
* not set - throws exception.
*
* @param list Rule name or list of rule names to enable.
* @param ignoreInvalid Set `true` to ignore errors when rule not found.
*
* @example
* ```javascript
* var md = require('markdown-it')()
* .enable(['sub', 'sup'])
* .disable('smartquotes');
* ```
*/
enable (list: string | string[], ignoreInvalid = false): this {
let result: string[] = []
@ -472,13 +433,12 @@ class MarkdownIt {
return this
}
/** chainable
* MarkdownIt.disable(list, ignoreInvalid)
* - list (String|Array): rule name or list of rule names to disable.
* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
*
* The same as [[MarkdownIt.enable]], but turn specified rules off.
**/
/**
* The same as {@link MarkdownIt.enable}, but turn specified rules off.
*
* @param list Rule name or list of rule names to disable.
* @param ignoreInvalid Set `true` to ignore errors when rule not found.
*/
disable (list: string | string[], ignoreInvalid = false): this {
let result: string[] = []
@ -499,22 +459,19 @@ class MarkdownIt {
return this
}
/** chainable
* MarkdownIt.use(plugin, params)
*
* Load specified plugin with given params into current parser instance.
* It's just a sugar to call `plugin(md, params)` with curring.
*
* ##### Example
*
* ```javascript
* var iterator = require('markdown-it-for-inline');
* var md = require('markdown-it')()
* .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
* tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
* });
* ```
**/
/**
* Load specified plugin with given params into current parser instance.
* It's just a sugar to call `plugin(md, params)` with curring.
*
* @example
* ```javascript
* var iterator = require('markdown-it-for-inline');
* var md = require('markdown-it')()
* .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
* tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
* });
* ```
*/
use<Params extends unknown[]> (
plugin: (md: this, ...params: Params) => void,
...params: Params
@ -523,21 +480,20 @@ class MarkdownIt {
return this
}
/** internal
* MarkdownIt.parse(src, env) -> Array
* - src (String): source string
* - env (Object): environment sandbox
*
* Parse input string and return list of block tokens (special token type
* "inline" will contain list of inline tokens). You should not call this
* method directly, until you write custom renderer (for example, to produce
* AST).
*
* `env` is used to pass data between "distributed" rules and return additional
* metadata like reference info, needed for the renderer. It also can be used to
* inject data in specific cases. Usually, you will be ok to pass `{}`,
* and then pass updated object to renderer.
**/
/**
* Parse input string and return list of block tokens (special token type
* "inline" will contain list of inline tokens). You should not call this
* method directly, until you write custom renderer (for example, to produce
* AST).
*
* `env` is used to pass data between "distributed" rules and return additional
* metadata like reference info, needed for the renderer. It also can be used to
* inject data in specific cases. Usually, you will be ok to pass `{}`,
* and then pass updated object to renderer.
*
* @param src Source string.
* @param env Environment sandbox.
*/
parse (src: string, env: Env): Token[] {
if (typeof src !== 'string') {
throw new Error('Input data should be a String')
@ -551,29 +507,27 @@ class MarkdownIt {
}
/**
* MarkdownIt.render(src [, env]) -> String
* - src (String): source string
* - env (Object): environment sandbox
*
* Render markdown string into html. It does all magic for you :).
*
* `env` can be used to inject additional metadata (`{}` by default).
* But you will not need it with high probability. See also comment
* in [[MarkdownIt.parse]].
**/
* Render markdown string into html. It does all magic for you :).
*
* `env` can be used to inject additional metadata (`{}` by default).
* But you will not need it with high probability. See also comment
* in {@link MarkdownIt.parse}.
*
* @param src Source string.
* @param env Environment sandbox.
*/
render (src: string, env: Env = {}): string {
return this.renderer.render(this.parse(src, env), this.options, env)
}
/** internal
* MarkdownIt.parseInline(src, env) -> Array
* - src (String): source string
* - env (Object): environment sandbox
*
* The same as [[MarkdownIt.parse]] but skip all block rules. It returns the
* block tokens list with the single `inline` element, containing parsed inline
* tokens in `children` property. Also updates `env` object.
**/
/**
* The same as {@link MarkdownIt.parse} but skip all block rules. It returns
* the block tokens list with the single `inline` element, containing parsed
* inline tokens in `children` property. Also updates `env` object.
*
* @param src Source string.
* @param env Environment sandbox.
*/
parseInline (src: string, env: Env): Token[] {
const state = new this.core.State(src, this, env)
@ -584,13 +538,12 @@ class MarkdownIt {
}
/**
* MarkdownIt.renderInline(src [, env]) -> String
* - src (String): source string
* - env (Object): environment sandbox
*
* Similar to [[MarkdownIt.render]] but for single paragraph content. Result
* will NOT be wrapped into `<p>` tags.
**/
* Similar to {@link MarkdownIt.render} but for single paragraph content.
* Result will NOT be wrapped into `<p>` tags.
*
* @param src Source string.
* @param env Environment sandbox.
*/
renderInline (src: string, env: Env = {}): string {
return this.renderer.render(this.parseInline(src, env), this.options, env)
}

20
src/parser_block.ts

@ -1,9 +1,3 @@
/** internal
* class ParserBlock
*
* Block-level tokenizer.
**/
import Ruler from './ruler.ts'
import StateBlock from './rules_block/state_block.ts'
import type Token from './token.ts'
@ -43,14 +37,12 @@ const _rules: Array<[
]
/**
* new ParserBlock()
**/
* Block-level tokenizer.
*/
class ParserBlock {
/**
* ParserBlock#ruler -> Ruler
*
* [[Ruler]] instance. Keep configuration of block rules.
**/
* {@link Ruler} instance. Keep configuration of block rules.
*/
ruler = new Ruler<[StateBlock, number, number, boolean], boolean>()
State = StateBlock
@ -127,10 +119,8 @@ class ParserBlock {
}
/**
* ParserBlock.parse(str, md, env, outTokens)
*
* Process input string and push block tokens into `outTokens`
**/
*/
parse (src: string, md: MarkdownIt, env: Env, outTokens: Token[]): void {
if (!src) { return }

22
src/parser_core.ts

@ -1,10 +1,3 @@
/** internal
* class ParserCore
*
* Top-level rules executor. Glues block/inline parsers and does intermediate
* transformations.
**/
import Ruler from './ruler.ts'
import StateCore from './rules_core/state_core.ts'
@ -32,14 +25,13 @@ const _rules: Array<[
]
/**
* new ParserCore()
**/
* Top-level rules executor. Glues block/inline parsers and does intermediate
* transformations.
*/
class ParserCore {
/**
* ParserCore#ruler -> Ruler
*
* [[Ruler]] instance. Keep configuration of core rules.
**/
* {@link Ruler} instance. Keep configuration of core rules.
*/
ruler = new Ruler<[StateCore], void>()
State = StateCore
@ -51,10 +43,8 @@ class ParserCore {
}
/**
* ParserCore.process(state)
*
* Executes core chain rules.
**/
*/
process (state: StateCore): void {
const rules = this.ruler.getRules('')

26
src/parser_inline.ts

@ -1,9 +1,3 @@
/** internal
* class ParserInline
*
* Tokenizes paragraph content.
**/
import Ruler from './ruler.ts'
import StateInline from './rules_inline/state_inline.ts'
import type Token from './token.ts'
@ -64,22 +58,18 @@ const _rules2: Array<[
]
/**
* new ParserInline()
**/
* Tokenizes paragraph content.
*/
class ParserInline {
/**
* ParserInline#ruler -> Ruler
*
* [[Ruler]] instance. Keep configuration of inline rules.
**/
* {@link Ruler} instance. Keep configuration of inline rules.
*/
ruler = new Ruler<[StateInline, boolean], boolean>()
/**
* ParserInline#ruler2 -> Ruler
*
* [[Ruler]] instance. Second ruler used for post-processing
* {@link Ruler} instance. Second ruler used for post-processing
* (e.g. in emphasis-like rules).
**/
*/
ruler2 = new Ruler<[StateInline], void>()
State = StateInline
@ -187,10 +177,8 @@ class ParserInline {
}
/**
* ParserInline.parse(str, md, env, outTokens)
*
* Process input string and push inline tokens into `outTokens`
**/
*/
parse (str: string, md: MarkdownIt, env: Env, outTokens: Token[]): void {
const state = new this.State(str, md, env, outTokens)

98
src/renderer.ts

@ -1,11 +1,3 @@
/**
* class Renderer
*
* Generates HTML from parsed token stream. Each instance has independent
* copy of rules. Those can be rewritten with ease. Also, you can add new
* rules if you create plugin and adds new token types.
**/
import { unescapeAll, escapeHtml } from './common/utils.ts'
import type Token from './token.ts'
import type { Env, MarkdownItOptions } from './types.ts'
@ -145,18 +137,20 @@ default_rules.html_inline = function (tokens: Token[], idx: number): string {
}
/**
* new Renderer()
* Generates HTML from parsed token stream. Each instance has independent
* copy of rules. Those can be rewritten with ease. Also, you can add new
* rules if you create plugin and adds new token types.
*
* Creates new [[Renderer]] instance and fill [[Renderer#rules]] with defaults.
**/
* Creates new renderer instance and fills {@link Renderer.rules} with defaults.
*/
class Renderer {
/**
* Renderer#rules -> Object
*
* Contains render rules for tokens. Can be updated and extended.
*
* ##### Example
* See [source code](https://github.com/markdown-it/markdown-it/blob/master/src/renderer.ts)
* for more details and examples.
*
* @example Custom render rules
* ```javascript
* var md = require('markdown-it')();
*
@ -166,25 +160,19 @@ class Renderer {
* var result = md.renderInline(...);
* ```
*
* Each rule is called as independent static function with fixed signature:
*
* @example Each rule is called as independent static function with fixed signature
* ```javascript
* function my_token_render(tokens, idx, options, env, renderer) {
* // ...
* return renderedHTML;
* }
* ```
*
* See [source code](https://github.com/markdown-it/markdown-it/blob/master/src/renderer.ts)
* for more details and examples.
**/
*/
rules: Record<string, RendererRule> = Object.assign({}, default_rules)
/**
* Renderer.renderAttrs(token) -> String
*
* Render token attributes to string.
**/
* Render token attributes to string.
*/
renderAttrs (token: Pick<Token, 'attrs'>): string {
let i, l, result
@ -200,14 +188,13 @@ class Renderer {
}
/**
* Renderer.renderToken(tokens, idx, options) -> String
* - tokens (Array): list of tokens
* - idx (Numbed): token index to render
* - options (Object): params of parser instance
*
* Default token renderer. Can be overriden by custom function
* in [[Renderer#rules]].
**/
* Default token renderer. Can be overriden by custom function
* in {@link Renderer.rules}.
*
* @param tokens List of tokens.
* @param idx Token index to render.
* @param options Params of parser instance.
*/
renderToken (tokens: Token[], idx: number, options: MarkdownItOptions): string {
const token = tokens[idx]
let result = ''
@ -267,13 +254,12 @@ class Renderer {
}
/**
* Renderer.renderInline(tokens, options, env) -> String
* - tokens (Array): list on block tokens to render
* - options (Object): params of parser instance
* - env (Object): additional data from parsed input (references, for example)
*
* The same as [[Renderer.render]], but for single token of `inline` type.
**/
* The same as {@link Renderer.render}, but for single token of `inline` type.
*
* @param tokens List on block tokens to render.
* @param options Params of parser instance.
* @param env Additional data from parsed input (references, for example).
*/
renderInline (tokens: Token[], options: MarkdownItOptions, env: Env | undefined): string {
let result = ''
const rules = this.rules
@ -291,16 +277,15 @@ class Renderer {
return result
}
/** internal
* Renderer.renderInlineAsText(tokens, options, env) -> String
* - tokens (Array): list on block tokens to render
* - options (Object): params of parser instance
* - env (Object): additional data from parsed input (references, for example)
*
* Special kludge for image `alt` attributes to conform CommonMark spec.
* Don't try to use it! Spec requires to show `alt` content with stripped markup,
* instead of simple escaping.
**/
/**
* Special kludge for image `alt` attributes to conform CommonMark spec.
* Don't try to use it! Spec requires to show `alt` content with stripped markup,
* instead of simple escaping.
*
* @param tokens List on block tokens to render.
* @param options Params of parser instance.
* @param env Additional data from parsed input (references, for example).
*/
renderInlineAsText (tokens: Token[], options: MarkdownItOptions, env: Env | undefined): string {
let result = ''
@ -329,14 +314,13 @@ class Renderer {
}
/**
* Renderer.render(tokens, options, env) -> String
* - tokens (Array): list on block tokens to render
* - options (Object): params of parser instance
* - env (Object): additional data from parsed input (references, for example)
*
* Takes token stream and generates HTML. Probably, you will never need to call
* this method directly.
**/
* Takes token stream and generates HTML. Probably, you will never need to call
* this method directly.
*
* @param tokens List on block tokens to render.
* @param options Params of parser instance.
* @param env Additional data from parsed input (references, for example).
*/
render (tokens: Token[], options: MarkdownItOptions, env?: Env): string {
let result = ''
const rules = this.rules

253
src/ruler.ts

@ -1,8 +1,8 @@
type RuleOptions = { alt?: string[] }
/**
* class Ruler
*
* Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
* [[MarkdownIt#inline]] to manage sequences of functions (rules):
* Helper class, used by {@link MarkdownIt.core}, {@link MarkdownIt.block} and
* {@link MarkdownIt.inline} to manage sequences of functions (rules):
*
* - keep rules in defined order
* - assign the name to each rule
@ -12,15 +12,9 @@
* - cacheing lists of active rules
*
* You will not need use this class directly until write plugins. For simple
* rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
* [[MarkdownIt.use]].
**/
/**
* new Ruler()
**/
type RuleOptions = { alt?: string[] }
* rules control use {@link MarkdownIt.disable}, {@link MarkdownIt.enable} and
* {@link MarkdownIt.use}.
*/
class Ruler<Args extends unknown[], Result> {
// List of added rules. Each element is:
//
@ -92,30 +86,23 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.at(name, fn [, options])
* - name (String): rule name to replace.
* - fn (Function): new rule function.
* - options (Object): new rule options (not mandatory).
*
* Replace rule by name with new function & options. Throws error if name not
* found.
*
* ##### Options:
*
* - __alt__ - array with names of "alternate" chains.
*
* ##### Example
*
* Replace existing typographer replacement rule with new one:
*
* ```javascript
* var md = require('markdown-it')();
*
* md.core.ruler.at('replacements', function replace(state) {
* //...
* });
* ```
**/
* Replace rule by name with new function & options. Throws error if name not
* found.
*
* @param name Rule name to replace.
* @param fn New rule function.
* @param options Rule options. `alt` is an array with names of "alternate"
* chains.
*
* @example Replace existing typographer replacement rule with new one
* ```javascript
* var md = require('markdown-it')();
*
* md.core.ruler.at('replacements', function replace(state) {
* //...
* });
* ```
*/
at (name: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(name)
@ -127,29 +114,24 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.before(beforeName, ruleName, fn [, options])
* - beforeName (String): new rule will be added before this one.
* - ruleName (String): name of added rule.
* - fn (Function): rule function.
* - options (Object): rule options (not mandatory).
*
* Add new rule to chain before one with given name. See also
* [[Ruler.after]], [[Ruler.push]].
*
* ##### Options:
*
* - __alt__ - array with names of "alternate" chains.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')();
*
* md.block.ruler.before('paragraph', 'my_rule', function replace(state) {
* //...
* });
* ```
**/
* Add new rule to chain before one with given name. See also
* {@link Ruler.after}, {@link Ruler.push}.
*
* @param beforeName New rule will be added before this one.
* @param ruleName Name of added rule.
* @param fn Rule function.
* @param options Rule options. `alt` is an array with names of "alternate"
* chains.
*
* @example
* ```javascript
* var md = require('markdown-it')();
*
* md.block.ruler.before('paragraph', 'my_rule', function replace(state) {
* //...
* });
* ```
*/
before (beforeName: string, ruleName: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(beforeName)
@ -166,29 +148,24 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.after(afterName, ruleName, fn [, options])
* - afterName (String): new rule will be added after this one.
* - ruleName (String): name of added rule.
* - fn (Function): rule function.
* - options (Object): rule options (not mandatory).
*
* Add new rule to chain after one with given name. See also
* [[Ruler.before]], [[Ruler.push]].
*
* ##### Options:
*
* - __alt__ - array with names of "alternate" chains.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')();
*
* md.inline.ruler.after('text', 'my_rule', function replace(state) {
* //...
* });
* ```
**/
* Add new rule to chain after one with given name. See also
* {@link Ruler.before}, {@link Ruler.push}.
*
* @param afterName New rule will be added after this one.
* @param ruleName Name of added rule.
* @param fn Rule function.
* @param options Rule options. `alt` is an array with names of "alternate"
* chains.
*
* @example
* ```javascript
* var md = require('markdown-it')();
*
* md.inline.ruler.after('text', 'my_rule', function replace(state) {
* //...
* });
* ```
*/
after (afterName: string, ruleName: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
const index = this.__find__(afterName)
@ -205,28 +182,23 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.push(ruleName, fn [, options])
* - ruleName (String): name of added rule.
* - fn (Function): rule function.
* - options (Object): rule options (not mandatory).
*
* Push new rule to the end of chain. See also
* [[Ruler.before]], [[Ruler.after]].
*
* ##### Options:
*
* - __alt__ - array with names of "alternate" chains.
*
* ##### Example
*
* ```javascript
* var md = require('markdown-it')();
*
* md.core.ruler.push('my_rule', function replace(state) {
* //...
* });
* ```
**/
* Push new rule to the end of chain. See also
* {@link Ruler.before}, {@link Ruler.after}.
*
* @param ruleName Name of added rule.
* @param fn Rule function.
* @param options Rule options. `alt` is an array with names of "alternate"
* chains.
*
* @example
* ```javascript
* var md = require('markdown-it')();
*
* md.core.ruler.push('my_rule', function replace(state) {
* //...
* });
* ```
*/
push (ruleName: string, fn: (...args: Args) => Result, options: RuleOptions = {}): void {
this.__rules__.push({
name: ruleName,
@ -239,17 +211,15 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.enable(list [, ignoreInvalid]) -> Array
* - list (String|Array): list of rule names to enable.
* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
*
* Enable rules with given names. If any rule name not found - throw Error.
* Errors can be disabled by second param.
*
* Returns list of found rule names (if no exception happened).
*
* See also [[Ruler.disable]], [[Ruler.enableOnly]].
**/
* Enable rules with given names. If any rule name not found - throw Error.
* Errors can be disabled by second param.
*
* See also {@link Ruler.disable}, {@link Ruler.enableOnly}.
*
* @param list List of rule names to enable.
* @param ignoreInvalid Set `true` to ignore errors when rule not found.
* @returns List of found rule names (if no exception happened).
*/
enable (list: string | string[], ignoreInvalid = false): string[] {
if (!Array.isArray(list)) { list = [list] }
@ -272,15 +242,14 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.enableOnly(list [, ignoreInvalid])
* - list (String|Array): list of rule names to enable (whitelist).
* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
*
* Enable rules with given names, and disable everything else. If any rule name
* not found - throw Error. Errors can be disabled by second param.
*
* See also [[Ruler.disable]], [[Ruler.enable]].
**/
* Enable rules with given names, and disable everything else. If any rule name
* not found - throw Error. Errors can be disabled by second param.
*
* See also {@link Ruler.disable}, {@link Ruler.enable}.
*
* @param list List of rule names to enable (whitelist).
* @param ignoreInvalid Set `true` to ignore errors when rule not found.
*/
enableOnly (list: string | string[], ignoreInvalid = false): void {
if (!Array.isArray(list)) { list = [list] }
@ -290,17 +259,15 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.disable(list [, ignoreInvalid]) -> Array
* - list (String|Array): list of rule names to disable.
* - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.
*
* Disable rules with given names. If any rule name not found - throw Error.
* Errors can be disabled by second param.
*
* Returns list of found rule names (if no exception happened).
*
* See also [[Ruler.enable]], [[Ruler.enableOnly]].
**/
* Disable rules with given names. If any rule name not found - throw Error.
* Errors can be disabled by second param.
*
* See also {@link Ruler.enable}, {@link Ruler.enableOnly}.
*
* @param list List of rule names to disable.
* @param ignoreInvalid Set `true` to ignore errors when rule not found.
* @returns List of found rule names (if no exception happened).
*/
disable (list: string | string[], ignoreInvalid = false): string[] {
if (!Array.isArray(list)) { list = [list] }
@ -323,14 +290,12 @@ class Ruler<Args extends unknown[], Result> {
}
/**
* Ruler.getRules(chainName) -> Array
*
* Return array of active functions (rules) for given chain name. It analyzes
* rules configuration, compiles caches if not exists and returns result.
*
* Default chain name is `''` (empty string). It can't be skipped. That's
* done intentionally, to keep signature monomorphic for high speed.
**/
* Return array of active functions (rules) for given chain name. It analyzes
* rules configuration, compiles caches if not exists and returns result.
*
* Default chain name is `''` (empty string). It can't be skipped. That's
* done intentionally, to keep signature monomorphic for high speed.
*/
getRules (chainName: string): Array<(...args: Args) => Result> {
if (!this.__cache__) this.__compile__()

98
src/token.ts

@ -1,136 +1,96 @@
// Token class
/**
* class Token
**/
/**
* new Token(type, tag, nesting)
*
* Create new token and fill passed properties.
**/
type TokenNesting = -1 | 0 | 1
type TokenAttribute = [name: string, value: string | number]
/** Create new token and fill passed properties. */
class Token {
/**
* Token#type -> String
*
* Type of the token (string, e.g. "paragraph_open")
**/
*/
declare type: string
/**
* Token#tag -> String
*
* html tag name, e.g. "p"
**/
*/
declare tag: string
/** Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` */
declare attrs: TokenAttribute[] | null
/**
* Token#map -> Array
*
* Source map info. Format: `[ line_begin, line_end ]`
**/
*/
map: [number, number] | null = null
/**
* Token#nesting -> Number
*
* Level change (number in {-1, 0, 1} set), where:
*
* - `1` means the tag is opening
* - `0` means the tag is self-closing
* - `-1` means the tag is closing
**/
*/
declare nesting: TokenNesting
/**
* Token#level -> Number
*
* nesting level, the same as `state.level`
**/
*/
level = 0
/**
* Token#children -> Array
*
* An array of child nodes (inline and img tokens)
**/
*/
children: Token[] | null = null
/**
* Token#content -> String
*
* In a case of self-closing tag (code, html, fence, etc.),
* it has contents of this tag.
**/
*/
content = ''
/**
* Token#markup -> String
*
* '*' or '_' for emphasis, fence string for fence, etc.
**/
*/
markup = ''
/**
* Token#info -> String
*
* Additional information:
*
* - Info string for "fence" tokens
* - The value "auto" for autolink "link_open" and "link_close" tokens
* - The string value of the item marker for ordered-list "list_item_open" tokens
**/
*/
info = ''
/** A place for plugins to store an arbitrary data */
declare meta: Record<string, unknown> | null
/**
* Token#block -> Boolean
*
* True for block-level tokens, false for inline tokens.
* Used in renderer to calculate line breaks
**/
*/
block = false
/**
* Token#hidden -> Boolean
*
* If it's true, ignore this element when rendering. Used for tight lists
* to hide paragraphs.
**/
*/
hidden = false
constructor (type: string, tag: string, nesting: TokenNesting) {
this.type = type
this.tag = tag
/**
* Token#attrs -> Array
*
* Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]`
**/
this.attrs = null
this.nesting = nesting
/**
* Token#meta -> Object
*
* A place for plugins to store an arbitrary data
**/
this.meta = null
}
/**
* Token.attrIndex(name) -> Number
*
* Search attribute index by name.
**/
* Search attribute index by name.
*/
attrIndex (name: string): number {
if (!this.attrs) { return -1 }
@ -143,10 +103,8 @@ class Token {
}
/**
* Token.attrPush(attrData)
*
* Add `[ name, value ]` attribute to list. Init attrs if necessary
**/
* Add `[ name, value ]` attribute to list. Init attrs if necessary
*/
attrPush (attrData: TokenAttribute): void {
if (this.attrs) {
this.attrs.push(attrData)
@ -156,10 +114,8 @@ class Token {
}
/**
* Token.attrSet(name, value)
*
* Set `name` attribute to `value`. Override old value if exists.
**/
* Set `name` attribute to `value`. Override old value if exists.
*/
attrSet (name: string, value: string | number): void {
const idx = this.attrIndex(name)
const attrData: TokenAttribute = [name, value]
@ -172,10 +128,8 @@ class Token {
}
/**
* Token.attrGet(name)
*
* Get the value of attribute `name`, or null if it does not exist.
**/
* Get the value of attribute `name`, or null if it does not exist.
*/
attrGet (name: string): string | number | null {
const idx = this.attrIndex(name)
let value = null
@ -186,11 +140,9 @@ class Token {
}
/**
* Token.attrJoin(name, value)
*
* Join value to existing attribute via space. Or create new attribute if not
* exists. Useful to operate with token classes.
**/
* Join value to existing attribute via space. Or create new attribute if not
* exists. Useful to operate with token classes.
*/
attrJoin (name: string, value: string | number): void {
const idx = this.attrIndex(name)

Loading…
Cancel
Save