react-smart-copy 1.18.0 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -2
- package/dist/chunks/inert-html-D75NyVvT.js +34 -0
- package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
- package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
- package/dist/chunks/url-B9jdFGQy.cjs +86 -0
- package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
- package/dist/chunks/url-vJaFPbNL.js +57 -0
- package/dist/chunks/url-vJaFPbNL.js.map +1 -0
- package/dist/code.cjs +2 -1
- package/dist/code.cjs.map +1 -1
- package/dist/code.js +2 -1
- package/dist/code.js.map +1 -1
- package/dist/link.cjs +2 -1
- package/dist/link.cjs.map +1 -1
- package/dist/link.js +2 -1
- package/dist/link.js.map +1 -1
- package/dist/markdown.cjs +11 -62
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.js +3 -54
- package/dist/markdown.js.map +1 -1
- package/dist/rich.cjs +1097 -6
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +97 -1
- package/dist/rich.d.ts +97 -1
- package/dist/rich.js +1095 -7
- package/dist/rich.js.map +1 -1
- package/dist/table.cjs +2 -1
- package/dist/table.cjs.map +1 -1
- package/dist/table.js +2 -1
- package/dist/table.js.map +1 -1
- package/package.json +18 -4
package/dist/link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.js","names":[],"sources":["../src/link/fragment.ts","../src/link/paste.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/**\n * A passage to link to: `start` alone, or `start` to `end` for a longer one.\n * `prefix` and `suffix` are the words around it, used to tell apart passages\n * that appear more than once. Each term must lie within one block of the page\n * (a paragraph, a list item, a heading).\n */\nexport interface TextFragment {\n readonly start: string;\n readonly end?: string;\n readonly prefix?: string;\n readonly suffix?: string;\n}\n\nexport interface TextFragmentOptions extends LinkUrlOptions {\n /** Passages longer than this many words link by their first and last words (`start,end`). Default 10. */\n readonly maxWords?: number;\n /** Words kept at each end of a long passage, and of prefix and suffix context. Default 4. */\n readonly contextWords?: number;\n /** Where to look for repeats of the passage, to decide whether context is needed. Default `document.body`. */\n readonly root?: Node;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst collapse = (text: string): string => text.replace(/\\s+/g, ' ').trim();\nconst words = (text: string): string[] => collapse(text).split(' ').filter((word) => word !== '');\n\n/**\n * Percent-encodes a directive term. `encodeURIComponent` leaves `-` alone, but the\n * directive syntax uses it (`prefix-,` and `,-suffix`), so it is encoded too.\n */\nexport function encodeTerm(term: string): string {\n return encodeURIComponent(term).replace(/-/g, '%2D');\n}\n\n/** The `text=` directive for a fragment. */\nexport function textDirective(fragment: TextFragment): string {\n const terms: string[] = [];\n if (fragment.prefix !== undefined && fragment.prefix !== '') terms.push(`${encodeTerm(fragment.prefix)}-`);\n terms.push(encodeTerm(fragment.start));\n if (fragment.end !== undefined && fragment.end !== '') terms.push(encodeTerm(fragment.end));\n if (fragment.suffix !== undefined && fragment.suffix !== '') terms.push(`-${encodeTerm(fragment.suffix)}`);\n return `text=${terms.join(',')}`;\n}\n\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`${name}\\` must be a positive integer (received ${String(value)}).`);\n}\n\n/** Elements that start a new block: text fragment terms never span them. */\nconst BLOCK = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'blockquote', 'body', 'caption', 'dd', 'details', 'dialog', 'div', 'dl', 'dt', 'fieldset',\n 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'main', 'nav',\n 'ol', 'p', 'pre', 'section', 'summary', 'table', 'td', 'th', 'tr', 'ul',\n]);\n\n/** The nearest block around `node`, or the top of its tree (a detached node's fragment, or the page body). */\nfunction blockOf(node: Node): Node {\n let top = node;\n for (let current: Node | null = node; current !== null; current = current.parentNode) {\n if (current.nodeType === 1 && BLOCK.has((current as Element).localName)) return current;\n top = current;\n }\n if (top.nodeType !== 9) return top;\n const body: unknown = (top as Document).body; // Null in an XML document, despite its type.\n return body instanceof Node ? body : top;\n}\n\n/** The text of `block` from its start to (`before`) or from (`after`) a boundary point. */\nfunction around(block: Node, container: Node, offset: number, side: 'before' | 'after'): string {\n const range = (container.ownerDocument as Document).createRange();\n range.selectNodeContents(block);\n if (side === 'before') range.setEnd(container, offset);\n else range.setStart(container, offset);\n return range.toString();\n}\n\nconst count = (haystack: string, needle: string): number => {\n let found = 0;\n for (let at = haystack.indexOf(needle); at !== -1 && found < 2; at = haystack.indexOf(needle, at + 1)) found += 1;\n return found;\n};\n\nfunction rootText(root: Node | undefined): string | null {\n const node = root ?? (typeof document === 'undefined' ? undefined : document.body);\n if (node === undefined) return null;\n // A range reads the text of any node, a whole Document included (whose `textContent` is null).\n const range = ((node.ownerDocument ?? node) as Document).createRange();\n range.selectNodeContents(node);\n return collapse(range.toString()).toLowerCase();\n}\n\n/** Splits a passage into a directive: whole when short, first and last words when long. */\nfunction fromText(text: string, maxWords: number, contextWords: number): TextFragment {\n const all = words(text);\n if (all.length === 0) throw invalid('A text fragment needs some text.');\n if (all.length <= maxWords) return { start: all.join(' ') };\n return { start: all.slice(0, contextWords).join(' '), end: all.slice(-contextWords).join(' ') };\n}\n\n/** A fragment for a selected range: terms taken from within their own blocks, context added when the passage repeats. */\nfunction fromRange(range: Range, maxWords: number, contextWords: number, root: Node | undefined): TextFragment {\n const startBlock = blockOf(range.startContainer);\n const endBlock = blockOf(range.endContainer);\n const text = collapse(range.toString());\n if (text === '') throw invalid('A text fragment needs some text: the range is empty.');\n let fragment: TextFragment;\n if (startBlock === endBlock) {\n fragment = fromText(text, maxWords, contextWords);\n } else {\n // A passage across blocks: start in the first block, end in the last.\n const head = words(around(startBlock, range.startContainer, range.startOffset, 'after')).slice(0, contextWords);\n const tail = words(around(endBlock, range.endContainer, range.endOffset, 'before')).slice(-contextWords);\n fragment = head.length === 0 || tail.length === 0 ? fromText(text, maxWords, contextWords) : { start: head.join(' '), end: tail.join(' ') };\n }\n const page = rootText(root);\n if (page !== null && count(page, fragment.start.toLowerCase()) < 2) return fragment;\n // The start appears more than once (or the page can't be read): add the words around the passage.\n const prefix = words(around(startBlock, range.startContainer, range.startOffset, 'before')).slice(-contextWords).join(' ');\n const suffix = words(around(endBlock, range.endContainer, range.endOffset, 'after')).slice(0, contextWords).join(' ');\n return { ...fragment, prefix, suffix }; // Empty terms are left out of the directive.\n}\n\n/** A caller's fragment with each term on one line; empty optional terms are left out of the directive. */\nfunction fromObject(passage: TextFragment): TextFragment {\n const term = (value: unknown): string => (typeof value === 'string' ? collapse(value) : '');\n const start = term(passage.start);\n if (start === '') throw invalid('A text fragment needs a non-empty `start`.');\n return { start, end: term(passage.end), prefix: term(passage.prefix), suffix: term(passage.suffix) };\n}\n\nfunction isRange(value: unknown): value is Range {\n return typeof value === 'object' && value !== null && typeof (value as Range).cloneContents === 'function' && 'startContainer' in value;\n}\n\n/**\n * A link that scrolls to, and highlights, a passage of the page: the\n * [text fragment](https://wicg.github.io/scroll-to-text-fragment/) syntax\n * (`#:~:text=`), supported by Chromium, Safari and Firefox. Browsers without it\n * open the page at its normal position (or its existing `#section`).\n *\n * The passage is a string, a {@link TextFragment}, or a DOM `Range` (the user's\n * selection): long passages link by their first and last words, and the words\n * around a passage are added when it appears more than once on the page.\n *\n * @example\n * textFragmentUrl(location.href, window.getSelection()!.getRangeAt(0));\n * textFragmentUrl('https://example.com/docs#install', 'npm install react-smart-copy');\n */\nexport function textFragmentUrl(url: string | URL, passage: string | TextFragment | Range, options: TextFragmentOptions = {}): string {\n const maxWords = positive(options.maxWords, 10, 'maxWords');\n const contextWords = positive(options.contextWords, 4, 'contextWords');\n let fragment: TextFragment;\n if (typeof passage === 'string') {\n fragment = fromText(passage, maxWords, contextWords);\n } else if (isRange(passage)) {\n fragment = fromRange(passage, maxWords, contextWords, options.root);\n } else if (typeof passage === 'object' && (passage as unknown) !== null && typeof (passage as { start?: unknown }).start === 'string') {\n fragment = fromObject(passage);\n } else {\n throw invalid('The passage must be a string, a TextFragment or a Range.');\n }\n const href = resolveLinkUrl(url, options);\n const hashAt = href.indexOf('#');\n const base = hashAt === -1 ? href : href.slice(0, hashAt);\n // Keep an existing #section; replace any earlier directive.\n const section = hashAt === -1 ? '' : (href.slice(hashAt + 1).split(':~:')[0] as string);\n return `${base}#${section}:~:${textDirective(fragment)}`;\n}\n\n/** Whether this browser scrolls to text fragments (`document.fragmentDirective`). */\nexport function supportsTextFragments(): boolean {\n return typeof document !== 'undefined' && 'fragmentDirective' in document;\n}\n","import { copyFailure } from '../core/errors';\nimport { asTextField, insertText } from '../core/text-field';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, markdownLink, type ResolvedLink } from './payload';\nimport { textFragmentUrl, type TextFragmentOptions } from './fragment';\nimport { linkUrlResolver, type LinkUrlOptions } from './url';\n\n/** What was pasted or dropped: a `PasteResult` from `usePaste`, a `DataTransfer`-like source, or the flavours themselves. */\nexport interface LinkPasteSource {\n readonly text?: string | null;\n readonly html?: string | null;\n /** `text/uri-list`. */\n readonly uriList?: string | null;\n /** A `PasteResult`'s entries: a `text/uri-list` entry is read from here. */\n readonly items?: readonly { readonly type: string; readonly data: string | Blob }[];\n}\n\n/** One URL with no spaces, as a whole pasted text (surrounding whitespace allowed). */\nconst SINGLE_URL = /^\\s*<?([a-z][a-z\\d+.-]*:[^\\s<>]+?)>?\\s*$/i;\n\ntype Resolve = (input: string) => string;\n\n/** The URL, or `null` when the clipboard content is not a valid, allowed link. */\nfunction tryUrl(resolve: Resolve, candidate: string): string | null {\n try {\n return resolve(candidate);\n } catch {\n return null;\n }\n}\n\nfunction fromUriList(list: string, resolve: Resolve): string | null {\n // RFC 2483: one URI per line, lines starting with \"#\" are comments.\n const first = list.split(/\\r?\\n/).find((line) => line.trim() !== '' && !line.startsWith('#'));\n return first === undefined ? null : tryUrl(resolve, first.trim());\n}\n\n/** The single link in pasted HTML (one `<a href>` and nothing else visible besides its text), parsed inertly. */\nfunction fromHtml(html: string, resolve: Resolve): ResolvedLink | null {\n if (typeof DOMParser === 'undefined' || html.trim() === '') return null;\n const body = new DOMParser().parseFromString(html.slice(0, 100_000), 'text/html').body;\n const anchors = body.querySelectorAll('a[href]');\n if (anchors.length !== 1) return null;\n const anchor = anchors[0] as HTMLAnchorElement;\n const visible = body.textContent.replace(/\\s+/g, ' ').trim();\n const label = anchor.textContent.replace(/\\s+/g, ' ').trim();\n if (visible !== label) return null; // A link inside more text is not \"a link\".\n const url = tryUrl(resolve, String(anchor.getAttribute('href'))); // Matched by `a[href]`.\n if (url === null) return null;\n const title = cleanTitle(label, DEFAULT_LINK_TITLE_LENGTH);\n return { url, title: title === '' ? url : title, titled: title !== '' && title !== url };\n}\n\n/**\n * The link the clipboard (or a drop) holds, or `null`: from `text/uri-list`,\n * from HTML that is exactly one link (keeping its title), or from text that is\n * exactly one URL. Every URL is validated: allowed schemes only (never\n * `javascript:`), credentials removed. Never throws for clipboard content.\n *\n * @example\n * usePaste({ accept: ['text', 'html', 'text/uri-list'], onPaste: (result) => {\n * const link = readLink(result);\n * if (link) addBookmark(link.url, link.title);\n * } });\n */\nexport function readLink(source: LinkPasteSource, options: LinkUrlOptions = {}): ResolvedLink | null {\n return readWith(source, linkUrlResolver(options));\n}\n\nfunction readWith(source: LinkPasteSource, resolve: Resolve): ResolvedLink | null {\n const uriList = source.uriList ?? source.items?.find((item) => item.type === 'text/uri-list' && typeof item.data === 'string')?.data;\n if (typeof uriList === 'string') {\n const url = fromUriList(uriList, resolve);\n if (url !== null) {\n const fromMarkup = typeof source.html === 'string' ? fromHtml(source.html, resolve) : null;\n return fromMarkup?.url === url ? fromMarkup : { url, title: url, titled: false };\n }\n }\n if (typeof source.html === 'string') {\n const link = fromHtml(source.html, resolve);\n if (link !== null) return link;\n }\n const match = typeof source.text === 'string' ? SINGLE_URL.exec(source.text) : null;\n const url = match === null ? null : tryUrl(resolve, match[1] as string);\n return url === null ? null : { url, title: url, titled: false };\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface LinkPasteEvent {\n readonly clipboardData: { getData(format: string): string } | null;\n readonly currentTarget: EventTarget | null;\n readonly target: EventTarget | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\nexport interface PasteAsLinkOptions extends LinkUrlOptions {\n /**\n * What replaces the selection. Default: a Markdown link, `[selection](url)`.\n * Receives the selected text and the pasted link.\n */\n readonly format?: (selection: string, link: ResolvedLink) => string;\n}\n\n/**\n * A paste handler for text fields: pasting a link over selected text turns the\n * selection into a link (`[selected text](url)` by default), as GitHub, Slack\n * and Notion do. Everything else is left to the browser: pasting with nothing\n * selected, pasting over a URL, or pasting something that is not one link. The\n * browser's undo still works. Returns whether it handled the paste.\n *\n * @example\n * <textarea onPaste={pasteAsLink} />\n */\nexport function pasteAsLink(event: LinkPasteEvent, options: PasteAsLinkOptions = {}): boolean {\n const { format, ...urlOptions } = options;\n // Invalid options are a programming error: thrown before the paste is touched, so the native paste still happens.\n const resolve = linkUrlResolver(urlOptions);\n if (event.defaultPrevented || event.clipboardData === null) return false;\n const field = asTextField(event.currentTarget) ?? asTextField(event.target);\n if (field === null || field.disabled || field.readOnly || field.selectionStart === null || field.selectionEnd === null) return false;\n const selection = field.value.slice(field.selectionStart, field.selectionEnd);\n if (selection.trim() === '' || SINGLE_URL.test(selection)) return false;\n const data = event.clipboardData;\n const link = readWith({ text: data.getData('text/plain'), html: data.getData('text/html'), uriList: data.getData('text/uri-list') }, resolve);\n if (link === null) return false;\n const text = format === undefined ? markdownLink({ ...link, title: selection, titled: true }) : format(selection, link);\n if (typeof text !== 'string') throw copyFailure('invalid-payload', '`format` must return a string.');\n event.preventDefault();\n return insertText(field, text);\n}\n\n/** A link to the current selection, as returned by {@link selectionLink}. */\nexport interface SelectionLink extends ResolvedLink {\n /** The selected text, as one line. */\n readonly quote: string;\n}\n\nexport interface SelectionLinkOptions extends TextFragmentOptions {\n /** The page to link to. Default: `location.href`. */\n readonly url?: string | URL;\n /** Default: `document.title`. */\n readonly title?: string;\n}\n\n/**\n * A link to the passage the user has selected (a text fragment link), with the\n * page title and the quote, or `null` when nothing is selected. Pass it to\n * `linkPayload` to copy it.\n *\n * @example\n * const link = selectionLink();\n * if (link) copy(() => linkPayload(link));\n */\nexport function selectionLink(options: SelectionLinkOptions = {}): SelectionLink | null {\n if (typeof window === 'undefined' || typeof document === 'undefined') return null;\n const selection = window.getSelection();\n if (selection === null || selection.rangeCount === 0 || selection.isCollapsed) return null;\n const range = selection.getRangeAt(0);\n const quote = range.toString().replace(/\\s+/g, ' ').trim();\n if (quote === '') return null;\n const { url = location.href, title = document.title, ...fragmentOptions } = options;\n const href = textFragmentUrl(url, range, fragmentOptions);\n const clean = cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '', quote };\n}\n"],"mappings":";;;;;;AAyBA,MAAM,WAAW,YAAoB,YAAY,mBAAmB,OAAO;AAE3E,MAAM,YAAY,SAAyB,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;AAC1E,MAAM,SAAS,SAA2B,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,SAAS,EAAE;;;;;AAMhG,SAAgB,WAAW,MAAsB;CAC/C,OAAO,mBAAmB,IAAI,CAAC,CAAC,QAAQ,MAAM,KAAK;AACrD;;AAGA,SAAgB,cAAc,UAAgC;CAC5D,MAAM,QAAkB,CAAC;CACzB,IAAI,SAAS,WAAW,KAAA,KAAa,SAAS,WAAW,IAAI,MAAM,KAAK,GAAG,WAAW,SAAS,MAAM,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AAQ,GAAG,CAAC,CAAC,KAAK;CACzD,IAAI,UAAU,IAAI,OAAO;CACzB,MAAM,EAAE,MAAM,SAAS,MAAM,QAAQ,SAAS,OAAO,GAAG,oBAAoB;CAC5E,MAAM,OAAO,gBAAgB,KAAK,OAAO,eAAe;CACxD,MAAM,QAAQ,WAAW,OAAA,GAAgC;CACzD,OAAO;EAAE,KAAK;EAAM,OAAO,UAAU,KAAK,OAAO;EAAO,QAAQ,UAAU;EAAI;CAAM;AACtF"}
|
|
1
|
+
{"version":3,"file":"link.js","names":[],"sources":["../src/link/fragment.ts","../src/link/paste.ts"],"sourcesContent":["import { copyFailure } from '../core/errors';\nimport { resolveLinkUrl, type LinkUrlOptions } from './url';\n\n/**\n * A passage to link to: `start` alone, or `start` to `end` for a longer one.\n * `prefix` and `suffix` are the words around it, used to tell apart passages\n * that appear more than once. Each term must lie within one block of the page\n * (a paragraph, a list item, a heading).\n */\nexport interface TextFragment {\n readonly start: string;\n readonly end?: string;\n readonly prefix?: string;\n readonly suffix?: string;\n}\n\nexport interface TextFragmentOptions extends LinkUrlOptions {\n /** Passages longer than this many words link by their first and last words (`start,end`). Default 10. */\n readonly maxWords?: number;\n /** Words kept at each end of a long passage, and of prefix and suffix context. Default 4. */\n readonly contextWords?: number;\n /** Where to look for repeats of the passage, to decide whether context is needed. Default `document.body`. */\n readonly root?: Node;\n}\n\nconst invalid = (message: string) => copyFailure('invalid-payload', message);\n\nconst collapse = (text: string): string => text.replace(/\\s+/g, ' ').trim();\nconst words = (text: string): string[] => collapse(text).split(' ').filter((word) => word !== '');\n\n/**\n * Percent-encodes a directive term. `encodeURIComponent` leaves `-` alone, but the\n * directive syntax uses it (`prefix-,` and `,-suffix`), so it is encoded too.\n */\nexport function encodeTerm(term: string): string {\n return encodeURIComponent(term).replace(/-/g, '%2D');\n}\n\n/** The `text=` directive for a fragment. */\nexport function textDirective(fragment: TextFragment): string {\n const terms: string[] = [];\n if (fragment.prefix !== undefined && fragment.prefix !== '') terms.push(`${encodeTerm(fragment.prefix)}-`);\n terms.push(encodeTerm(fragment.start));\n if (fragment.end !== undefined && fragment.end !== '') terms.push(encodeTerm(fragment.end));\n if (fragment.suffix !== undefined && fragment.suffix !== '') terms.push(`-${encodeTerm(fragment.suffix)}`);\n return `text=${terms.join(',')}`;\n}\n\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value >= 1) return value;\n throw invalid(`\\`${name}\\` must be a positive integer (received ${String(value)}).`);\n}\n\n/** Elements that start a new block: text fragment terms never span them. */\nconst BLOCK = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'blockquote', 'body', 'caption', 'dd', 'details', 'dialog', 'div', 'dl', 'dt', 'fieldset',\n 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'main', 'nav',\n 'ol', 'p', 'pre', 'section', 'summary', 'table', 'td', 'th', 'tr', 'ul',\n]);\n\n/** The nearest block around `node`, or the top of its tree (a detached node's fragment, or the page body). */\nfunction blockOf(node: Node): Node {\n let top = node;\n for (let current: Node | null = node; current !== null; current = current.parentNode) {\n if (current.nodeType === 1 && BLOCK.has((current as Element).localName)) return current;\n top = current;\n }\n if (top.nodeType !== 9) return top;\n const body: unknown = (top as Document).body; // Null in an XML document, despite its type.\n return body instanceof Node ? body : top;\n}\n\n/** The text of `block` from its start to (`before`) or from (`after`) a boundary point. */\nfunction around(block: Node, container: Node, offset: number, side: 'before' | 'after'): string {\n const range = (container.ownerDocument as Document).createRange();\n range.selectNodeContents(block);\n if (side === 'before') range.setEnd(container, offset);\n else range.setStart(container, offset);\n return range.toString();\n}\n\nconst count = (haystack: string, needle: string): number => {\n let found = 0;\n for (let at = haystack.indexOf(needle); at !== -1 && found < 2; at = haystack.indexOf(needle, at + 1)) found += 1;\n return found;\n};\n\nfunction rootText(root: Node | undefined): string | null {\n const node = root ?? (typeof document === 'undefined' ? undefined : document.body);\n if (node === undefined) return null;\n // A range reads the text of any node, a whole Document included (whose `textContent` is null).\n const range = ((node.ownerDocument ?? node) as Document).createRange();\n range.selectNodeContents(node);\n return collapse(range.toString()).toLowerCase();\n}\n\n/** Splits a passage into a directive: whole when short, first and last words when long. */\nfunction fromText(text: string, maxWords: number, contextWords: number): TextFragment {\n const all = words(text);\n if (all.length === 0) throw invalid('A text fragment needs some text.');\n if (all.length <= maxWords) return { start: all.join(' ') };\n return { start: all.slice(0, contextWords).join(' '), end: all.slice(-contextWords).join(' ') };\n}\n\n/** A fragment for a selected range: terms taken from within their own blocks, context added when the passage repeats. */\nfunction fromRange(range: Range, maxWords: number, contextWords: number, root: Node | undefined): TextFragment {\n const startBlock = blockOf(range.startContainer);\n const endBlock = blockOf(range.endContainer);\n const text = collapse(range.toString());\n if (text === '') throw invalid('A text fragment needs some text: the range is empty.');\n let fragment: TextFragment;\n if (startBlock === endBlock) {\n fragment = fromText(text, maxWords, contextWords);\n } else {\n // A passage across blocks: start in the first block, end in the last.\n const head = words(around(startBlock, range.startContainer, range.startOffset, 'after')).slice(0, contextWords);\n const tail = words(around(endBlock, range.endContainer, range.endOffset, 'before')).slice(-contextWords);\n fragment = head.length === 0 || tail.length === 0 ? fromText(text, maxWords, contextWords) : { start: head.join(' '), end: tail.join(' ') };\n }\n const page = rootText(root);\n if (page !== null && count(page, fragment.start.toLowerCase()) < 2) return fragment;\n // The start appears more than once (or the page can't be read): add the words around the passage.\n const prefix = words(around(startBlock, range.startContainer, range.startOffset, 'before')).slice(-contextWords).join(' ');\n const suffix = words(around(endBlock, range.endContainer, range.endOffset, 'after')).slice(0, contextWords).join(' ');\n return { ...fragment, prefix, suffix }; // Empty terms are left out of the directive.\n}\n\n/** A caller's fragment with each term on one line; empty optional terms are left out of the directive. */\nfunction fromObject(passage: TextFragment): TextFragment {\n const term = (value: unknown): string => (typeof value === 'string' ? collapse(value) : '');\n const start = term(passage.start);\n if (start === '') throw invalid('A text fragment needs a non-empty `start`.');\n return { start, end: term(passage.end), prefix: term(passage.prefix), suffix: term(passage.suffix) };\n}\n\nfunction isRange(value: unknown): value is Range {\n return typeof value === 'object' && value !== null && typeof (value as Range).cloneContents === 'function' && 'startContainer' in value;\n}\n\n/**\n * A link that scrolls to, and highlights, a passage of the page: the\n * [text fragment](https://wicg.github.io/scroll-to-text-fragment/) syntax\n * (`#:~:text=`), supported by Chromium, Safari and Firefox. Browsers without it\n * open the page at its normal position (or its existing `#section`).\n *\n * The passage is a string, a {@link TextFragment}, or a DOM `Range` (the user's\n * selection): long passages link by their first and last words, and the words\n * around a passage are added when it appears more than once on the page.\n *\n * @example\n * textFragmentUrl(location.href, window.getSelection()!.getRangeAt(0));\n * textFragmentUrl('https://example.com/docs#install', 'npm install react-smart-copy');\n */\nexport function textFragmentUrl(url: string | URL, passage: string | TextFragment | Range, options: TextFragmentOptions = {}): string {\n const maxWords = positive(options.maxWords, 10, 'maxWords');\n const contextWords = positive(options.contextWords, 4, 'contextWords');\n let fragment: TextFragment;\n if (typeof passage === 'string') {\n fragment = fromText(passage, maxWords, contextWords);\n } else if (isRange(passage)) {\n fragment = fromRange(passage, maxWords, contextWords, options.root);\n } else if (typeof passage === 'object' && (passage as unknown) !== null && typeof (passage as { start?: unknown }).start === 'string') {\n fragment = fromObject(passage);\n } else {\n throw invalid('The passage must be a string, a TextFragment or a Range.');\n }\n const href = resolveLinkUrl(url, options);\n const hashAt = href.indexOf('#');\n const base = hashAt === -1 ? href : href.slice(0, hashAt);\n // Keep an existing #section; replace any earlier directive.\n const section = hashAt === -1 ? '' : (href.slice(hashAt + 1).split(':~:')[0] as string);\n return `${base}#${section}:~:${textDirective(fragment)}`;\n}\n\n/** Whether this browser scrolls to text fragments (`document.fragmentDirective`). */\nexport function supportsTextFragments(): boolean {\n return typeof document !== 'undefined' && 'fragmentDirective' in document;\n}\n","import { copyFailure } from '../core/errors';\nimport { asTextField, insertText } from '../core/text-field';\nimport { cleanTitle, DEFAULT_LINK_TITLE_LENGTH, markdownLink, type ResolvedLink } from './payload';\nimport { textFragmentUrl, type TextFragmentOptions } from './fragment';\nimport { linkUrlResolver, type LinkUrlOptions } from './url';\nimport { parseInertHtml } from '../core/inert-html';\n\n/** What was pasted or dropped: a `PasteResult` from `usePaste`, a `DataTransfer`-like source, or the flavours themselves. */\nexport interface LinkPasteSource {\n readonly text?: string | null;\n readonly html?: string | null;\n /** `text/uri-list`. */\n readonly uriList?: string | null;\n /** A `PasteResult`'s entries: a `text/uri-list` entry is read from here. */\n readonly items?: readonly { readonly type: string; readonly data: string | Blob }[];\n}\n\n/** One URL with no spaces, as a whole pasted text (surrounding whitespace allowed). */\nconst SINGLE_URL = /^\\s*<?([a-z][a-z\\d+.-]*:[^\\s<>]+?)>?\\s*$/i;\n\ntype Resolve = (input: string) => string;\n\n/** The URL, or `null` when the clipboard content is not a valid, allowed link. */\nfunction tryUrl(resolve: Resolve, candidate: string): string | null {\n try {\n return resolve(candidate);\n } catch {\n return null;\n }\n}\n\nfunction fromUriList(list: string, resolve: Resolve): string | null {\n // RFC 2483: one URI per line, lines starting with \"#\" are comments.\n const first = list.split(/\\r?\\n/).find((line) => line.trim() !== '' && !line.startsWith('#'));\n return first === undefined ? null : tryUrl(resolve, first.trim());\n}\n\n/** The single link in pasted HTML (one `<a href>` and nothing else visible besides its text), parsed inertly. */\nfunction fromHtml(html: string, resolve: Resolve): ResolvedLink | null {\n if (typeof DOMParser === 'undefined' || html.trim() === '') return null;\n const body = parseInertHtml(html.slice(0, 100_000)).body;\n const anchors = body.querySelectorAll('a[href]');\n if (anchors.length !== 1) return null;\n const anchor = anchors[0] as HTMLAnchorElement;\n const visible = body.textContent.replace(/\\s+/g, ' ').trim();\n const label = anchor.textContent.replace(/\\s+/g, ' ').trim();\n if (visible !== label) return null; // A link inside more text is not \"a link\".\n const url = tryUrl(resolve, String(anchor.getAttribute('href'))); // Matched by `a[href]`.\n if (url === null) return null;\n const title = cleanTitle(label, DEFAULT_LINK_TITLE_LENGTH);\n return { url, title: title === '' ? url : title, titled: title !== '' && title !== url };\n}\n\n/**\n * The link the clipboard (or a drop) holds, or `null`: from `text/uri-list`,\n * from HTML that is exactly one link (keeping its title), or from text that is\n * exactly one URL. Every URL is validated: allowed schemes only (never\n * `javascript:`), credentials removed. Never throws for clipboard content.\n *\n * @example\n * usePaste({ accept: ['text', 'html', 'text/uri-list'], onPaste: (result) => {\n * const link = readLink(result);\n * if (link) addBookmark(link.url, link.title);\n * } });\n */\nexport function readLink(source: LinkPasteSource, options: LinkUrlOptions = {}): ResolvedLink | null {\n return readWith(source, linkUrlResolver(options));\n}\n\nfunction readWith(source: LinkPasteSource, resolve: Resolve): ResolvedLink | null {\n const uriList = source.uriList ?? source.items?.find((item) => item.type === 'text/uri-list' && typeof item.data === 'string')?.data;\n if (typeof uriList === 'string') {\n const url = fromUriList(uriList, resolve);\n if (url !== null) {\n const fromMarkup = typeof source.html === 'string' ? fromHtml(source.html, resolve) : null;\n return fromMarkup?.url === url ? fromMarkup : { url, title: url, titled: false };\n }\n }\n if (typeof source.html === 'string') {\n const link = fromHtml(source.html, resolve);\n if (link !== null) return link;\n }\n const match = typeof source.text === 'string' ? SINGLE_URL.exec(source.text) : null;\n const url = match === null ? null : tryUrl(resolve, match[1] as string);\n return url === null ? null : { url, title: url, titled: false };\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface LinkPasteEvent {\n readonly clipboardData: { getData(format: string): string } | null;\n readonly currentTarget: EventTarget | null;\n readonly target: EventTarget | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\nexport interface PasteAsLinkOptions extends LinkUrlOptions {\n /**\n * What replaces the selection. Default: a Markdown link, `[selection](url)`.\n * Receives the selected text and the pasted link.\n */\n readonly format?: (selection: string, link: ResolvedLink) => string;\n}\n\n/**\n * A paste handler for text fields: pasting a link over selected text turns the\n * selection into a link (`[selected text](url)` by default), as GitHub, Slack\n * and Notion do. Everything else is left to the browser: pasting with nothing\n * selected, pasting over a URL, or pasting something that is not one link. The\n * browser's undo still works. Returns whether it handled the paste.\n *\n * @example\n * <textarea onPaste={pasteAsLink} />\n */\nexport function pasteAsLink(event: LinkPasteEvent, options: PasteAsLinkOptions = {}): boolean {\n const { format, ...urlOptions } = options;\n // Invalid options are a programming error: thrown before the paste is touched, so the native paste still happens.\n const resolve = linkUrlResolver(urlOptions);\n if (event.defaultPrevented || event.clipboardData === null) return false;\n const field = asTextField(event.currentTarget) ?? asTextField(event.target);\n if (field === null || field.disabled || field.readOnly || field.selectionStart === null || field.selectionEnd === null) return false;\n const selection = field.value.slice(field.selectionStart, field.selectionEnd);\n if (selection.trim() === '' || SINGLE_URL.test(selection)) return false;\n const data = event.clipboardData;\n const link = readWith({ text: data.getData('text/plain'), html: data.getData('text/html'), uriList: data.getData('text/uri-list') }, resolve);\n if (link === null) return false;\n const text = format === undefined ? markdownLink({ ...link, title: selection, titled: true }) : format(selection, link);\n if (typeof text !== 'string') throw copyFailure('invalid-payload', '`format` must return a string.');\n event.preventDefault();\n return insertText(field, text);\n}\n\n/** A link to the current selection, as returned by {@link selectionLink}. */\nexport interface SelectionLink extends ResolvedLink {\n /** The selected text, as one line. */\n readonly quote: string;\n}\n\nexport interface SelectionLinkOptions extends TextFragmentOptions {\n /** The page to link to. Default: `location.href`. */\n readonly url?: string | URL;\n /** Default: `document.title`. */\n readonly title?: string;\n}\n\n/**\n * A link to the passage the user has selected (a text fragment link), with the\n * page title and the quote, or `null` when nothing is selected. Pass it to\n * `linkPayload` to copy it.\n *\n * @example\n * const link = selectionLink();\n * if (link) copy(() => linkPayload(link));\n */\nexport function selectionLink(options: SelectionLinkOptions = {}): SelectionLink | null {\n if (typeof window === 'undefined' || typeof document === 'undefined') return null;\n const selection = window.getSelection();\n if (selection === null || selection.rangeCount === 0 || selection.isCollapsed) return null;\n const range = selection.getRangeAt(0);\n const quote = range.toString().replace(/\\s+/g, ' ').trim();\n if (quote === '') return null;\n const { url = location.href, title = document.title, ...fragmentOptions } = options;\n const href = textFragmentUrl(url, range, fragmentOptions);\n const clean = cleanTitle(title, DEFAULT_LINK_TITLE_LENGTH);\n return { url: href, title: clean === '' ? href : clean, titled: clean !== '', quote };\n}\n"],"mappings":";;;;;;;AAyBA,MAAM,WAAW,YAAoB,YAAY,mBAAmB,OAAO;AAE3E,MAAM,YAAY,SAAyB,KAAK,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;AAC1E,MAAM,SAAS,SAA2B,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,QAAQ,SAAS,SAAS,EAAE;;;;;AAMhG,SAAgB,WAAW,MAAsB;CAC/C,OAAO,mBAAmB,IAAI,CAAC,CAAC,QAAQ,MAAM,KAAK;AACrD;;AAGA,SAAgB,cAAc,UAAgC;CAC5D,MAAM,QAAkB,CAAC;CACzB,IAAI,SAAS,WAAW,KAAA,KAAa,SAAS,WAAW,IAAI,MAAM,KAAK,GAAG,WAAW,SAAS,MAAM,EAAE,EAAE;CACzG,MAAM,KAAK,WAAW,SAAS,KAAK,CAAC;CACrC,IAAI,SAAS,QAAQ,KAAA,KAAa,SAAS,QAAQ,IAAI,MAAM,KAAK,WAAW,SAAS,GAAG,CAAC;CAC1F,IAAI,SAAS,WAAW,KAAA,KAAa,SAAS,WAAW,IAAI,MAAM,KAAK,IAAI,WAAW,SAAS,MAAM,GAAG;CACzG,OAAO,QAAQ,MAAM,KAAK,GAAG;AAC/B;AAEA,SAAS,SAAS,OAA2B,UAAkB,MAAsB;CACnF,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,OAAO,UAAU,KAAK,KAAK,SAAS,GAAG,OAAO;CAClD,MAAM,QAAQ,KAAK,KAAK,0CAA0C,OAAO,KAAK,EAAE,GAAG;AACrF;;AAGA,MAAM,wBAAwB,IAAI,IAAI;CACpC;CAAW;CAAW;CAAS;CAAc;CAAQ;CAAW;CAAM;CAAW;CAAU;CAAO;CAAM;CAAM;CAC9G;CAAc;CAAU;CA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,eAAe;CAAE,GAAG,OAAO;CAC5I,IAAI,SAAS,MAAM,OAAO;CAC1B,MAAM,OAAO,WAAW,KAAA,IAAY,aAAa;EAAE,GAAG;EAAM,OAAO;EAAW,QAAQ;CAAK,CAAC,IAAI,OAAO,WAAW,IAAI;CACtH,IAAI,OAAO,SAAS,UAAU,MAAM,YAAY,mBAAmB,gCAAgC;CACnG,MAAM,eAAe;CACrB,OAAO,WAAW,OAAO,IAAI;AAC/B;;;;;;;;;;AAwBA,SAAgB,cAAc,UAAgC,CAAC,GAAyB;CACtF,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa,OAAO;CAC7E,MAAM,YAAY,OAAO,aAAa;CACtC,IAAI,cAAc,QAAQ,UAAU,eAAe,KAAK,UAAU,aAAa,OAAO;CACtF,MAAM,QAAQ,UAAU,WAAW,CAAC;CACpC,MAAM,QAAQ,MAAM,SAAS,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CACzD,IAAI,UAAU,IAAI,OAAO;CACzB,MAAM,EAAE,MAAM,SAAS,MAAM,QAAQ,SAAS,OAAO,GAAG,oBAAoB;CAC5E,MAAM,OAAO,gBAAgB,KAAK,OAAO,eAAe;CACxD,MAAM,QAAQ,WAAW,OAAA,GAAgC;CACzD,OAAO;EAAE,KAAK;EAAM,OAAO,UAAU,KAAK,OAAO;EAAO,QAAQ,UAAU;EAAI;CAAM;AACtF"}
|
package/dist/markdown.cjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
|
|
4
|
+
const require_inert_html = require("./chunks/inert-html-DyxjWDok.cjs");
|
|
5
|
+
const require_url = require("./chunks/url-B9jdFGQy.cjs");
|
|
4
6
|
const require_text_field = require("./chunks/text-field-Ba8W3v4R.cjs");
|
|
5
7
|
//#region src/markdown/escape.ts
|
|
6
8
|
/**
|
|
@@ -43,59 +45,6 @@ function escapeLineStart(text) {
|
|
|
43
45
|
function escapeMarkdown(text) {
|
|
44
46
|
return text.split(/\r\n|\r|\n/).map((line) => escapeLineStart(escapeInline(line.replace(/^[ \t]+/, "")))).join("\n");
|
|
45
47
|
}
|
|
46
|
-
//#endregion
|
|
47
|
-
//#region src/markdown/url.ts
|
|
48
|
-
/**
|
|
49
|
-
* URL safety for pasted links and images. Only absolute URLs with an allowed
|
|
50
|
-
* scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
|
|
51
|
-
* relative links without a base, malformed URLs) is dropped and the visible
|
|
52
|
-
* text is kept. Parsing uses the WHATWG URL parser, the same one the browser
|
|
53
|
-
* uses when the link is clicked, so tricks like `java\tscript:` are seen as
|
|
54
|
-
* `javascript:`.
|
|
55
|
-
*/
|
|
56
|
-
const DEFAULT_LINK_PROTOCOLS = [
|
|
57
|
-
"http:",
|
|
58
|
-
"https:",
|
|
59
|
-
"mailto:"
|
|
60
|
-
];
|
|
61
|
-
const DEFAULT_IMAGE_PROTOCOLS = ["https:", "http:"];
|
|
62
|
-
function parse(raw, base) {
|
|
63
|
-
try {
|
|
64
|
-
return new URL(raw.trim(), base);
|
|
65
|
-
} catch {
|
|
66
|
-
return null;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Click-tracking redirects that pasted links often carry: Google (Docs,
|
|
71
|
-
* Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.
|
|
72
|
-
*/
|
|
73
|
-
function unwrapRedirect(url) {
|
|
74
|
-
const host = url.hostname.toLowerCase();
|
|
75
|
-
const param = /(^|\.)google\.[a-z.]+$/.test(host) && url.pathname === "/url" ? url.searchParams.get("q") ?? url.searchParams.get("url") : host.endsWith(".safelinks.protection.outlook.com") ? url.searchParams.get("url") : null;
|
|
76
|
-
if (param === null) return url;
|
|
77
|
-
const target = parse(param, void 0);
|
|
78
|
-
return target !== null && (target.protocol === "https:" || target.protocol === "http:") ? target : url;
|
|
79
|
-
}
|
|
80
|
-
/** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */
|
|
81
|
-
function safeUrl(raw, protocols, base) {
|
|
82
|
-
const parsed = parse(raw, base);
|
|
83
|
-
if (parsed === null) return null;
|
|
84
|
-
const url = unwrapRedirect(parsed);
|
|
85
|
-
return protocols.includes(url.protocol) ? url.href : null;
|
|
86
|
-
}
|
|
87
|
-
/** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */
|
|
88
|
-
const percent = (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
|
|
89
|
-
/**
|
|
90
|
-
* A Markdown link destination. ASCII whitespace, `<`, `>` and controls are
|
|
91
|
-
* percent-encoded (opaque URLs such as `mailto:` keep them otherwise),
|
|
92
|
-
* backslashes too so they can't act as escapes, and parentheses are kept
|
|
93
|
-
* exact by using the `<…>` form.
|
|
94
|
-
*/
|
|
95
|
-
function linkDestination(href) {
|
|
96
|
-
const encoded = href.replace(/[ <>\\\u0000-\u001f\u007f]/g, percent);
|
|
97
|
-
return /[()]/.test(encoded) ? `<${encoded}>` : encoded;
|
|
98
|
-
}
|
|
99
48
|
/** Outermost first: a style lower in the list is always nested inside the ones above it. */
|
|
100
49
|
const ORDER = [
|
|
101
50
|
[4, "~~"],
|
|
@@ -257,7 +206,7 @@ function tokenize(runs, options) {
|
|
|
257
206
|
if (tokens.length - 1 === linkStart) tokens.pop();
|
|
258
207
|
else tokens.push({
|
|
259
208
|
kind: "syntax",
|
|
260
|
-
s: `](${linkDestination(href)})`
|
|
209
|
+
s: `](${require_url.linkDestination(href)})`
|
|
261
210
|
});
|
|
262
211
|
href = null;
|
|
263
212
|
};
|
|
@@ -288,7 +237,7 @@ function tokenize(runs, options) {
|
|
|
288
237
|
setStyle(run.style & -9, "");
|
|
289
238
|
tokens.push({
|
|
290
239
|
kind: "syntax",
|
|
291
|
-
s: `})`
|
|
240
|
+
s: `})`
|
|
292
241
|
});
|
|
293
242
|
continue;
|
|
294
243
|
}
|
|
@@ -544,8 +493,8 @@ function resolveOptions(options) {
|
|
|
544
493
|
return {
|
|
545
494
|
images: options.images ?? "alt",
|
|
546
495
|
links: options.links ?? "keep",
|
|
547
|
-
linkProtocols: options.linkProtocols ?? DEFAULT_LINK_PROTOCOLS,
|
|
548
|
-
imageProtocols: options.imageProtocols ?? DEFAULT_IMAGE_PROTOCOLS,
|
|
496
|
+
linkProtocols: options.linkProtocols ?? require_url.DEFAULT_LINK_PROTOCOLS,
|
|
497
|
+
imageProtocols: options.imageProtocols ?? require_url.DEFAULT_IMAGE_PROTOCOLS,
|
|
549
498
|
baseUrl: options.baseUrl,
|
|
550
499
|
bullet: options.bullet ?? "-",
|
|
551
500
|
hardBreak: options.hardBreak === "spaces" ? " \n" : "\\\n",
|
|
@@ -891,7 +840,7 @@ var Converter = class {
|
|
|
891
840
|
const { images, imageProtocols, baseUrl } = this.options;
|
|
892
841
|
if (images === "drop") return;
|
|
893
842
|
const alt = (element.getAttribute("alt") ?? "").replace(/\s+/g, " ").trim();
|
|
894
|
-
const src = images === "keep" ? safeUrl(element.getAttribute("src") ?? "", imageProtocols, baseUrl) : null;
|
|
843
|
+
const src = images === "keep" ? require_url.safeUrl(element.getAttribute("src") ?? "", imageProtocols, baseUrl) : null;
|
|
895
844
|
const style = ctx.style & ~ctx.mask;
|
|
896
845
|
if (src !== null) runs.push({
|
|
897
846
|
kind: "image",
|
|
@@ -910,7 +859,7 @@ var Converter = class {
|
|
|
910
859
|
link(element, tag, ctx) {
|
|
911
860
|
if (tag !== "a" || ctx.href !== null || this.options.links === "text") return ctx.href;
|
|
912
861
|
const href = element.getAttribute("href");
|
|
913
|
-
return href === null ? null : safeUrl(href, this.options.linkProtocols, this.options.baseUrl);
|
|
862
|
+
return href === null ? null : require_url.safeUrl(href, this.options.linkProtocols, this.options.baseUrl);
|
|
914
863
|
}
|
|
915
864
|
code(element, ctx) {
|
|
916
865
|
const text = this.codeText(element, ctx.depth).replace(/\r\n?/g, "\n").replace(/\u00a0/g, " ").replace(/^\n/, "").replace(/\s+$/, "");
|
|
@@ -1213,7 +1162,7 @@ function htmlToMarkdown(source, options = {}) {
|
|
|
1213
1162
|
function parseHtml(html, resolved) {
|
|
1214
1163
|
if (typeof DOMParser === "undefined") throw require_errors.copyFailure("unsupported", "htmlToMarkdown needs DOMParser to read an HTML string; pass a DOM node instead.");
|
|
1215
1164
|
return {
|
|
1216
|
-
body:
|
|
1165
|
+
body: require_inert_html.parseInertHtml(html.slice(0, resolved.maxLength)).body,
|
|
1217
1166
|
truncated: html.length > resolved.maxLength
|
|
1218
1167
|
};
|
|
1219
1168
|
}
|
|
@@ -1320,8 +1269,8 @@ function pasteAsMarkdown(event, options) {
|
|
|
1320
1269
|
return require_text_field.insertText(field, pasted.markdown);
|
|
1321
1270
|
}
|
|
1322
1271
|
//#endregion
|
|
1323
|
-
exports.DEFAULT_IMAGE_PROTOCOLS = DEFAULT_IMAGE_PROTOCOLS;
|
|
1324
|
-
exports.DEFAULT_LINK_PROTOCOLS = DEFAULT_LINK_PROTOCOLS;
|
|
1272
|
+
exports.DEFAULT_IMAGE_PROTOCOLS = require_url.DEFAULT_IMAGE_PROTOCOLS;
|
|
1273
|
+
exports.DEFAULT_LINK_PROTOCOLS = require_url.DEFAULT_LINK_PROTOCOLS;
|
|
1325
1274
|
exports.DEFAULT_MARKDOWN_MAX_DEPTH = DEFAULT_MARKDOWN_MAX_DEPTH;
|
|
1326
1275
|
exports.DEFAULT_MARKDOWN_MAX_LENGTH = DEFAULT_MARKDOWN_MAX_LENGTH;
|
|
1327
1276
|
exports.DEFAULT_MARKDOWN_MAX_NODES = DEFAULT_MARKDOWN_MAX_NODES;
|