@lexical/code 0.1.17

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/LexicalCode.js ADDED
@@ -0,0 +1,9 @@
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
+ 'use strict'
8
+ const LexicalCode = process.env.NODE_ENV === 'development' ? require('./LexicalCode.dev.js') : require('./LexicalCode.prod.js')
9
+ module.exports = LexicalCode;
@@ -0,0 +1,74 @@
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
+ * @flow strict
8
+ */
9
+
10
+ import type {
11
+ EditorConfig,
12
+ LexicalNode,
13
+ NodeKey,
14
+ ParagraphNode,
15
+ RangeSelection,
16
+ EditorThemeClasses,
17
+ } from 'lexical';
18
+
19
+ import {ElementNode} from 'lexical';
20
+
21
+ declare export class CodeNode extends ElementNode {
22
+ static getType(): string;
23
+ static clone(node: CodeNode): CodeNode;
24
+ constructor(key?: NodeKey): void;
25
+ createDOM<EditorContext>(config: EditorConfig<EditorContext>): HTMLElement;
26
+ updateDOM(prevNode: CodeNode, dom: HTMLElement): boolean;
27
+ insertNewAfter(
28
+ selection: RangeSelection,
29
+ ): null | ParagraphNode | CodeHighlightNode;
30
+ canInsertTab(): true;
31
+ collapseAtStart(): true;
32
+ setLanguage(language: string): void;
33
+ getLanguage(): string | void;
34
+ }
35
+ declare export function $createCodeNode(): CodeNode;
36
+ declare export function $isCodeNode(
37
+ node: ?LexicalNode,
38
+ ): boolean %checks(node instanceof CodeNode);
39
+
40
+ declare export function getFirstCodeHighlightNodeOfLine(
41
+ anchor: LexicalNode,
42
+ ): ?CodeHighlightNode;
43
+
44
+ declare export function getLastCodeHighlightNodeOfLine(
45
+ anchor: LexicalNode,
46
+ ): ?CodeHighlightNode;
47
+
48
+ import {TextNode} from 'lexical';
49
+
50
+ declare export class CodeHighlightNode extends TextNode {
51
+ __highlightType: ?string;
52
+ constructor(text: string, highlightType?: string, key?: NodeKey): void;
53
+ static getType(): string;
54
+ static clone(node: CodeHighlightNode): CodeHighlightNode;
55
+ createDOM<EditorContext>(config: EditorConfig<EditorContext>): HTMLElement;
56
+ updateDOM<EditorContext>(
57
+ // $FlowFixMe
58
+ prevNode: CodeHighlightNode,
59
+ dom: HTMLElement,
60
+ config: EditorConfig<EditorContext>,
61
+ ): boolean;
62
+ setFormat(format: number): this;
63
+ }
64
+ declare function getHighlightThemeClass(
65
+ theme: EditorThemeClasses,
66
+ highlightType: ?string,
67
+ ): ?string;
68
+ declare export function $createCodeHighlightNode(
69
+ text: string,
70
+ highlightType?: string,
71
+ ): CodeHighlightNode;
72
+ declare export function $isCodeHighlightNode(
73
+ node: ?LexicalNode,
74
+ ): boolean %checks(node instanceof CodeHighlightNode);
@@ -0,0 +1,44 @@
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
+ MIT <https://opensource.org/licenses/MIT>
9
+ @author Lea Verou <https://lea.verou.me>
10
+ @namespace
11
+ @public
12
+ */
13
+ var n=require("@lexical/utils"),L=require("lexical"),aa="undefined"!==typeof globalThis?globalThis:"undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:{},ba={exports:{}};
14
+ (function(a){var c=function(b){function k(u,q,h,d){this.type=u;this.content=q;this.alias=h;this.length=(d||"").length|0}function x(u,q,h,d){u.lastIndex=q;(u=u.exec(h))&&d&&u[1]&&(d=u[1].length,u.index+=d,u[0]=u[0].slice(d));return u}function B(u,q,h,d,e,f){for(var l in h)if(h.hasOwnProperty(l)&&h[l]){var t=h[l];t=Array.isArray(t)?t:[t];for(var r=0;r<t.length;++r){if(f&&f.cause==l+","+r)return;var m=t[r],p=m.inside,I=!!m.lookbehind,U=!!m.greedy,oa=m.alias;if(U&&!m.pattern.global){var J=m.pattern.toString().match(/[imsuy]*$/)[0];
15
+ m.pattern=RegExp(m.pattern.source,J+"g")}m=m.pattern||m;var v=d.next;for(J=e;v!==q.tail&&!(f&&J>=f.reach);J+=v.value.length,v=v.next){var K=v.value;if(q.length>u.length)return;if(!(K instanceof k)){var M=1;if(U){var A=x(m,J,u,I);if(!A)break;var E=A.index;K=A.index+A[0].length;var C=J;for(C+=v.value.length;E>=C;)v=v.next,C+=v.value.length;J=C-=v.value.length;if(v.value instanceof k)continue;for(E=v;E!==q.tail&&(C<K||"string"===typeof E.value);E=E.next)M++,C+=E.value.length;M--;K=u.slice(J,C);A.index-=
16
+ J}else if(A=x(m,0,K,I),!A)continue;E=A.index;A=A[0];C=K.slice(0,E);E=K.slice(E+A.length);K=J+K.length;f&&K>f.reach&&(f.reach=K);v=v.prev;C&&(v=D(q,v,C),J+=C.length);C=q;for(var W=v,R=W.next,X=0;X<M&&R!==C.tail;X++)R=R.next;W.next=R;R.prev=W;C.length-=X;A=new k(l,p?g.tokenize(A,p):A,oa,A);v=D(q,v,A);E&&D(q,v,E);1<M&&(M={cause:l+","+r,reach:K},B(u,q,h,v.prev,J,M),f&&M.reach>f.reach&&(f.reach=M.reach))}}}}}function F(){var u={value:null,prev:null,next:null},q={value:null,prev:u,next:null};u.next=q;this.head=
17
+ u;this.tail=q;this.length=0}function D(u,q,h){var d=q.next;h={value:h,prev:q,next:d};q.next=h;d.prev=h;u.length++;return h}function y(){g.manual||g.highlightAll()}var w=/\blang(?:uage)?-([\w-]+)\b/i,G=0,z={},g={manual:b.Prism&&b.Prism.manual,disableWorkerMessageHandler:b.Prism&&b.Prism.disableWorkerMessageHandler,util:{encode:function h(q){return q instanceof k?new k(q.type,h(q.content),q.alias):Array.isArray(q)?q.map(h):q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(q){return Object.prototype.toString.call(q).slice(8,
18
+ -1)},objId:function(q){q.__id||Object.defineProperty(q,"__id",{value:++G});return q.__id},clone:function e(h,d){d=d||{};switch(g.util.type(h)){case "Object":var f=g.util.objId(h);if(d[f])return d[f];var l={};d[f]=l;for(var t in h)h.hasOwnProperty(t)&&(l[t]=e(h[t],d));return l;case "Array":f=g.util.objId(h);if(d[f])return d[f];l=[];d[f]=l;h.forEach(function(r,m){l[m]=e(r,d)});return l;default:return h}},getLanguage:function(h){for(;h&&!w.test(h.className);)h=h.parentElement;return h?(h.className.match(w)||
19
+ [,"none"])[1].toLowerCase():"none"},currentScript:function(){if("undefined"===typeof document)return null;if("currentScript"in document)return document.currentScript;try{throw Error();}catch(f){var h=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(f.stack)||[])[1];if(h){var d=document.getElementsByTagName("script"),e;for(e in d)if(d[e].src==h)return d[e]}return null}},isActive:function(h,d,e){for(var f="no-"+d;h;){var l=h.classList;if(l.contains(d))return!0;if(l.contains(f))return!1;h=h.parentElement}return!!e}},
20
+ languages:{plain:z,plaintext:z,text:z,txt:z,extend:function(h,d){h=g.util.clone(g.languages[h]);for(var e in d)h[e]=d[e];return h},insertBefore:function(h,d,e,f){f=f||g.languages;var l=f[h],t={},r;for(r in l)if(l.hasOwnProperty(r)){if(r==d)for(var m in e)e.hasOwnProperty(m)&&(t[m]=e[m]);e.hasOwnProperty(r)||(t[r]=l[r])}var p=f[h];f[h]=t;g.languages.DFS(g.languages,function(I,U){U===p&&I!=h&&(this[I]=t)});return t},DFS:function t(d,e,f,l){l=l||{};var r=g.util.objId,m;for(m in d)if(d.hasOwnProperty(m)){e.call(d,
21
+ m,d[m],f||m);var p=d[m],I=g.util.type(p);"Object"!==I||l[r(p)]?"Array"!==I||l[r(p)]||(l[r(p)]=!0,t(p,e,m,l)):(l[r(p)]=!0,t(p,e,null,l))}}},plugins:{},highlightAll:function(d,e){g.highlightAllUnder(document,d,e)},highlightAllUnder:function(d,e,f){d={callback:f,container:d,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};g.hooks.run("before-highlightall",d);d.elements=Array.prototype.slice.apply(d.container.querySelectorAll(d.selector));g.hooks.run("before-all-elements-highlight",
22
+ d);f=0;for(var l;l=d.elements[f++];)g.highlightElement(l,!0===e,d.callback)},highlightElement:function(d,e,f){function l(I){p.highlightedCode=I;g.hooks.run("before-insert",p);p.element.innerHTML=p.highlightedCode;g.hooks.run("after-highlight",p);g.hooks.run("complete",p);f&&f.call(p.element)}var t=g.util.getLanguage(d),r=g.languages[t];d.className=d.className.replace(w,"").replace(/\s+/g," ")+" language-"+t;var m=d.parentElement;m&&"pre"===m.nodeName.toLowerCase()&&(m.className=m.className.replace(w,
23
+ "").replace(/\s+/g," ")+" language-"+t);var p={element:d,language:t,grammar:r,code:d.textContent};g.hooks.run("before-sanity-check",p);(m=p.element.parentElement)&&"pre"===m.nodeName.toLowerCase()&&!m.hasAttribute("tabindex")&&m.setAttribute("tabindex","0");p.code?(g.hooks.run("before-highlight",p),p.grammar?e&&b.Worker?(d=new Worker(g.filename),d.onmessage=function(I){l(I.data)},d.postMessage(JSON.stringify({language:p.language,code:p.code,immediateClose:!0}))):l(g.highlight(p.code,p.grammar,p.language)):
24
+ l(g.util.encode(p.code))):(g.hooks.run("complete",p),f&&f.call(p.element))},highlight:function(d,e,f){d={code:d,grammar:e,language:f};g.hooks.run("before-tokenize",d);d.tokens=g.tokenize(d.code,d.grammar);g.hooks.run("after-tokenize",d);return k.stringify(g.util.encode(d.tokens),d.language)},tokenize:function(d,e){var f=e.rest;if(f){for(var l in f)e[l]=f[l];delete e.rest}f=new F;D(f,f.head,d);B(d,f,e,f.head,0);d=[];for(e=f.head.next;e!==f.tail;)d.push(e.value),e=e.next;return d},hooks:{all:{},add:function(d,
25
+ e){var f=g.hooks.all;f[d]=f[d]||[];f[d].push(e)},run:function(d,e){if((d=g.hooks.all[d])&&d.length)for(var f=0,l;l=d[f++];)l(e)}},Token:k};b.Prism=g;k.stringify=function l(e,f){if("string"==typeof e)return e;if(Array.isArray(e)){var t="";e.forEach(function(p){t+=l(p,f)});return t}var r={type:e.type,content:l(e.content,f),tag:"span",classes:["token",e.type],attributes:{},language:f};(e=e.alias)&&(Array.isArray(e)?Array.prototype.push.apply(r.classes,e):r.classes.push(e));g.hooks.run("wrap",r);e="";
26
+ for(var m in r.attributes)e+=" "+m+'="'+(r.attributes[m]||"").replace(/"/g,"&quot;")+'"';return"<"+r.tag+' class="'+r.classes.join(" ")+'"'+e+">"+r.content+"</"+r.tag+">"};if(!b.document){if(!b.addEventListener)return g;g.disableWorkerMessageHandler||b.addEventListener("message",function(e){e=JSON.parse(e.data);var f=e.language,l=e.immediateClose;b.postMessage(g.highlight(e.code,g.languages[f],f));l&&b.close()},!1);return g}if(z=g.util.currentScript())g.filename=z.src,z.hasAttribute("data-manual")&&
27
+ (g.manual=!0);if(!g.manual){var H=document.readyState;"loading"===H||"interactive"===H&&z&&z.defer?document.addEventListener("DOMContentLoaded",y):window.requestAnimationFrame?window.requestAnimationFrame(y):window.setTimeout(y,16)}return g}("undefined"!==typeof window?window:"undefined"!==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{});a.exports&&(a.exports=c);"undefined"!==typeof aa&&(aa.Prism=c)})(ba);var N=ba.exports;
28
+ class O extends L.TextNode{constructor(a,c,b){super(a,b);this.__highlightType=c}static getType(){return"code-highlight"}static clone(a){return new O(a.__text,a.__highlightType||void 0,a.__key)}createDOM(a){const c=super.createDOM(a);a=P(a.theme,this.__highlightType);n.addClassNamesToElement(c,a);return c}updateDOM(a,c,b){const k=super.updateDOM(a,c,b);a=P(b.theme,a.__highlightType);b=P(b.theme,this.__highlightType);a!==b&&(a&&n.removeClassNamesFromElement(c,a),b&&n.addClassNamesToElement(c,b));return k}setFormat(){return this.getWritable()}}
29
+ function P(a,c){return c&&a&&a.codeHighlight&&a.codeHighlight[c]}function Q(a,c){return new O(a,c)}function S(a){return a instanceof O}
30
+ class T extends L.ElementNode{static getType(){return"code"}static clone(a){return new T(a.__language,a.__key)}constructor(a,c){super(c);this.__language=a}createDOM(a){const c=document.createElement("code");n.addClassNamesToElement(c,a.theme.code);c.setAttribute("spellcheck","false");return c}updateDOM(){return!1}static convertDOM(){return{div:()=>({conversion:ca,priority:1}),pre:()=>({conversion:da,priority:0}),table:a=>V(a)?{conversion:ea,priority:4}:null,td:a=>{const c=a.closest("table");return a.classList.contains("js-file-line")?
31
+ {conversion:fa,priority:4}:c&&V(c)?{conversion:ha,priority:4}:null},tr:a=>(a=a.closest("table"))&&V(a)?{conversion:ha,priority:4}:null}}insertNewAfter(a){var c=this.getChildren(),b=c.length;if(2<=b&&"\n"===c[b-1].getTextContent()&&"\n"===c[b-2].getTextContent()&&a.isCollapsed()&&a.anchor.key===this.__key&&a.anchor.offset===b)return c[b-1].remove(),c[b-2].remove(),a=L.$createParagraphNode(),this.insertAfter(a),a;c=a.anchor.getNode();var k=Y(c);if(null!=k){b=0;for(k=k.getTextContent();b<k.length&&/[\t ]/.test(k[b]);)b+=
32
+ 1;if(0<b)return b=k.substring(0,b),b=Q(b),c.insertAfter(b),a.insertNodes([L.$createLineBreakNode()]),b.select(),b}return null}canInsertTab(){return!0}collapseAtStart(){const a=L.$createParagraphNode();this.getChildren().forEach(c=>a.append(c));this.replace(a);return!0}setLanguage(a){this.getWritable().__language=a}getLanguage(){return this.getLatest().__language}}function Z(a){return new T(a)}function ia(a){return a instanceof T}
33
+ function Y(a){let c=null;const b=a.getPreviousSiblings();for(b.push(a);0<b.length&&(a=b.pop(),S(a)&&(c=a),!L.$isLineBreakNode(a)););return c}function ja(a){let c=null;const b=a.getNextSiblings();for(b.unshift(a);0<b.length&&(a=b.shift(),S(a)&&(c=a),!L.$isLineBreakNode(a)););return c}function da(){return{node:Z()}}function ca(a){return{after:c=>{const b=a.parentNode;null!=b&&a!==b.lastChild&&c.push(L.$createLineBreakNode());return c},node:null!==a.style.fontFamily.match("monospace")?Z():null}}
34
+ function ea(){return{node:Z()}}function ha(){return{node:null}}function fa(a){return{after:c=>{a.parentNode&&a.parentNode.nextSibling&&c.push(L.$createLineBreakNode());return c},node:null}}function V(a){return a.classList.contains("js-file-line-container")}function ka(a,c){const b=a.getParent();ia(b)?la(b,c):S(a)&&a.replace(L.$createTextNode(a.__text))}let ma=!1;
35
+ function la(a,c){ma||(ma=!0,c.update(()=>{void 0===a.getLanguage()&&a.setLanguage("javascript");na(a,()=>{var b=a.getTextContent();b=N.tokenize(b,N.languages[a.getLanguage()||""]||N.languages.javascript);b=pa(b);var k=a.getChildren();let x=0;for(;x<k.length&&qa(k[x],b[x]);)x++;var B=k.length;const F=b.length,D=Math.min(B,F)-x;let y=0;for(;y<D;)if(y++,!qa(k[B-y],b[F-y])){y--;break}k=x;B-=y;b=b.slice(x,F-y);const {from:w,to:G,nodesForReplacement:z}={from:k,nodesForReplacement:b,to:B};return w!==G||
36
+ z.length?(a.splice(w,G-w,z),!0):!1})},{onUpdate:()=>{ma=!1},skipTransforms:!0}))}function pa(a){const c=[];a.forEach(b=>{if("string"===typeof b){b=b.split("\n");for(var k=0;k<b.length;k++){const x=b[k];x.length&&c.push(Q(x));k<b.length-1&&c.push(L.$createLineBreakNode())}}else({content:k}=b),"string"===typeof k?c.push(Q(k,b.type)):1===k.length&&"string"===typeof k[0]?c.push(Q(k[0],b.type)):c.push(...pa(k))});return c}
37
+ function na(a,c){var b=L.$getSelection();if(L.$isRangeSelection(b)&&b.anchor){b=b.anchor;var k=b.offset,x="element"===b.type&&L.$isLineBreakNode(a.getChildAtIndex(b.offset-1)),B=0;if(!x){const F=b.getNode();B=k+F.getPreviousSiblings().reduce((D,y)=>D+(L.$isLineBreakNode(y)?0:y.getTextContentSize()),0)}c()&&(x?b.getNode().select(k,k):a.getChildren().some(F=>{if(L.$isTextNode(F)){const D=F.getTextContentSize();if(D>=B)return F.select(B,B),!0;B-=D}return!1}))}}
38
+ function qa(a,c){return S(a)&&S(c)?a.__text===c.__text&&a.__highlightType===c.__highlightType:L.$isLineBreakNode(a)&&L.$isLineBreakNode(c)?!0:!1}function ra(a){var c=L.$getSelection();if(!L.$isRangeSelection(c)||c.isCollapsed())return!1;c=c.getNodes();for(var b=0;b<c.length;b++){var k=c[b];if(!S(k)&&!L.$isLineBreakNode(k))return!1}b=Y(c[0]);null!=b&&sa(b,a);for(b=1;b<c.length;b++)k=c[b],L.$isLineBreakNode(c[b-1])&&S(k)&&sa(k,a);return!0}
39
+ function sa(a,c){const b=a.getTextContent();c===L.INDENT_CONTENT_COMMAND?0<b.length&&/\s/.test(b[0])?a.setTextContent("\t"+b):(c=Q("\t"),a.insertBefore(c)):0===b.indexOf("\t")&&(1===b.length?a.remove():a.setTextContent(b.substring(1)))}
40
+ function ta(a,c){const b=L.$getSelection();if(!c.altKey||!L.$isRangeSelection(b))return!1;const {anchor:k,focus:x}=b,B=k.offset,F=x.offset,D=k.getNode(),y=x.getNode();if(!S(D)||!S(y))return!1;var w=Y(D),G=ja(y);if(null==w||null==G)return!1;const z=w.getNodesBetween(G);for(let H=0;H<z.length;H++){const u=z[H];if(!S(u)&&!L.$isLineBreakNode(u))return!1}c.preventDefault();c.stopPropagation();w=(c=a===L.KEY_ARROW_UP_COMMAND)?w.getPreviousSibling():G.getNextSibling();if(!L.$isLineBreakNode(w))return!0;
41
+ G=c?w.getPreviousSibling():w.getNextSibling();if(null==G)return!0;c=c?Y(G):ja(G);let g=null!=c?c:G;w.remove();z.forEach(H=>H.remove());a===L.KEY_ARROW_UP_COMMAND?(z.forEach(H=>g.insertBefore(H)),g.insertBefore(w)):(g.insertAfter(w),g=w,z.forEach(H=>{g.insertAfter(H);g=H}));b.setTextNodeRange(D,B,y,F);return!0}exports.$createCodeHighlightNode=Q;exports.$createCodeNode=Z;exports.$isCodeHighlightNode=S;exports.$isCodeNode=ia;exports.CodeHighlightNode=O;exports.CodeNode=T;
42
+ exports.getCodeLanguages=()=>Object.keys(N.languages).filter(a=>"function"!==typeof N.languages[a]).sort();exports.getDefaultCodeLanguage=()=>"javascript";exports.getFirstCodeHighlightNodeOfLine=Y;exports.getLastCodeHighlightNodeOfLine=ja;
43
+ exports.registerCodeHighlighting=function(a){if(!a.hasNodes([T,O]))throw Error("CodeHighlightPlugin: CodeNode or CodeHighlightNode not registered on editor");return n.mergeRegister(a.registerNodeTransform(T,c=>la(c,a)),a.registerNodeTransform(L.TextNode,c=>ka(c,a)),a.registerNodeTransform(O,c=>ka(c,a)),a.registerCommand(L.INDENT_CONTENT_COMMAND,()=>ra(L.INDENT_CONTENT_COMMAND),1),a.registerCommand(L.OUTDENT_CONTENT_COMMAND,()=>ra(L.OUTDENT_CONTENT_COMMAND),1),a.registerCommand(L.KEY_ARROW_UP_COMMAND,
44
+ c=>ta(L.KEY_ARROW_UP_COMMAND,c),1),a.registerCommand(L.KEY_ARROW_DOWN_COMMAND,c=>ta(L.KEY_ARROW_DOWN_COMMAND,c),1))};
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # `@lexical/code`
2
+
3
+ This package contains the functionality for the code blocks and code highlighting for Lexical.
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@lexical/code",
3
+ "description": "This package contains the functionality for the code blocks and code highlighting for Lexical.",
4
+ "keywords": [
5
+ "lexical",
6
+ "editor",
7
+ "rich-text",
8
+ "code"
9
+ ],
10
+ "license": "MIT",
11
+ "version": "0.1.17",
12
+ "main": "LexicalCode.js",
13
+ "peerDependencies": {
14
+ "lexical": "0.1.17"
15
+ },
16
+ "dependencies": {
17
+ "@lexical/utils": "0.1.17",
18
+ "prismjs": "^1.25.0"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "https://github.com/facebook/lexical",
23
+ "directory": "packages/lexical-cod"
24
+ }
25
+ }