@lexical/markdown 0.3.7 → 0.3.10

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.
@@ -20,6 +20,7 @@ var link = require('@lexical/link');
20
20
  * LICENSE file in the root directory of this source tree.
21
21
  *
22
22
  */
23
+
23
24
  function indexBy(list, callback) {
24
25
  const index = {};
25
26
 
@@ -38,9 +39,9 @@ function indexBy(list, callback) {
38
39
  function transformersByType(transformers) {
39
40
  const byType = indexBy(transformers, t => t.type);
40
41
  return {
41
- element: byType.element,
42
- textFormat: byType['text-format'],
43
- textMatch: byType['text-match']
42
+ element: byType.element || [],
43
+ textFormat: byType['text-format'] || [],
44
+ textMatch: byType['text-match'] || []
44
45
  };
45
46
  }
46
47
  const PUNCTUATION_OR_SPACE = /[!-/:-@[-`{-~\s]/;
@@ -230,7 +231,7 @@ function createMarkdownImport(transformers) {
230
231
  const children = root.getChildren();
231
232
 
232
233
  for (const child of children) {
233
- if (lexical.$isParagraphNode(child) && MARKDOWN_EMPTY_LINE_REG_EXP.test(child.getTextContent())) {
234
+ if (isEmptyParagraph(child)) {
234
235
  child.remove();
235
236
  }
236
237
  }
@@ -239,6 +240,15 @@ function createMarkdownImport(transformers) {
239
240
  };
240
241
  }
241
242
 
243
+ function isEmptyParagraph(node) {
244
+ if (!lexical.$isParagraphNode(node)) {
245
+ return false;
246
+ }
247
+
248
+ const firstChild = node.getFirstChild();
249
+ return firstChild == null || node.getChildrenSize() === 1 && lexical.$isTextNode(firstChild) && MARKDOWN_EMPTY_LINE_REG_EXP.test(firstChild.getTextContent());
250
+ }
251
+
242
252
  function importBlocks(lineText, rootNode, elementTransformers, textFormatTransformersIndex, textMatchTransformers) {
243
253
  const lineTextTrimmed = lineText.trim();
244
254
  const textNode = lexical.$createTextNode(lineTextTrimmed);
@@ -328,7 +338,7 @@ function importTextFormatTransformers(textNode, textFormatTransformersIndex, tex
328
338
  return;
329
339
  }
330
340
 
331
- let currentNode, remainderNode; // If matching full content there's no need to run splitText and can reuse existing textNode
341
+ let currentNode, remainderNode, leadingNode; // If matching full content there's no need to run splitText and can reuse existing textNode
332
342
  // to update its content and apply format. E.g. for **_Hello_** string after applying bold
333
343
  // format (**) it will reuse the same text node to apply italic (_)
334
344
 
@@ -341,7 +351,7 @@ function importTextFormatTransformers(textNode, textFormatTransformersIndex, tex
341
351
  if (startIndex === 0) {
342
352
  [currentNode, remainderNode] = textNode.splitText(endIndex);
343
353
  } else {
344
- [, currentNode, remainderNode] = textNode.splitText(startIndex, endIndex);
354
+ [leadingNode, currentNode, remainderNode] = textNode.splitText(startIndex, endIndex);
345
355
  }
346
356
  }
347
357
 
@@ -359,9 +369,13 @@ function importTextFormatTransformers(textNode, textFormatTransformersIndex, tex
359
369
 
360
370
  if (!currentNode.hasFormat('code')) {
361
371
  importTextFormatTransformers(currentNode, textFormatTransformersIndex, textMatchTransformers);
362
- } // Run over remaining text if any
372
+ } // Run over leading/remaining text if any
363
373
 
364
374
 
375
+ if (leadingNode) {
376
+ importTextFormatTransformers(leadingNode, textFormatTransformersIndex, textMatchTransformers);
377
+ }
378
+
365
379
  if (remainderNode) {
366
380
  importTextFormatTransformers(remainderNode, textFormatTransformersIndex, textMatchTransformers);
367
381
  }
@@ -540,7 +554,7 @@ function runTextMatchTransformers(anchorNode, anchorOffset, transformersByTrigge
540
554
  [, replaceNode] = anchorNode.splitText(startIndex, endIndex);
541
555
  }
542
556
 
543
- replaceNode.selectNext();
557
+ replaceNode.selectNext(0, 0);
544
558
  transformer.replace(replaceNode, match);
545
559
  return true;
546
560
  }
@@ -4,25 +4,25 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
- 'use strict';var k=require("lexical"),y=require("@lexical/code"),E=require("@lexical/list"),F=require("@lexical/rich-text"),aa=require("@lexical/utils"),G=require("@lexical/link");function H(a,b){let c={};for(let d of a)a=b(d),c[a]?c[a].push(d):c[a]=[d];return c}function I(a){a=H(a,b=>b.type);return{element:a.element,textFormat:a["text-format"],textMatch:a["text-match"]}}let J=/[!-/:-@[-`{-~\s]/;
8
- function ba(a){let b=I(a),c=b.textFormat.filter(d=>1===d.format.length);return()=>{let d=[];var e=k.$getRoot().getChildren();for(let f of e)e=ca(f,b.element,c,b.textMatch),null!=e&&d.push(e);return d.join("\n\n")}}function ca(a,b,c,d){for(let e of b)if(b=e.export(a,f=>K(f,c,d)),null!=b)return b;return k.$isElementNode(a)?K(a,c,d):null}
9
- function K(a,b,c){let d=[];a=a.getChildren();a:for(let e of a){for(let f of c)if(a=f.export(e,h=>K(h,b,c),(h,p)=>L(h,p,b)),null!=a){d.push(a);continue a}k.$isLineBreakNode(e)?d.push("\n"):k.$isTextNode(e)?d.push(L(e,e.getTextContent(),b)):k.$isElementNode(e)&&d.push(K(e,b,c))}return d.join("")}function L(a,b,c){let d=b.trim(),e=d,f=new Set;for(let p of c){c=p.format[0];let r=p.tag;if(M(a,c)&&!f.has(c)){f.add(c);var h=N(a,!0);M(h,c)||(e=r+e);h=N(a,!1);M(h,c)||(e+=r)}}return b.replace(d,e)}
10
- function N(a,b){let c=b?a.getPreviousSibling():a.getNextSibling();c||(a=a.getParentOrThrow(),a.isInline()&&(c=b?a.getPreviousSibling():a.getNextSibling()));for(;c;){if(k.$isElementNode(c)){if(!c.isInline())break;a=b?c.getLastDescendant():c.getFirstDescendant();if(k.$isTextNode(a))return a;c=b?c.getPreviousSibling():c.getNextSibling()}if(k.$isTextNode(c))return c;if(!k.$isElementNode(c))break}return null}function M(a,b){return k.$isTextNode(a)&&a.hasFormat(b)}let da=/^\s{0,3}$/,O=/^```(\w{1,10})?\s?$/;
11
- function ea(a){let b=I(a),c=fa(b.textFormat);return d=>{var e=d.split("\n");let f=e.length;d=k.$getRoot();d.clear();for(let g=0;g<f;g++){var h=e[g];a:{var p=e,r=g;var l=d;var x=p[r].match(O);if(x)for(var q=r,m=p.length;++q<m;)if(p[q].match(O)){x=y.$createCodeNode(x[1]);p=k.$createTextNode(p.slice(r+1,q).join("\n"));x.append(p);l.append(x);l=[x,q];break a}l=[null,r]}let [n,u]=l;if(null!=n)g=u;else{l=h;m=d;var v=b.element;q=c;p=b.textMatch;r=l.trim();x=k.$createTextNode(r);h=k.$createParagraphNode();
12
- h.append(x);m.append(h);for(let {regExp:w,replace:t}of v)if(m=l.match(w)){x.setTextContent(l.slice(m[0].length));t(h,[x],m,!0);break}P(x,q,p);h.isAttached()&&0<r.length&&(l=h.getPreviousSibling(),k.$isParagraphNode(l)||F.$isQuoteNode(l)||E.$isListNode(l))&&(q=l,E.$isListNode(l)&&(l=l.getLastDescendant(),q=null==l?null:aa.$findMatchingParent(l,E.$isListItemNode)),null!=q&&0<q.getTextContentSize()&&(q.splice(q.getChildrenSize(),0,[k.$createLineBreakNode(),...h.getChildren()]),h.remove()))}}e=d.getChildren();
13
- for(let g of e)k.$isParagraphNode(g)&&da.test(g.getTextContent())&&g.remove();d.selectEnd()}}
14
- function P(a,b,c){let d=a.getTextContent(),e=ha(d,b);if(e){if(e[0]===d)var f=a;else{var h=e.index||0,p=h+e[0].length;0===h?[f,l]=a.splitText(p):[,f,l]=a.splitText(h,p)}f.setTextContent(e[2]);if(h=b.transformersByTag[e[1]])for(var r of h.format)f.hasFormat(r)||f.toggleFormat(r);f.hasFormat("code")||P(f,b,c);l&&P(l,b,c)}else a:for(b=a;b;){for(h of c)if(f=b.getTextContent().match(h.importRegExp)){var l=f.index||0;r=l+f[0].length;0===l?[p,b]=b.splitText(r):[,p,b]=b.splitText(l,r);h.replace(p,f);continue a}break}}
15
- function ha(a,b){var c=a.match(b.openTagsRegExp);if(null==c)return null;for(let f of c){var d=f.replace(/^\s/,"");c=b.fullMatchRegExpByTag[d];if(null!=c&&(c=a.match(c),d=b.transformersByTag[d],null!=c&&null!=d)){if(!1!==d.intraword)return c;var {index:e=0}=c;d=a[e-1];e=a[e+c[0].length];if(!(d&&!J.test(d)||e&&!J.test(e)))return c}}return null}
7
+ 'use strict';var h=require("lexical"),y=require("@lexical/code"),E=require("@lexical/list"),F=require("@lexical/rich-text"),aa=require("@lexical/utils"),G=require("@lexical/link");function H(a,b){let c={};for(let d of a)a=b(d),c[a]?c[a].push(d):c[a]=[d];return c}function I(a){a=H(a,b=>b.type);return{element:a.element||[],textFormat:a["text-format"]||[],textMatch:a["text-match"]||[]}}let J=/[!-/:-@[-`{-~\s]/;
8
+ function ba(a){let b=I(a),c=b.textFormat.filter(d=>1===d.format.length);return()=>{let d=[];var e=h.$getRoot().getChildren();for(let f of e)e=ca(f,b.element,c,b.textMatch),null!=e&&d.push(e);return d.join("\n\n")}}function ca(a,b,c,d){for(let e of b)if(b=e.export(a,f=>K(f,c,d)),null!=b)return b;return h.$isElementNode(a)?K(a,c,d):null}
9
+ function K(a,b,c){let d=[];a=a.getChildren();a:for(let e of a){for(let f of c)if(a=f.export(e,k=>K(k,b,c),(k,p)=>L(k,p,b)),null!=a){d.push(a);continue a}h.$isLineBreakNode(e)?d.push("\n"):h.$isTextNode(e)?d.push(L(e,e.getTextContent(),b)):h.$isElementNode(e)&&d.push(K(e,b,c))}return d.join("")}function L(a,b,c){let d=b.trim(),e=d,f=new Set;for(let p of c){c=p.format[0];let r=p.tag;if(M(a,c)&&!f.has(c)){f.add(c);var k=N(a,!0);M(k,c)||(e=r+e);k=N(a,!1);M(k,c)||(e+=r)}}return b.replace(d,e)}
10
+ function N(a,b){let c=b?a.getPreviousSibling():a.getNextSibling();c||(a=a.getParentOrThrow(),a.isInline()&&(c=b?a.getPreviousSibling():a.getNextSibling()));for(;c;){if(h.$isElementNode(c)){if(!c.isInline())break;a=b?c.getLastDescendant():c.getFirstDescendant();if(h.$isTextNode(a))return a;c=b?c.getPreviousSibling():c.getNextSibling()}if(h.$isTextNode(c))return c;if(!h.$isElementNode(c))break}return null}function M(a,b){return h.$isTextNode(a)&&a.hasFormat(b)}let da=/^\s{0,3}$/,O=/^```(\w{1,10})?\s?$/;
11
+ function ea(a){let b=I(a),c=fa(b.textFormat);return d=>{var e=d.split("\n"),f=e.length;d=h.$getRoot();d.clear();for(let g=0;g<f;g++){var k=e[g];a:{var p=e,r=g;var n=d;var t=p[r].match(O);if(t)for(var q=r,l=p.length;++q<l;)if(p[q].match(O)){t=y.$createCodeNode(t[1]);p=h.$createTextNode(p.slice(r+1,q).join("\n"));t.append(p);n.append(t);n=[t,q];break a}n=[null,r]}let [m,v]=n;if(null!=m)g=v;else{n=k;l=d;var w=b.element;q=c;p=b.textMatch;r=n.trim();t=h.$createTextNode(r);k=h.$createParagraphNode();k.append(t);
12
+ l.append(k);for(let {regExp:x,replace:u}of w)if(l=n.match(x)){t.setTextContent(n.slice(l[0].length));u(k,[t],l,!0);break}P(t,q,p);k.isAttached()&&0<r.length&&(n=k.getPreviousSibling(),h.$isParagraphNode(n)||F.$isQuoteNode(n)||E.$isListNode(n))&&(q=n,E.$isListNode(n)&&(n=n.getLastDescendant(),q=null==n?null:aa.$findMatchingParent(n,E.$isListItemNode)),null!=q&&0<q.getTextContentSize()&&(q.splice(q.getChildrenSize(),0,[h.$createLineBreakNode(),...k.getChildren()]),k.remove()))}}e=d.getChildren();for(let g of e)e=
13
+ g,h.$isParagraphNode(e)?(f=e.getFirstChild(),e=null==f||1===e.getChildrenSize()&&h.$isTextNode(f)&&da.test(f.getTextContent())):e=!1,e&&g.remove();d.selectEnd()}}
14
+ function P(a,b,c){let d=a.getTextContent(),e=ha(d,b);if(e){if(e[0]===d)var f=a;else{var k=e.index||0,p=k+e[0].length;0===k?[f,r]=a.splitText(p):[n,f,r]=a.splitText(k,p)}f.setTextContent(e[2]);if(k=b.transformersByTag[e[1]])for(let t of k.format)f.hasFormat(t)||f.toggleFormat(t);f.hasFormat("code")||P(f,b,c);n&&P(n,b,c);r&&P(r,b,c)}else a:for(b=a;b;){for(k of c)if(f=b.getTextContent().match(k.importRegExp)){var r=f.index||0;var n=r+f[0].length;0===r?[p,b]=b.splitText(n):[,p,b]=b.splitText(r,n);k.replace(p,
15
+ f);continue a}break}}function ha(a,b){var c=a.match(b.openTagsRegExp);if(null==c)return null;for(let f of c){var d=f.replace(/^\s/,"");c=b.fullMatchRegExpByTag[d];if(null!=c&&(c=a.match(c),d=b.transformersByTag[d],null!=c&&null!=d)){if(!1!==d.intraword)return c;var {index:e=0}=c;d=a[e-1];e=a[e+c[0].length];if(!(d&&!J.test(d)||e&&!J.test(e)))return c}}return null}
16
16
  function fa(a){let b={},c={},d=[];for(let e of a){({tag:a}=e);b[a]=e;let f=a.replace(/(\*|\^)/g,"\\$1");d.push(f);c[a]=new RegExp(`(${f})(?![${f}\\s])(.*?[^${f}\\s])${f}(?!${f})`)}return{fullMatchRegExpByTag:c,openTagsRegExp:new RegExp("("+d.join("|")+")","g"),transformersByTag:b}}function Q(a,b,c){let d=c.length;for(;b>=d;b--){let e=b-d;if(R(a,e,c,0,d)&&" "!==a[e+d])return e}return-1}function R(a,b,c,d,e){for(let f=0;f<e;f++)if(a[b+f]!==c[d+f])return!1;return!0}
17
17
  let S=a=>(b,c,d)=>{d=a(d);d.append(...c);b.replace(d);d.select(0,0)},T=a=>(b,c,d)=>{var e=b.getPreviousSibling();const f=E.$createListItemNode("check"===a?"x"===d[3]:void 0);E.$isListNode(e)&&e.getListType()===a?(e.append(f),b.remove()):(e=E.$createListNode(a,"number"===a?Number(d[2]):void 0),e.append(f),b.replace(e));f.append(...c);f.select(0,0);(b=Math.floor(d[1].length/4))&&f.setIndent(b)},U=(a,b,c)=>{const d=[];var e=a.getChildren();let f=0;for(const p of e)if(E.$isListItemNode(p)){if(1===p.getChildrenSize()&&
18
- (e=p.getFirstChild(),E.$isListNode(e))){d.push(U(e,b,c+1));continue}e=" ".repeat(4*c);var h=a.getListType();h="number"===h?`${a.getStart()+f}. `:"check"===h?`- [${p.getChecked()?"x":" "}] `:"- ";d.push(e+h+b(p));f++}return d.join("\n")},V={export:(a,b)=>{if(!F.$isHeadingNode(a))return null;const c=Number(a.getTag().slice(1));return"#".repeat(c)+" "+b(a)},regExp:/^(#{1,6})\s/,replace:S(a=>F.$createHeadingNode("h"+a[1].length)),type:"element"},W={export:(a,b)=>{if(!F.$isQuoteNode(a))return null;a=b(a).split("\n");
19
- b=[];for(const c of a)b.push("> "+c);return b.join("\n")},regExp:/^>\s/,replace:(a,b,c,d)=>{if(d&&(c=a.getPreviousSibling(),F.$isQuoteNode(c))){c.splice(c.getChildrenSize(),0,[k.$createLineBreakNode(),...b]);c.select(0,0);a.remove();return}c=F.$createQuoteNode();c.append(...b);a.replace(c);c.select(0,0)},type:"element"},X={export:a=>{if(!y.$isCodeNode(a))return null;const b=a.getTextContent();return"```"+(a.getLanguage()||"")+(b?"\n"+b:"")+"\n```"},regExp:/^```(\w{1,10})?\s/,replace:S(a=>y.$createCodeNode(a?
18
+ (e=p.getFirstChild(),E.$isListNode(e))){d.push(U(e,b,c+1));continue}e=" ".repeat(4*c);var k=a.getListType();k="number"===k?`${a.getStart()+f}. `:"check"===k?`- [${p.getChecked()?"x":" "}] `:"- ";d.push(e+k+b(p));f++}return d.join("\n")},V={export:(a,b)=>{if(!F.$isHeadingNode(a))return null;const c=Number(a.getTag().slice(1));return"#".repeat(c)+" "+b(a)},regExp:/^(#{1,6})\s/,replace:S(a=>F.$createHeadingNode("h"+a[1].length)),type:"element"},W={export:(a,b)=>{if(!F.$isQuoteNode(a))return null;a=b(a).split("\n");
19
+ b=[];for(const c of a)b.push("> "+c);return b.join("\n")},regExp:/^>\s/,replace:(a,b,c,d)=>{if(d&&(c=a.getPreviousSibling(),F.$isQuoteNode(c))){c.splice(c.getChildrenSize(),0,[h.$createLineBreakNode(),...b]);c.select(0,0);a.remove();return}c=F.$createQuoteNode();c.append(...b);a.replace(c);c.select(0,0)},type:"element"},X={export:a=>{if(!y.$isCodeNode(a))return null;const b=a.getTextContent();return"```"+(a.getLanguage()||"")+(b?"\n"+b:"")+"\n```"},regExp:/^```(\w{1,10})?\s/,replace:S(a=>y.$createCodeNode(a?
20
20
  a[1]:void 0)),type:"element"},Y={export:(a,b)=>E.$isListNode(a)?U(a,b,0):null,regExp:/^(\s*)[-*+]\s/,replace:T("bullet"),type:"element"},ia={export:(a,b)=>E.$isListNode(a)?U(a,b,0):null,regExp:/^(\s*)(?:-\s)?\s?(\[(\s|x)?\])\s/i,replace:T("check"),type:"element"},ja={export:(a,b)=>E.$isListNode(a)?U(a,b,0):null,regExp:/^(\s*)(\d{1,})\.\s/,replace:T("number"),type:"element"},ka={format:["code"],tag:"`",type:"text-format"},la={format:["bold","italic"],tag:"***",type:"text-format"},ma={format:["bold",
21
- "italic"],intraword:!1,tag:"___",type:"text-format"},na={format:["bold"],tag:"**",type:"text-format"},pa={format:["bold"],intraword:!1,tag:"__",type:"text-format"},qa={format:["strikethrough"],tag:"~~",type:"text-format"},ra={format:["italic"],tag:"*",type:"text-format"},sa={format:["italic"],intraword:!1,tag:"_",type:"text-format"},ta={export:(a,b,c)=>{if(!G.$isLinkNode(a))return null;b=`[${a.getTextContent()}](${a.getURL()})`;const d=a.getFirstChild();return 1===a.getChildrenSize()&&k.$isTextNode(d)?
22
- c(d,b):b},importRegExp:/(?:\[([^[]+)\])(?:\(([^(]+)\))/,regExp:/(?:\[([^[]+)\])(?:\(([^(]+)\))$/,replace:(a,b)=>{const [,c,d]=b;b=G.$createLinkNode(d);const e=k.$createTextNode(c);e.setFormat(a.getFormat());b.append(e);a.replace(b)},trigger:")",type:"text-match"},ua=[V,W,X,Y,ja],va=[ka,la,ma,na,pa,ra,sa,qa],wa=[ta],Z=[...ua,...va,...wa];exports.$convertFromMarkdownString=function(a,b=Z){return ea(b)(a)};exports.$convertToMarkdownString=function(a=Z){return ba(a)()};exports.BOLD_ITALIC_STAR=la;
21
+ "italic"],intraword:!1,tag:"___",type:"text-format"},na={format:["bold"],tag:"**",type:"text-format"},pa={format:["bold"],intraword:!1,tag:"__",type:"text-format"},qa={format:["strikethrough"],tag:"~~",type:"text-format"},ra={format:["italic"],tag:"*",type:"text-format"},sa={format:["italic"],intraword:!1,tag:"_",type:"text-format"},ta={export:(a,b,c)=>{if(!G.$isLinkNode(a))return null;b=`[${a.getTextContent()}](${a.getURL()})`;const d=a.getFirstChild();return 1===a.getChildrenSize()&&h.$isTextNode(d)?
22
+ c(d,b):b},importRegExp:/(?:\[([^[]+)\])(?:\(([^(]+)\))/,regExp:/(?:\[([^[]+)\])(?:\(([^(]+)\))$/,replace:(a,b)=>{const [,c,d]=b;b=G.$createLinkNode(d);const e=h.$createTextNode(c);e.setFormat(a.getFormat());b.append(e);a.replace(b)},trigger:")",type:"text-match"},ua=[V,W,X,Y,ja],va=[ka,la,ma,na,pa,ra,sa,qa],wa=[ta],Z=[...ua,...va,...wa];exports.$convertFromMarkdownString=function(a,b=Z){return ea(b)(a)};exports.$convertToMarkdownString=function(a=Z){return ba(a)()};exports.BOLD_ITALIC_STAR=la;
23
23
  exports.BOLD_ITALIC_UNDERSCORE=ma;exports.BOLD_STAR=na;exports.BOLD_UNDERSCORE=pa;exports.CHECK_LIST=ia;exports.CODE=X;exports.ELEMENT_TRANSFORMERS=ua;exports.HEADING=V;exports.INLINE_CODE=ka;exports.ITALIC_STAR=ra;exports.ITALIC_UNDERSCORE=sa;exports.LINK=ta;exports.ORDERED_LIST=ja;exports.QUOTE=W;exports.STRIKETHROUGH=qa;exports.TEXT_FORMAT_TRANSFORMERS=va;exports.TEXT_MATCH_TRANSFORMERS=wa;exports.TRANSFORMERS=Z;exports.UNORDERED_LIST=Y;
24
- exports.registerMarkdownShortcuts=function(a,b=Z){let c=I(b),d=H(c.textFormat,({tag:f})=>f[f.length-1]),e=H(c.textMatch,({trigger:f})=>f);return a.registerUpdateListener(({tags:f,dirtyLeaves:h,editorState:p,prevEditorState:r})=>{if(!f.has("historic")){var l=p.read(k.$getSelection);f=r.read(k.$getSelection);if(k.$isRangeSelection(f)&&k.$isRangeSelection(l)&&l.isCollapsed()){r=l.anchor.key;var x=l.anchor.offset,q=p._nodeMap.get(r);k.$isTextNode(q)&&h.has(r)&&(1===x||x===f.anchor.offset+1)&&a.update(()=>
25
- {if(!q.hasFormat("code")){var m=q.getParent();if(null!==m&&!y.$isCodeNode(m)){var v=l.anchor.offset;b:{var g=c.element,n=m.getParent();if(k.$isRootNode(n)&&m.getFirstChild()===q&&(n=q.getTextContent()," "===n[v-1]))for(let {regExp:B,replace:C}of g)if((g=n.match(B))&&g[0].length===v){n=q.getNextSiblings();let [D,oa]=q.splitText(v);D.remove();n=oa?[oa,...n]:n;C(m,n,g,!1);m=!0;break b}m=!1}if(!m){b:{g=q.getTextContent();m=e[g[v-1]];if(null!=m){v<g.length&&(g=g.slice(0,v));for(w of m)if(m=g.match(w.regExp),
26
- null!==m){g=m.index||0;n=g+m[0].length;var u=void 0;0===g?[u]=q.splitText(n):[,u]=q.splitText(g,n);u.selectNext();w.replace(u,m);var w=!0;break b}}w=!1}if(!w)b:{n=q.getTextContent();--v;var t=n[v];if(w=d[t])for(let B of w){var {tag:A}=B;w=A.length;let C=v-w+1;if(!(1<w&&!R(n,C,A,0,w)||" "===n[C-1])&&(u=n[v+1],!1!==B.intraword||!u||J.test(u))){m=u=q;g=Q(n,C,A);for(var z=m;0>g&&(z=z.getPreviousSibling())&&!k.$isLineBreakNode(z);)k.$isTextNode(z)&&(g=z.getTextContent(),m=z,g=Q(g,g.length,A));if(!(0>g||
27
- m===u&&g+w===C||(A=m.getTextContent(),0<g&&A[g-1]===t||(z=A[g-1],!1===B.intraword&&z&&!J.test(z))))){n=u.getTextContent();n=n.slice(0,C)+n.slice(v+1);u.setTextContent(n);n=m===u?n:A;m.setTextContent(n.slice(0,g)+n.slice(g+w));n=k.$getSelection();t=k.$createRangeSelection();k.$setSelection(t);v=v-w*(m===u?2:1)+1;t.anchor.set(m.__key,g,"text");t.focus.set(u.__key,v,"text");for(let D of B.format)t.hasFormat(D)||t.formatText(D);t.anchor.set(t.focus.key,t.focus.offset,t.focus.type);for(let D of B.format)t.hasFormat(D)&&
28
- t.toggleFormat(D);k.$isRangeSelection(n)&&(t.format=n.format);break b}}}}}}}})}}})}
24
+ exports.registerMarkdownShortcuts=function(a,b=Z){let c=I(b),d=H(c.textFormat,({tag:f})=>f[f.length-1]),e=H(c.textMatch,({trigger:f})=>f);return a.registerUpdateListener(({tags:f,dirtyLeaves:k,editorState:p,prevEditorState:r})=>{if(!f.has("historic")){var n=p.read(h.$getSelection);f=r.read(h.$getSelection);if(h.$isRangeSelection(f)&&h.$isRangeSelection(n)&&n.isCollapsed()){r=n.anchor.key;var t=n.anchor.offset,q=p._nodeMap.get(r);h.$isTextNode(q)&&k.has(r)&&(1===t||t===f.anchor.offset+1)&&a.update(()=>
25
+ {if(!q.hasFormat("code")){var l=q.getParent();if(null!==l&&!y.$isCodeNode(l)){var w=n.anchor.offset;b:{var g=c.element,m=l.getParent();if(h.$isRootNode(m)&&l.getFirstChild()===q&&(m=q.getTextContent()," "===m[w-1]))for(let {regExp:B,replace:C}of g)if((g=m.match(B))&&g[0].length===w){m=q.getNextSiblings();let [D,oa]=q.splitText(w);D.remove();m=oa?[oa,...m]:m;C(l,m,g,!1);l=!0;break b}l=!1}if(!l){b:{g=q.getTextContent();l=e[g[w-1]];if(null!=l){w<g.length&&(g=g.slice(0,w));for(x of l)if(l=g.match(x.regExp),
26
+ null!==l){g=l.index||0;m=g+l[0].length;var v=void 0;0===g?[v]=q.splitText(m):[,v]=q.splitText(g,m);v.selectNext(0,0);x.replace(v,l);var x=!0;break b}}x=!1}if(!x)b:{m=q.getTextContent();--w;var u=m[w];if(x=d[u])for(let B of x){var {tag:A}=B;x=A.length;let C=w-x+1;if(!(1<x&&!R(m,C,A,0,x)||" "===m[C-1])&&(v=m[w+1],!1!==B.intraword||!v||J.test(v))){l=v=q;g=Q(m,C,A);for(var z=l;0>g&&(z=z.getPreviousSibling())&&!h.$isLineBreakNode(z);)h.$isTextNode(z)&&(g=z.getTextContent(),l=z,g=Q(g,g.length,A));if(!(0>
27
+ g||l===v&&g+x===C||(A=l.getTextContent(),0<g&&A[g-1]===u||(z=A[g-1],!1===B.intraword&&z&&!J.test(z))))){m=v.getTextContent();m=m.slice(0,C)+m.slice(w+1);v.setTextContent(m);m=l===v?m:A;l.setTextContent(m.slice(0,g)+m.slice(g+x));m=h.$getSelection();u=h.$createRangeSelection();h.$setSelection(u);w=w-x*(l===v?2:1)+1;u.anchor.set(l.__key,g,"text");u.focus.set(v.__key,w,"text");for(let D of B.format)u.hasFormat(D)||u.formatText(D);u.anchor.set(u.focus.key,u.focus.offset,u.focus.type);for(let D of B.format)u.hasFormat(D)&&
28
+ u.toggleFormat(D);h.$isRangeSelection(m)&&(u.format=m.format);break b}}}}}}}})}}})}
File without changes
File without changes
package/index.d.ts CHANGED
@@ -5,9 +5,9 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  *
7
7
  */
8
- import type { ElementTransformer, TextFormatTransformer, TextMatchTransformer, Transformer } from './v2/MarkdownTransformers';
9
- import { registerMarkdownShortcuts } from './v2/MarkdownShortcuts';
10
- import { BOLD_ITALIC_STAR, BOLD_ITALIC_UNDERSCORE, BOLD_STAR, BOLD_UNDERSCORE, CHECK_LIST, CODE, HEADING, INLINE_CODE, ITALIC_STAR, ITALIC_UNDERSCORE, LINK, ORDERED_LIST, QUOTE, STRIKETHROUGH, UNORDERED_LIST } from './v2/MarkdownTransformers';
8
+ import type { ElementTransformer, TextFormatTransformer, TextMatchTransformer, Transformer } from './MarkdownTransformers';
9
+ import { registerMarkdownShortcuts } from './MarkdownShortcuts';
10
+ import { BOLD_ITALIC_STAR, BOLD_ITALIC_UNDERSCORE, BOLD_STAR, BOLD_UNDERSCORE, CHECK_LIST, CODE, HEADING, INLINE_CODE, ITALIC_STAR, ITALIC_UNDERSCORE, LINK, ORDERED_LIST, QUOTE, STRIKETHROUGH, UNORDERED_LIST } from './MarkdownTransformers';
11
11
  declare const ELEMENT_TRANSFORMERS: Array<ElementTransformer>;
12
12
  declare const TEXT_FORMAT_TRANSFORMERS: Array<TextFormatTransformer>;
13
13
  declare const TEXT_MATCH_TRANSFORMERS: Array<TextMatchTransformer>;
package/package.json CHANGED
@@ -8,18 +8,18 @@
8
8
  "markdown"
9
9
  ],
10
10
  "license": "MIT",
11
- "version": "0.3.7",
11
+ "version": "0.3.10",
12
12
  "main": "LexicalMarkdown.js",
13
13
  "peerDependencies": {
14
- "lexical": "0.3.7"
14
+ "lexical": "0.3.10"
15
15
  },
16
16
  "dependencies": {
17
- "@lexical/utils": "0.3.7",
18
- "@lexical/code": "0.3.7",
19
- "@lexical/text": "0.3.7",
20
- "@lexical/rich-text": "0.3.7",
21
- "@lexical/list": "0.3.7",
22
- "@lexical/link": "0.3.7"
17
+ "@lexical/utils": "0.3.10",
18
+ "@lexical/code": "0.3.10",
19
+ "@lexical/text": "0.3.10",
20
+ "@lexical/rich-text": "0.3.10",
21
+ "@lexical/list": "0.3.10",
22
+ "@lexical/link": "0.3.10"
23
23
  },
24
24
  "repository": {
25
25
  "type": "git",
package/utils.d.ts CHANGED
@@ -5,32 +5,11 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  *
7
7
  */
8
- import type { TextNodeWithOffset } from '@lexical/text';
9
- import type { DecoratorNode, ElementNode, LexicalEditor, LexicalNode, NodeKey, TextFormatType } from 'lexical';
10
- export declare type AutoFormatTriggerState = Readonly<{
11
- anchorOffset: number;
12
- hasParentNode: boolean;
13
- isCodeBlock: boolean;
14
- isParentAListItemNode: boolean;
15
- isSelectionCollapsed: boolean;
16
- isSimpleText: boolean;
17
- nodeKey: NodeKey;
18
- textContent: string;
19
- }>;
20
- export declare type MarkdownFormatKind = 'noTransformation' | 'paragraphH1' | 'paragraphH2' | 'paragraphH3' | 'paragraphH4' | 'paragraphH5' | 'paragraphH6' | 'paragraphBlockQuote' | 'paragraphUnorderedList' | 'paragraphOrderedList' | 'paragraphCodeBlock' | 'horizontalRule' | 'bold' | 'code' | 'italic' | 'underline' | 'strikethrough' | 'italic_bold' | 'strikethrough_italic' | 'strikethrough_bold' | 'strikethrough_italic_bold' | 'link';
21
- export declare type ScanningContext = {
22
- currentElementNode: null | ElementNode;
23
- editor: LexicalEditor;
24
- isAutoFormatting: boolean;
25
- isWithinCodeBlock: boolean;
26
- joinedText: string | null | undefined;
27
- markdownCriteria: MarkdownCriteria;
28
- patternMatchResults: PatternMatchResults;
29
- textNodeWithOffset: TextNodeWithOffset | null | undefined;
30
- triggerState: AutoFormatTriggerState | null | undefined;
31
- };
32
- export declare type MarkdownCriteria = Readonly<{
33
- export?: (node: LexicalNode, traverseChildren: (node: ElementNode) => string) => string | null;
8
+ import type { ElementTransformer, TextFormatTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';
9
+ import type { ElementNode, LexicalNode, TextFormatType } from 'lexical';
10
+ declare type MarkdownFormatKind = 'noTransformation' | 'paragraphH1' | 'paragraphH2' | 'paragraphH3' | 'paragraphH4' | 'paragraphH5' | 'paragraphH6' | 'paragraphBlockQuote' | 'paragraphUnorderedList' | 'paragraphOrderedList' | 'paragraphCodeBlock' | 'horizontalRule' | 'bold' | 'code' | 'italic' | 'underline' | 'strikethrough' | 'italic_bold' | 'strikethrough_italic' | 'strikethrough_bold' | 'strikethrough_italic_bold' | 'link';
11
+ declare type MarkdownCriteria = Readonly<{
12
+ export?: (node: LexicalNode, traverseChildren: (elementNode: ElementNode) => string) => string | null;
34
13
  exportFormat?: TextFormatType;
35
14
  exportTag?: string;
36
15
  exportTagClose?: string;
@@ -39,36 +18,14 @@ export declare type MarkdownCriteria = Readonly<{
39
18
  regExForAutoFormatting: RegExp;
40
19
  requiresParagraphStart: boolean | null | undefined;
41
20
  }>;
42
- declare type CaptureGroupDetail = {
43
- offsetInParent: number;
44
- text: string;
45
- };
46
- export declare type PatternMatchResults = {
47
- regExCaptureGroups: Array<CaptureGroupDetail>;
48
- };
49
- export declare type MarkdownCriteriaWithPatternMatchResults = {
50
- markdownCriteria: null | MarkdownCriteria;
51
- patternMatchResults: null | PatternMatchResults;
52
- };
53
- export declare type MarkdownCriteriaArray = Array<MarkdownCriteria>;
54
- export declare type AutoFormatTriggerKind = 'space_trigger' | 'codeBlock_trigger';
55
- export declare type AutoFormatTrigger = {
56
- triggerKind: AutoFormatTriggerKind;
57
- triggerString: string;
58
- };
59
- export declare const triggers: Array<AutoFormatTrigger>;
60
- export declare const allMarkdownCriteria: MarkdownCriteriaArray;
61
- export declare function getAllTriggers(): Array<AutoFormatTrigger>;
21
+ declare type MarkdownCriteriaArray = Array<MarkdownCriteria>;
62
22
  export declare function getAllMarkdownCriteriaForParagraphs(): MarkdownCriteriaArray;
63
23
  export declare function getAllMarkdownCriteriaForTextNodes(): MarkdownCriteriaArray;
64
- export declare function getAllMarkdownCriteria(): MarkdownCriteriaArray;
65
- export declare function getInitialScanningContext(editor: LexicalEditor, isAutoFormatting: boolean, textNodeWithOffset: null | TextNodeWithOffset, triggerState: null | AutoFormatTriggerState): ScanningContext;
66
- export declare function resetScanningContext(scanningContext: ScanningContext): ScanningContext;
67
- export declare function getCodeBlockCriteria(): MarkdownCriteria;
68
- export declare function getPatternMatchResultsForCriteria(markdownCriteria: MarkdownCriteria, scanningContext: ScanningContext, parentElementNode: ElementNode): null | PatternMatchResults;
69
- export declare function getPatternMatchResultsForCodeBlock(scanningContext: ScanningContext, text: string): null | PatternMatchResults;
70
- export declare function hasPatternMatchResults(scanningContext: ScanningContext): boolean;
71
- export declare function getTextNodeWithOffsetOrThrow(scanningContext: ScanningContext): TextNodeWithOffset;
72
- export declare function transformTextNodeForMarkdownCriteria<T>(scanningContext: ScanningContext, elementNode: ElementNode, createHorizontalRuleNode: null | (() => DecoratorNode<T>)): void;
73
- export declare function getParentElementNodeOrThrow(scanningContext: ScanningContext): ElementNode;
24
+ export declare function indexBy<T>(list: Array<T>, callback: (arg0: T) => string): Readonly<Record<string, Array<T>>>;
25
+ export declare function transformersByType(transformers: Array<Transformer>): Readonly<{
26
+ element: Array<ElementTransformer>;
27
+ textFormat: Array<TextFormatTransformer>;
28
+ textMatch: Array<TextMatchTransformer>;
29
+ }>;
30
+ export declare const PUNCTUATION_OR_SPACE: RegExp;
74
31
  export {};
@@ -1,12 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
- import type { AutoFormatTriggerState, ScanningContext } from './utils';
9
- import type { DecoratorNode, EditorState, LexicalEditor } from 'lexical';
10
- export declare function updateAutoFormatting<T>(editor: LexicalEditor, scanningContext: ScanningContext, createHorizontalRuleNode: () => DecoratorNode<T>): void;
11
- export declare function getTriggerState(editorState: EditorState): null | AutoFormatTriggerState;
12
- export declare function findScanningContext(editor: LexicalEditor, currentTriggerState: null | AutoFormatTriggerState, priorTriggerState: null | AutoFormatTriggerState): null | ScanningContext;
@@ -1,10 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
- import type { DecoratorNode, LexicalEditor, RootNode } from 'lexical';
9
- export declare function convertStringToLexical(text: string, editor: LexicalEditor): null | RootNode;
10
- export declare function convertMarkdownForElementNodes<T>(editor: LexicalEditor, createHorizontalRuleNode: null | (() => DecoratorNode<T>)): void;
package/v2/utils.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /**
2
- * Copyright (c) Meta Platforms, Inc. and affiliates.
3
- *
4
- * This source code is licensed under the MIT license found in the
5
- * LICENSE file in the root directory of this source tree.
6
- *
7
- */
8
- import type { ElementTransformer, TextFormatTransformer, TextMatchTransformer, Transformer } from '@lexical/markdown';
9
- export declare function indexBy<T>(list: Array<T>, callback: (arg0: T) => string): Readonly<Record<string, Array<T>>>;
10
- export declare function transformersByType(transformers: Array<Transformer>): Readonly<{
11
- element: Array<ElementTransformer>;
12
- textFormat: Array<TextFormatTransformer>;
13
- textMatch: Array<TextMatchTransformer>;
14
- }>;
15
- export declare const PUNCTUATION_OR_SPACE: RegExp;