Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

chore: improve tables (#4491)

Wolf Mermelsteinf2850545df66
diff --git a/apps/web/patches/@lexical%[email protected] b/apps/web/patches/@lexical%[email protected]
new file mode 100644
index 0000000000..25cbff7722
--- /dev/null
+++ b/apps/web/patches/@lexical%[email protected]
@@ -0,0 +1,59 @@
+diff --git a/dist/LexicalTable.dev.js b/dist/LexicalTable.dev.js
+index ff5036056810b607f6c1f6c7ae47b7061d4e5026..9156aa39f3607a641aa51adc675ed58010b134ed 100644
+--- a/dist/LexicalTable.dev.js
++++ b/dist/LexicalTable.dev.js
+@@ -2239,8 +2239,6 @@ class TableObserver {
+ selectedNodes.forEach(cellNode => {
+ if (lexical.$isElementNode(cellNode)) {
+ const paragraphNode = lexical.$createParagraphNode();
+- const textNode = lexical.$createTextNode();
+- paragraphNode.append(textNode);
+ cellNode.append(paragraphNode);
+ cellNode.getChildren().forEach(child => {
+ if (child !== paragraphNode) {
+diff --git a/dist/LexicalTable.dev.mjs b/dist/LexicalTable.dev.mjs
+index 6685bb15967b1a476e575d02578552e446836559..ae79bfd1d1756c781fe36232ba903f1d2a17843e 100644
+--- a/dist/LexicalTable.dev.mjs
++++ b/dist/LexicalTable.dev.mjs
+@@ -2237,8 +2237,6 @@ class TableObserver {
+ selectedNodes.forEach(cellNode => {
+ if ($isElementNode(cellNode)) {
+ const paragraphNode = $createParagraphNode();
+- const textNode = $createTextNode();
+- paragraphNode.append(textNode);
+ cellNode.append(paragraphNode);
+ cellNode.getChildren().forEach(child => {
+ if (child !== paragraphNode) {
+diff --git a/dist/LexicalTable.prod.js b/dist/LexicalTable.prod.js
+index 030a4df067c0dde286a273ed9b3ce2e7593a4ef8..70d0e16c3cad6f197615941fc13dfdc8f86a0c81 100644
+--- a/dist/LexicalTable.prod.js
++++ b/dist/LexicalTable.prod.js
+@@ -6,4 +6,4 @@
+ *
+ */
+
+-"use strict";var e=require("@lexical/utils"),t=require("lexical"),n=require("@lexical/extension"),o=require("@lexical/clipboard"),r=require("@lexical/html");const l=/^(\d+(?:\.\d+)?)px$/,s={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1};class i extends t.ElementNode{__colSpan;__rowSpan;__headerState;__width;__backgroundColor;__verticalAlign;static getType(){return"tablecell"}static clone(e){return new i(e.__headerState,e.__colSpan,e.__width,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__rowSpan=e.__rowSpan,this.__backgroundColor=e.__backgroundColor,this.__verticalAlign=e.__verticalAlign,this.__colSpan=e.__colSpan,this.__headerState=e.__headerState,this.__width=e.__width}static importDOM(){return{td:e=>({conversion:c,priority:0}),th:e=>({conversion:c,priority:0})}}static importJSON(e){return u().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeaderStyles(e.headerState).setColSpan(e.colSpan||1).setRowSpan(e.rowSpan||1).setWidth(e.width||void 0).setBackgroundColor(e.backgroundColor||null).setVerticalAlign(e.verticalAlign||void 0)}constructor(e=s.NO_STATUS,t=1,n,o){super(o),this.__colSpan=t,this.__rowSpan=1,this.__headerState=e,this.__width=n,this.__backgroundColor=null,this.__verticalAlign=void 0}createDOM(t){const n=document.createElement(this.getTag());return this.__width&&(n.style.width=`${this.__width}px`),this.__colSpan>1&&(n.colSpan=this.__colSpan),this.__rowSpan>1&&(n.rowSpan=this.__rowSpan),null!==this.__backgroundColor&&(n.style.backgroundColor=this.__backgroundColor),a(this.__verticalAlign)&&(n.style.verticalAlign=this.__verticalAlign),e.addClassNamesToElement(n,t.theme.tableCell,this.hasHeader()&&t.theme.tableCellHeader),n}exportDOM(e){const n=super.exportDOM(e);if(t.isHTMLElement(n.element)){const e=n.element;e.setAttribute("data-temporary-table-cell-lexical-key",this.getKey()),e.style.border="1px solid black",this.__colSpan>1&&(e.colSpan=this.__colSpan),this.__rowSpan>1&&(e.rowSpan=this.__rowSpan),e.style.width=`${this.getWidth()||75}px`,e.style.verticalAlign=this.getVerticalAlign()||"top",e.style.textAlign="start",null===this.__backgroundColor&&this.hasHeader()&&(e.style.backgroundColor="#f2f3f5")}return n}exportJSON(){return{...super.exportJSON(),...a(this.__verticalAlign)&&{verticalAlign:this.__verticalAlign},backgroundColor:this.getBackgroundColor(),colSpan:this.__colSpan,headerState:this.__headerState,rowSpan:this.__rowSpan,width:this.getWidth()}}getColSpan(){return this.getLatest().__colSpan}setColSpan(e){const t=this.getWritable();return t.__colSpan=e,t}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(e){const t=this.getWritable();return t.__rowSpan=e,t}getTag(){return this.hasHeader()?"th":"td"}setHeaderStyles(e,t=s.BOTH){const n=this.getWritable();return n.__headerState=e&t|n.__headerState&~t,n}getHeaderStyles(){return this.getLatest().__headerState}setWidth(e){const t=this.getWritable();return t.__width=e,t}getWidth(){return this.getLatest().__width}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(e){const t=this.getWritable();return t.__backgroundColor=e,t}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(e){const t=this.getWritable();return t.__verticalAlign=e||void 0,t}toggleHeaderStyle(e){const t=this.getWritable();return(t.__headerState&e)===e?t.__headerState-=e:t.__headerState+=e,t}hasHeaderState(e){return(this.getHeaderStyles()&e)===e}hasHeader(){return this.getLatest().__headerState!==s.NO_STATUS}updateDOM(e){return e.__headerState!==this.__headerState||e.__width!==this.__width||e.__colSpan!==this.__colSpan||e.__rowSpan!==this.__rowSpan||e.__backgroundColor!==this.__backgroundColor||e.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}}function a(e){return"middle"===e||"bottom"===e}function c(e){const n=e,o=e.nodeName.toLowerCase();let r;l.test(n.style.width)&&(r=parseFloat(n.style.width));let i=s.NO_STATUS;if("th"===o){const e=n.getAttribute("scope");if("col"===e)i=s.COLUMN;else if("row"===e)i=s.ROW;else{const e=n.parentElement,o=t.isHTMLElement(e)&&"tr"===e.nodeName.toLowerCase()&&t.isHTMLElement(e.parentElement)&&("thead"===e.parentElement.nodeName.toLowerCase()||0===e.rowIndex),r=0===n.cellIndex;o&&(i|=s.ROW),r&&(i|=s.COLUMN),i===s.NO_STATUS&&(i=s.ROW)}}const c=u(i,n.colSpan,r);c.__rowSpan=n.rowSpan;const d=n.style.backgroundColor;""!==d&&(c.__backgroundColor=d);const h=n.style.verticalAlign;a(h)&&(c.__verticalAlign=h);const g=n.style,f=(g&&g.textDecoration||"").split(" "),m="700"===g.fontWeight||"bold"===g.fontWeight,p=f.includes("line-through"),C="italic"===g.fontStyle,_=f.includes("underline"),S=g.color;return{after:e=>{const n=[];let o=null;const r=()=>{if(o){const e=o.getFirstChild();t.$isLineBreakNode(e)&&1===o.getChildrenSize()&&e.remove()}};for(const l of e)if(t.$isInlineElementOrDecoratorNode(l)||t.$isTextNode(l)||t.$isLineBreakNode(l)){if(t.$isTextNode(l)&&(m&&l.toggleFormat("bold"),p&&l.toggleFormat("strikethrough"),C&&l.toggleFormat("italic"),_&&l.toggleFormat("underline"),S)){const e=l.getStyle();e.includes("color:")||l.setStyle(e+`color: ${S};`)}o?o.append(l):(o=t.$createParagraphNode().append(l),n.push(o))}else n.push(l),r(),o=null;return r(),0===n.length&&n.push(t.$createParagraphNode()),n},node:c}}function u(e=s.NO_STATUS,n=1,o){return t.$applyNodeReplacement(new i(e,n,o))}function d(e){return e instanceof i}const h=t.createCommand("INSERT_TABLE_COMMAND");function g(e,...t){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(const e of t)o.append("v",e);throw n.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}class f extends t.ElementNode{__height;static getType(){return"tablerow"}static clone(e){return new f(e.__height,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__height=e.__height}static importDOM(){return{tr:e=>({conversion:m,priority:0})}}static importJSON(e){return p().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeight(e.height)}constructor(e,t){super(t),this.__height=e}exportJSON(){const e=this.getHeight();return{...super.exportJSON(),...void 0===e?void 0:{height:e}}}createDOM(t){const n=document.createElement("tr");return this.__height&&(n.style.height=`${this.__height}px`),e.addClassNamesToElement(n,t.theme.tableRow),n}extractWithChild(e,t,n){return"html"===n}isShadowRoot(){return!0}setHeight(e){const t=this.getWritable();return t.__height=e,t}getHeight(){return this.getLatest().__height}updateDOM(e){return e.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}}function m(t){const n=t;let o;return l.test(n.style.height)&&(o=parseFloat(n.style.height)),{after:t=>e.$descendantsMatching(t,d),node:p(o)}}function p(e){return t.$applyNodeReplacement(new f(e))}function C(e){return e instanceof f}function _(e,n,o=!0){const r=ze();for(let l=0;l<e;l++){const e=p();for(let r=0;r<n;r++){let n=s.NO_STATUS;"object"==typeof o?(0===l&&o.rows&&(n|=s.ROW),0===r&&o.columns&&(n|=s.COLUMN)):o&&(0===l&&(n|=s.ROW),0===r&&(n|=s.COLUMN));const i=u(n),a=t.$createParagraphNode();a.append(t.$createTextNode()),i.append(a),e.append(i)}r.append(e)}return r}function S(t){const n=e.$findMatchingParent(t,e=>C(e));if(C(n))return n;throw new Error("Expected table cell to be inside of table row.")}function N(t){const n=e.$findMatchingParent(t,e=>Ye(e));if(Ye(n))return n;throw new Error("Expected table cell to be inside of table.")}function b(e,t){const n=N(e),{x:o,y:r}=n.getCordsFromCellNode(e,t);return{above:n.getCellNodeFromCords(o,r-1,t),below:n.getCellNodeFromCords(o,r+1,t),left:n.getCellNodeFromCords(o-1,r,t),right:n.getCellNodeFromCords(o+1,r,t)}}const w=(e,t)=>e===s.BOTH||e===t?t:s.NO_STATUS;function y(e=!0){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=n.focus.getNode(),[l]=H(o),[s,,i]=H(r),[,a,c]=k(i,s,l),{startRow:u}=c,{startRow:d}=a;return e?$(u+l.__rowSpan>d+s.__rowSpan?l:s,!0):$(d<u?s:l,!1)}const T=y;function $(e,n=!0){const[,,o]=H(e),[r,l]=k(o,e,e),i=r[0].length,{startRow:a}=l;let c=null;if(n){const n=a+e.__rowSpan-1,l=r[n],d=p();for(let e=0;e<i;e++){const{cell:o,startRow:r}=l[e];if(r+o.__rowSpan-1<=n){const n=l[e].cell.__headerState,o=w(n,s.COLUMN);d.append(u(o).append(t.$createParagraphNode()))}else o.setRowSpan(o.__rowSpan+1)}const h=o.getChildAtIndex(n);C(h)||g(256),h.insertAfter(d),c=d}else{const e=a,n=r[e],l=p();for(let o=0;o<i;o++){const{cell:r,startRow:i}=n[o];if(i===e){const e=n[o].cell.__headerState,r=w(e,s.COLUMN);l.append(u(r).append(t.$createParagraphNode()))}else r.setRowSpan(r.__rowSpan+1)}const d=o.getChildAtIndex(e);C(d)||g(257),d.insertBefore(l),c=l}return c}function R(e=!0){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=n.focus.getNode(),[l]=H(o),[s,,i]=H(r),[,a,c]=k(i,s,l),{startColumn:u}=c,{startColumn:d}=a;return e?E(u+l.__colSpan>d+s.__colSpan?l:s,!0):E(d<u?s:l,!1)}const x=R;function E(e,n=!0,o=!0){const[,,r]=H(e),[l,i]=k(r,e,e),a=l.length,{startColumn:c}=i,d=n?c+e.__colSpan-1:c-1,h=r.getFirstChild();C(h)||g(120);let f=null;function m(e=s.NO_STATUS){const n=u(e).append(t.$createParagraphNode());return null===f&&(f=n),n}let p=h;e:for(let e=0;e<a;e++){if(0!==e){const e=p.getNextSibling();C(e)||g(121),p=e}const t=l[e],n=t[d<0?0:d].cell.__headerState,o=w(n,s.ROW);if(d<0){P(p,m(o));continue}const{cell:r,startColumn:i,startRow:a}=t[d];if(i+r.__colSpan-1<=d){let n=r,l=a,s=d;for(;l!==e&&n.__rowSpan>1;){if(s-=r.__colSpan,!(s>=0)){p.append(m(o));continue e}{const{cell:e,startRow:o}=t[s];n=e,l=o}}n.insertAfter(m(o))}else r.setColSpan(r.__colSpan+1)}null!==f&&o&&F(f);const _=r.getColWidths();if(_){const e=[..._],t=d<0?0:d,n=e[t];e.splice(t,0,n),r.setColWidths(e)}return f}function M(){const e=t.$getSelection();t.$isRangeSelection(e)||X(e)||g(188);const[n,o]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[r,,l]=H(n),[s]=H(o),[i,a,c]=k(l,r,s),{startRow:u}=a,{startRow:d}=c,h=d+s.__rowSpan-1;if(i.length===h-u+1)return void l.remove();const f=i[0].length,m=i[h+1],p=l.getChildAtIndex(h+1);for(let e=h;e>=u;e--){for(let t=f-1;t>=0;t--){const{cell:n,startRow:o,startColumn:r}=i[e][t];if(r===t){if(o<u||o+n.__rowSpan-1>h){const e=Math.max(o,u),t=Math.min(n.__rowSpan+o-1,h),r=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-r)}if(o>=u&&o+n.__rowSpan-1>h&&e===h){null===p&&g(122);let o=null;for(let n=0;n<t;n++){const t=m[n],r=t.cell;t.startRow===e+1&&(o=r),r.__colSpan>1&&(n+=r.__colSpan-1)}null===o?P(p,n):o.insertAfter(n)}}}const t=l.getChildAtIndex(e);C(t)||g(206,String(e)),t.remove()}if(void 0!==m){const{cell:e}=m[0];F(e)}else{const e=i[u-1],{cell:t}=e[0];F(t)}}const O=M;function A(){const e=t.$getSelection();t.$isRangeSelection(e)||X(e)||g(188);const n=e.anchor.getNode(),o=e.focus.getNode(),[r,,l]=H(n),[s]=H(o),[i,a,c]=k(l,r,s),{startColumn:u}=a,{startRow:d,startColumn:h}=c,f=Math.min(u,h),m=Math.max(u+r.__colSpan-1,h+s.__colSpan-1),p=m-f+1;if(i[0].length===m-f+1)return l.selectPrevious(),void l.remove();const C=i.length;for(let e=0;e<C;e++)for(let t=f;t<=m;t++){const{cell:n,startColumn:o}=i[e][t];if(o<f){if(t===f){const e=f-o;n.setColSpan(n.__colSpan-Math.min(p,n.__colSpan-e))}}else if(o+n.__colSpan-1>m){if(t===m){const e=m-o+1;n.setColSpan(n.__colSpan-e)}}else n.remove()}const _=i[d],S=u>h?_[u+r.__colSpan]:_[h+s.__colSpan];if(void 0!==S){const{cell:e}=S;F(e)}else{const e=h<u?_[h-1]:_[u-1],{cell:t}=e;F(t)}const N=l.getColWidths();if(N){const e=[...N];e.splice(f,p),l.setColWidths(e)}}const v=A;function F(e){const t=e.getFirstDescendant();null==t?e.selectStart():t.getParentOrThrow().selectStart()}function P(e,t){const n=e.getFirstChild();null!==n?n.insertBefore(t):e.append(t)}function K(e){if(0===e.length)return null;const n=N(e[0]),[o]=L(n,null,null);let r=1/0,l=-1/0,s=1/0,i=-1/0;const a=new Set;for(const t of o)for(const n of t){if(!n||!n.cell)continue;const t=n.cell.getKey();if(!a.has(t)&&e.some(e=>e.is(n.cell))){a.add(t);const e=n.startRow,o=n.startColumn,c=n.cell.__rowSpan||1,u=n.cell.__colSpan||1;r=Math.min(r,e),l=Math.max(l,e+c-1),s=Math.min(s,o),i=Math.max(i,o+u-1)}}if(r===1/0||s===1/0)return null;const c=l-r+1,u=i-s+1,d=o[r][s];if(!d.cell)return null;const h=d.cell;h.setColSpan(u),h.setRowSpan(c);const g=new Set([h.getKey()]);for(let e=r;e<=l;e++)for(let t=s;t<=i;t++){const n=o[e][t];if(!n.cell)continue;const r=n.cell,l=r.getKey();if(!g.has(l)){g.add(l);D(r)||h.append(...r.getChildren()),r.remove()}}return 0===h.getChildrenSize()&&h.append(t.$createParagraphNode()),h}function D(e){if(1!==e.getChildrenSize())return!1;const n=e.getFirstChildOrThrow();return!(!t.$isParagraphNode(n)||!n.isEmpty())}function I(e){const[n,o,r]=H(e),l=n.__colSpan,i=n.__rowSpan;if(1===l&&1===i)return;const[a,c]=k(r,n,n),{startColumn:d,startRow:h}=c,f=n.__headerState&s.COLUMN,m=Array.from({length:l},(e,t)=>{let n=f;for(let e=0;0!==n&&e<a.length;e++)n&=a[e][t+d].cell.__headerState;return n}),p=n.__headerState&s.ROW,_=Array.from({length:i},(e,t)=>{let n=p;for(let e=0;0!==n&&e<a[0].length;e++)n&=a[t+h][e].cell.__headerState;return n});if(l>1){for(let e=1;e<l;e++)n.insertAfter(u(m[e]|_[0]).append(t.$createParagraphNode()));n.setColSpan(1)}if(i>1){let e;for(let n=1;n<i;n++){const r=h+n,s=a[r];e=(e||o).getNextSibling(),C(e)||g(125);let i=null;for(let e=0;e<d;e++){const t=s[e],n=t.cell;t.startRow===r&&(i=n),n.__colSpan>1&&(e+=n.__colSpan-1)}if(null===i)for(let o=l-1;o>=0;o--)P(e,u(m[o]|_[n]).append(t.$createParagraphNode()));else for(let e=l-1;e>=0;e--)i.insertAfter(u(m[e]|_[n]).append(t.$createParagraphNode()))}n.setRowSpan(1)}}function k(e,t,n){const[o,r,l]=L(e,t,n);return null===r&&g(207),null===l&&g(208),[o,r,l]}function L(e,t,n){const o=[];let r=null,l=null;function s(e){let t=o[e];return void 0===t&&(o[e]=t=[]),t}const i=e.getChildren();for(let e=0;e<i.length;e++){const o=i[e];C(o)||g(209);const a=s(e);for(let c=o.getFirstChild(),u=0;null!=c;c=c.getNextSibling()){for(d(c)||g(147);void 0!==a[u];)u++;const o={cell:c,startColumn:u,startRow:e},{__rowSpan:h,__colSpan:f}=c;for(let t=0;t<h&&!(e+t>=i.length);t++){const n=s(e+t);for(let e=0;e<f;e++)n[u+e]=o}null!==t&&null===r&&t.is(c)&&(r=o),null!==n&&null===l&&n.is(c)&&(l=o)}}return[o,r,l]}function H(t){let n;if(t instanceof i)n=t;else if("__type"in t){const o=e.$findMatchingParent(t,d);d(o)||g(148),n=o}else{const o=e.$findMatchingParent(t.getNode(),d);d(o)||g(148),n=o}const o=n.getParent();C(o)||g(149);const r=o.getParent();return Ye(r)||g(210),[n,o,r]}function W(e,t,n){let o,r=Math.min(t.startColumn,n.startColumn),l=Math.min(t.startRow,n.startRow),s=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),i=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{o=!1;for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const a=e[t][n];if(!a)continue;const c=a.startColumn+a.cell.__colSpan-1,u=a.startRow+a.cell.__rowSpan-1,d=a.startColumn<=s&&c>=r,h=a.startRow<=i&&u>=l;if(d&&h){const e=Math.min(r,a.startColumn),t=Math.max(s,c),n=Math.min(l,a.startRow),d=Math.max(i,u);e===r&&t===s&&n===l&&d===i||(r=e,s=t,l=n,i=d,o=!0)}}}while(o);return{maxColumn:s,maxRow:i,minColumn:r,minRow:l}}function B(e){const t=e.getChildren();let n=null;for(const e of t){if(!C(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!d(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function z(e){const[t,,n]=H(e),o=n.getChildren(),r=o.length,l=o[0].getChildren().length,s=new Array(r);for(let e=0;e<r;e++)s[e]=new Array(l);for(let e=0;e<r;e++){const n=o[e].getChildren();let r=0;for(let o=0;o<n.length;o++){for(;s[e][r];)r++;const l=n[o],i=l.__rowSpan||1,a=l.__colSpan||1;for(let t=0;t<i;t++)for(let n=0;n<a;n++)s[e+t][r+n]=l;if(t===l)return{colSpan:a,columnIndex:r,rowIndex:e,rowSpan:i};r+=a}}return null}function Y(t){const[[n,o,r,l],[s,i,a,c]]=["anchor","focus"].map(n=>{const o=t[n].getNode(),r=e.$findMatchingParent(o,d);d(r)||g(238,n,o.getKey(),o.getType());const l=r.getParent();C(l)||g(239,n);const s=l.getParent();return Ye(s)||g(240,n),[o,r,l,s]});return l.is(c)||g(241),{anchorCell:o,anchorNode:n,anchorRow:r,anchorTable:l,focusCell:i,focusNode:s,focusRow:a,focusTable:c}}class U{tableKey;anchor;focus;_cachedNodes;dirty;constructor(e,t,n){this.anchor=t,this.focus=n,t._selection=this,n._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=e}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if("root"===this.tableKey||"root"===this.anchor.key||"element"!==this.anchor.type||"root"===this.focus.key||"element"!==this.focus.type)return!1;const e=t.$getNodeByKey(this.tableKey),n=t.$getNodeByKey(this.anchor.key),o=t.$getNodeByKey(this.focus.key);return null!==e&&null!==n&&null!==o}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return X(e)&&this.tableKey===e.tableKey&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)}set(e,t,n){this.dirty=this.dirty||e!==this.tableKey||t!==this.anchor.key||n!==this.focus.key,this.tableKey=e,this.anchor.key=t,this.focus.key=n,this._cachedNodes=null}clone(){return new U(this.tableKey,t.$createPoint(this.anchor.key,this.anchor.offset,this.anchor.type),t.$createPoint(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(e){}insertText(){}hasFormat(e){let n=0;this.getNodes().filter(d).forEach(e=>{const o=e.getFirstChild();t.$isParagraphNode(o)&&(n|=o.getTextFormat())});const o=t.TEXT_TYPE_TO_FORMAT[e];return 0!==(n&o)}insertNodes(e){const n=this.focus.getNode();t.$isElementNode(n)||g(151);t.$normalizeSelection__EXPERIMENTAL(n.select(0,n.getChildrenSize())).insertNodes(e)}getShape(){const{anchorCell:e,focusCell:t}=Y(this),n=z(e);null===n&&g(153);const o=z(t);null===o&&g(155);const r=Math.min(n.columnIndex,o.columnIndex),l=Math.max(n.columnIndex+n.colSpan-1,o.columnIndex+o.colSpan-1),s=Math.min(n.rowIndex,o.rowIndex),i=Math.max(n.rowIndex+n.rowSpan-1,o.rowIndex+o.rowSpan-1);return{fromX:Math.min(r,l),fromY:Math.min(s,i),toX:Math.max(r,l),toY:Math.max(s,i)}}getNodes(){if(!this.isValid())return[];const e=this._cachedNodes;if(null!==e)return e;const{anchorTable:n,anchorCell:o,focusCell:r}=Y(this),l=r.getParents()[1];if(l!==n){if(n.isParentOf(r)){const e=l.getParent();null==e&&g(159),this.set(this.tableKey,r.getKey(),e.getKey())}else{const e=n.getParent();null==e&&g(158),this.set(this.tableKey,e.getKey(),r.getKey())}return this.getNodes()}const[s,i,a]=k(n,o,r),{minColumn:c,maxColumn:u,minRow:d,maxRow:h}=W(s,i,a),f=new Map([[n.getKey(),n]]);let m=null;for(let e=d;e<=h;e++)for(let t=c;t<=u;t++){const{cell:n}=s[e][t],o=n.getParent();C(o)||g(160),o!==m&&(f.set(o.getKey(),o),m=o),f.has(n.getKey())||J(n,e=>{f.set(e.getKey(),e)})}const p=Array.from(f.values());return t.isCurrentlyReadOnlyMode()||(this._cachedNodes=p),p}getTextContent(){const e=this.getNodes().filter(e=>d(e));let t="";for(let n=0;n<e.length;n++){const o=e[n],r=o.__parent,l=(e[n+1]||{}).__parent;t+=o.getTextContent()+(l!==r?"\n":"\t")}return t}}function X(e){return e instanceof U}function G(){const e=t.$createPoint("root",0,"element"),n=t.$createPoint("root",0,"element");return new U("root",e,n)}function q(e,n,o){e.getKey(),n.getKey(),o.getKey();const r=t.$getSelection(),l=X(r)?r.clone():G();return l.set(e.getKey(),n.getKey(),o.getKey()),l}function J(e,n){const o=[[e]];for(let e=o.at(-1);void 0!==e&&o.length>0;e=o.at(-1)){const r=e.pop();void 0===r?o.pop():!1!==n(r)&&t.$isElementNode(r)&&o.push(r.getChildren())}}function j(e,n=t.$getEditor()){const o=t.$getNodeByKey(e);Ye(o)||g(231,e);const r=te(o,n.getElementByKey(e));return null===r&&g(232,e),{tableElement:r,tableNode:o}}class V{observers;nextFocus;shouldCheckSelectionForTable;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null}setNextFocus(e){this.nextFocus=e}getAndClearNextFocus(){const{nextFocus:e}=this;return null!==e&&(this.nextFocus=null),e}setShouldCheckSelectionForTable(e){this.shouldCheckSelectionForTable=e}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:e}=this;return e?(this.shouldCheckSelectionForTable=null,e):null}}class Q{focusX;focusY;listenersToRemove;table;isHighlightingCells;anchorX;anchorY;tableNodeKey;anchorCell;focusCell;anchorCellNodeKey;focusCellNodeKey;editor;tableSelection;hasHijackedSelectionStyles;isSelecting;pointerType;abortController;listenerOptions;constructor(e,t){this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=t,this.editor=e,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort("removeListeners"),Array.from(this.listenersToRemove).forEach(e=>e()),this.listenersToRemove.clear()}$lookup(){return j(this.tableNodeKey,this.editor)}trackTable(){const e=new MutationObserver(e=>{this.editor.getEditorState().read(()=>{let t=!1;for(let n=0;n<e.length;n++){const o=e[n].target.nodeName;if("TABLE"===o||"TBODY"===o||"THEAD"===o||"TR"===o){t=!0;break}}if(!t)return;const{tableNode:n,tableElement:o}=this.$lookup();this.table=fe(n,o)},{editor:this.editor})});this.editor.getEditorState().read(()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=fe(t,n),e.observe(n,{attributes:!0,childList:!0,subtree:!0})},{editor:this.editor})}$clearHighlight(e=!0){const n=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:o,tableElement:r}=this.$lookup();me(n,fe(o,r),null),e&&null!==t.$getSelection()&&(t.$setSelection(null),n.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0))}$enableHighlightStyle(){const t=this.editor,{tableElement:n}=this.$lookup();e.removeClassNamesFromElement(n,t._config.theme.tableSelection),n.classList.remove("disable-selection"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:t}=this.$lookup();e.addClassNamesToElement(t,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(e){if(null!==e){e.tableKey!==this.tableNodeKey&&g(233,e.tableKey,this.tableNodeKey);const t=this.editor;this.tableSelection=e,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),me(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=t.getDOMSelection(this.editor._window);e&&e.rangeCount>0&&e.removeAllRanges()}}$setFocusCellForSelection(e,n=!1){const o=this.editor,{tableNode:r}=this.$lookup(),l=e.x,s=e.y;if(this.focusCell=e,!this.isHighlightingCells){(n||this.anchorX!==l||this.anchorY!==s||null!=this.tableSelection&&null!=this.anchorCellNodeKey)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle())}if(-1!==this.focusX&&-1!==this.focusY&&l===this.focusX&&s===this.focusY)return!1;if(this.focusX=l,this.focusY=s,this.isHighlightingCells){const i=Pe(r,e.elem);if(null!=this.tableSelection&&null!=this.anchorCellNodeKey){let e=i;if(null===e&&n&&(e=r.getCellNodeFromCords(l,s,this.table)),null!==e){const n=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=e.getKey(),this.tableSelection=q(r,n,e),t.$setSelection(this.tableSelection),o.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0),me(o,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){return this.anchorCellNodeKey?t.$getNodeByKey(this.anchorCellNodeKey):null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&g(234),e}$getFocusTableCell(){return this.focusCellNodeKey?t.$getNodeByKey(this.focusCellNodeKey):null}$getFocusTableCellOrThrow(){const e=this.$getFocusTableCell();return null===e&&g(235),e}$setAnchorCellForSelection(e){this.isHighlightingCells=!1,this.anchorCell=e,this.anchorX=e.x,this.anchorY=e.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:t}=this.$lookup(),n=Pe(t,e.elem);if(null!==n){const e=n.getKey();null!=this.tableSelection?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(t.getKey(),e,e)):this.tableSelection=q(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const n=t.$getSelection();X(n)||g(236);const o=t.$createRangeSelection(),r=o.anchor,l=o.focus,s=n.getNodes().filter(d);s.length>0||g(237);const i=s[0].getFirstChild(),a=t.$isParagraphNode(i)?i.getFormatFlags(e,null):null;s.forEach(t=>{r.set(t.getKey(),0,"element"),l.set(t.getKey(),t.getChildrenSize(),"element"),o.formatText(e,a)}),t.$setSelection(n),this.editor.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}$clearText(){const{editor:e}=this,n=t.$getNodeByKey(this.tableNodeKey);if(!Ye(n))throw new Error("Expected TableNode.");const o=t.$getSelection();X(o)||g(253);const r=o.getNodes().filter(d),l=n.getFirstChild(),s=n.getLastChild();if(r.length>0&&null!==l&&null!==s&&C(l)&&C(s)&&r[0]===l.getFirstChild()&&r[r.length-1]===s.getLastChild()){n.selectPrevious();const o=n.getParent();return n.remove(),void(t.$isRootNode(o)&&o.isEmpty()&&e.dispatchCommand(t.INSERT_PARAGRAPH_COMMAND,void 0))}r.forEach(e=>{if(t.$isElementNode(e)){const n=t.$createParagraphNode(),o=t.$createTextNode();n.append(o),e.append(n),e.getChildren().forEach(e=>{e!==n&&e.remove()})}}),me(e,this.table,null),t.$setSelection(null),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}}const Z="__lexicalTableSelection";function ee(e){return t.isHTMLElement(e)&&"TABLE"===e.nodeName}function te(e,t){if(!t)return t;const n=ee(t)?t:t.querySelector("table");return ee(n)||g(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function ne(e){return e._window}function oe(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;d(n)&&(o=n)}return null}const re=[[t.KEY_ARROW_DOWN_COMMAND,"down"],[t.KEY_ARROW_UP_COMMAND,"up"],[t.KEY_ARROW_LEFT_COMMAND,"backward"],[t.KEY_ARROW_RIGHT_COMMAND,"forward"]],le=[t.DELETE_WORD_COMMAND,t.DELETE_LINE_COMMAND,t.DELETE_CHARACTER_COMMAND],se=[t.KEY_BACKSPACE_COMMAND,t.KEY_DELETE_COMMAND];function ie(e,n){return e.registerRootListener(o=>{if(null===o)return;const r=e._window;if(null===r)return;const l=r=>{const l=r.target;if(0!==r.button||!t.isDOMNode(l)||!o.contains(l))return;const s=function(e){const t=he(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if("TABLE"===n.nodeName&&Z in n&&n[Z])return{cellElement:t,tableElement:n,tableObserver:n[Z]};n=n.parentNode}return null}(l);e.update(()=>{if(X(t.$getSelection())){for(const[e]of n.observers.values())e.$clearHighlight(!1);t.$setSelection(null),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}if(!s)return;const{tableObserver:o,tableElement:l,cellElement:i}=s;!function(e,n,o,r,l,s){const i=e._window;if(!i)return;const a=n=>{if(l.isSelecting)return;l.isSelecting=!0,null!==n&&null===l.anchorCell&&e.update(()=>{l.$setAnchorCellForSelection(n)});const o=()=>{l.isSelecting=!1,i.removeEventListener("pointerup",o),i.removeEventListener("pointermove",a)},a=n=>{if(!(e=>!(1&~e.buttons))(n)&&l.isSelecting)return l.isSelecting=!1,i.removeEventListener("pointerup",o),void i.removeEventListener("pointermove",a);if(!t.isDOMNode(n.target))return;let c=null;const u=!(t.IS_FIREFOX||r.contains(n.target));if(u)c=ge(r,n.target);else for(const e of document.elementsFromPoint(n.clientX,n.clientY))if(c=ge(r,e),c)break;if(c){const n=c;null===l.anchorCell&&e.update(()=>{l.$setAnchorCellForSelection(n)}),null!==l.focusCell&&c.elem===l.focusCell.elem||(s.setNextFocus({focusCell:c,override:u,tableKey:l.tableNodeKey}),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0))}};i.addEventListener("pointerup",o,l.listenerOptions),i.addEventListener("pointermove",a,l.listenerOptions)};l.pointerType=n.pointerType;const c=t.$getNodeByKeyOrThrow(l.tableNodeKey),u=t.$getPreviousSelection();if(t.IS_FIREFOX&&n.shiftKey&&we(u,c)&&(t.$isRangeSelection(u)||X(u))){const e=u.anchor.getNode(),t=oe(c,u.anchor.getNode());if(t)l.$setAnchorCellForSelection(Fe(l,t)),l.$setFocusCellForSelection(o),Oe(n);else{(c.isBefore(e)?c.selectStart():c.selectEnd()).anchor.set(u.anchor.key,u.anchor.offset,u.anchor.type)}}else"touch"!==n.pointerType&&l.$setAnchorCellForSelection(o);a(o)}(e,r,i,l,o,n)})};return r.addEventListener("pointerdown",l),()=>{r.removeEventListener("pointerdown",l)}})}function ae(n,r,l,s,i){const a=l.getRootElement(),c=ne(l);null!==a&&null!==c||g(246);const u=new Q(l,n.getKey()),h=te(n,r);!function(e,t){null!==de(e)&&g(205);e[Z]=t}(h,u),u.listenersToRemove.add(()=>function(e,t){de(e)===t&&delete e[Z]}(h,u));const f=e=>{if(e.detail>=3&&t.isDOMNode(e.target)){null!==he(e.target)&&e.preventDefault()}};h.addEventListener("mousedown",f,u.listenerOptions),u.listenersToRemove.add(()=>{h.removeEventListener("mousedown",f)});for(const[e,o]of re)u.listenersToRemove.add(l.registerCommand(e,e=>Me(l,e,o,n,u,i),t.COMMAND_PRIORITY_HIGH));u.listenersToRemove.add(l.registerCommand(t.KEY_ESCAPE_COMMAND,e=>{const o=t.$getSelection();if(X(o)){const t=oe(n,o.focus.getNode());if(null!==t)return Oe(e),t.selectEnd(),!0}return!1},t.COMMAND_PRIORITY_HIGH));const m=o=>()=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$clearText(),!0;if(t.$isRangeSelection(r)){if(!d(oe(n,r.anchor.getNode())))return!1;const l=r.anchor.getNode(),s=r.focus.getNode(),i=n.isParentOf(l),a=n.isParentOf(s);if(i&&!a||a&&!i)return u.$clearText(),!0;const c=e.$findMatchingParent(r.anchor.getNode(),e=>t.$isElementNode(e)),h=c&&e.$findMatchingParent(c,e=>t.$isElementNode(e)&&d(e.getParent()));if(!t.$isElementNode(h)||!t.$isElementNode(c))return!1;if(o===t.DELETE_LINE_COMMAND&&null===h.getPreviousSibling())return!0}return!1};for(const e of le)u.listenersToRemove.add(l.registerCommand(e,m(e),t.COMMAND_PRIORITY_HIGH));const p=e=>{const o=t.$getSelection();if(!X(o)&&!t.$isRangeSelection(o))return!1;const r=n.isParentOf(o.anchor.getNode());if(r!==n.isParentOf(o.focus.getNode())){const e=r?"anchor":"focus",t=r?"focus":"anchor",{key:l,offset:s,type:i}=o[t];return n[o[e].isBefore(o[t])?"selectPrevious":"selectNext"]()[t].set(l,s,i),!1}return!!we(o,n)&&(!!X(o)&&(e&&(e.preventDefault(),e.stopPropagation()),u.$clearText(),!0))};for(const e of se)u.listenersToRemove.add(l.registerCommand(e,p,t.COMMAND_PRIORITY_HIGH));return u.listenersToRemove.add(l.registerCommand(t.CUT_COMMAND,n=>{const r=t.$getSelection();if(r){if(!X(r)&&!t.$isRangeSelection(r))return!1;o.copyToClipboard(l,e.objectKlassEquals(n,ClipboardEvent)?n:null,o.$getClipboardDataFromSelection(r));const s=p(n);return t.$isRangeSelection(r)?(r.removeText(),!0):s}return!1},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FORMAT_TEXT_COMMAND,o=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$formatCells(o),!0;if(t.$isRangeSelection(r)){const t=e.$findMatchingParent(r.anchor.getNode(),e=>d(e));if(!d(t))return!1}return!1},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FORMAT_ELEMENT_COMMAND,e=>{const o=t.$getSelection();if(!X(o)||!we(o,n))return!1;const r=o.anchor.getNode(),l=o.focus.getNode();if(!d(r)||!d(l))return!1;if(function(e,t){if(X(e)){const n=e.anchor.getNode(),o=e.focus.getNode();if(t&&n&&o){const[e]=k(t,n,o);return n.getKey()===e[0][0].cell.getKey()&&o.getKey()===e[e.length-1].at(-1).cell.getKey()}}return!1}(o,n))return n.setFormat(e),!0;const[s,i,a]=k(n,r,l),c=Math.max(i.startRow+i.cell.__rowSpan-1,a.startRow+a.cell.__rowSpan-1),u=Math.max(i.startColumn+i.cell.__colSpan-1,a.startColumn+a.cell.__colSpan-1),h=Math.min(i.startRow,a.startRow),g=Math.min(i.startColumn,a.startColumn),f=new Set;for(let n=h;n<=c;n++)for(let o=g;o<=u;o++){const r=s[n][o].cell;if(f.has(r))continue;f.add(r),r.setFormat(e);const l=r.getChildren();for(let n=0;n<l.length;n++){const o=l[n];t.$isElementNode(o)&&!o.isInline()&&o.setFormat(e)}}return!0},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.CONTROLLED_TEXT_INSERTION_COMMAND,o=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$clearHighlight(),!1;if(t.$isRangeSelection(r)){const s=e.$findMatchingParent(r.anchor.getNode(),e=>d(e));if(!d(s))return!1;if("string"==typeof o){const e=ve(l,r,n);if(e)return Ae(e,n,[t.$createTextNode(o)]),!0}}return!1},t.COMMAND_PRIORITY_HIGH)),s&&u.listenersToRemove.add(l.registerCommand(t.KEY_TAB_COMMAND,o=>{const r=t.$getSelection();if(!t.$isRangeSelection(r)||!r.isCollapsed()||!we(r,n))return!1;const l=Re(r.anchor.getNode());return!(null===l||!n.is(xe(l)))&&(Oe(o),function(n,o){const r="next"===o?"getNextSibling":"getPreviousSibling",l="next"===o?"getFirstChild":"getLastChild",s=n[r]();if(t.$isElementNode(s))return s.selectEnd();const i=e.$findMatchingParent(n,C);null===i&&g(247);for(let e=i[r]();C(e);e=e[r]()){const n=e[l]();if(t.$isElementNode(n))return n.selectEnd()}const a=e.$findMatchingParent(i,Ye);null===a&&g(248);"next"===o?a.selectNext():a.selectPrevious()}(l,o.shiftKey?"previous":"next"),!0)},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FOCUS_COMMAND,e=>n.isSelected(),t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.INSERT_PARAGRAPH_COMMAND,()=>{const e=t.$getSelection();if(!t.$isRangeSelection(e)||!e.isCollapsed()||!we(e,n))return!1;const o=ve(l,e,n);return!!o&&(Ae(o,n),!0)},t.COMMAND_PRIORITY_HIGH)),u}function ce(n,o){const r=t.$getSelection(),l=t.$getPreviousSelection(),s=n.getAndClearNextFocus();if(null!==s){const{tableKey:e,focusCell:t}=s,o=n.observers.get(e);o||g(335,e);const[l]=o;if(X(r)&&r.tableKey===l.tableNodeKey)return(t.x!==l.focusX||t.y!==l.focusY)&&(l.$setFocusCellForSelection(t),!0);if(null!==l.anchorCell&&null!==l.anchorCellNodeKey&&t.elem!==l.anchorCell.elem&&null!==l.tableSelection)return l.$setFocusCellForSelection(t,!0),!0}const i=n.getAndClearShouldCheckSelectionForTable();if(i&&t.$isRangeSelection(l)&&t.$isRangeSelection(r)&&r.isCollapsed()){const n=t.$getNodeByKeyOrThrow(i),o=r.anchor.getNode(),l=n.getFirstChild(),s=Re(o);if(null!==s&&C(l)){const t=l.getFirstChild();if(d(t)&&n.is(e.$findMatchingParent(s,e=>e.is(n)||e.is(t))))return t.selectStart(),!0}}X(r)&&function(e,n){const o=ne(e),r=t.$getPreviousSelection();if(!n.is(r))return;const l=t.$getNodeByKeyOrThrow(n.tableKey),s=t.getDOMSelection(o);if(s&&s.anchorNode&&s.focusNode){const o=t.$getNearestNodeFromDOMNode(s.focusNode),r=o&&!l.isParentOf(o),i=t.$getNearestNodeFromDOMNode(s.anchorNode),a=i&&l.isParentOf(i);if(r&&a&&s.rangeCount>0){const o=t.$createRangeSelectionFromDom(s,e);o&&(o.anchor.set(l.getKey(),n.isBackward()?l.getChildrenSize():0,"element"),s.removeAllRanges(),t.$setSelection(o))}}}(o,r),t.$isRangeSelection(r)&&function(e,n){const o=t.$getPreviousSelection(),{anchor:r,focus:l}=e,s=r.getNode(),i=l.getNode(),a=Re(s),c=Re(i),u=a?xe(a):null,d=c?xe(c):null,h=e.isBackward(),f=a&&c&&u&&d&&u.is(d),m=d&&(!u||u.isParentOf(d)),p=u&&(!d||d.isParentOf(u));if(m){const n=e.clone(),[o]=k(d,c,c),r=o[0][0].cell,l=o[o.length-1].at(-1).cell;n.focus.set(h?r.getKey():l.getKey(),h?0:l.getChildrenSize(),"element"),t.$setSelection(n)}else if(p){const n=e.clone(),[o]=k(u,a,a),r=o[0][0].cell,l=o[o.length-1].at(-1).cell;n.anchor.set(h?l.getKey():r.getKey(),h?l.getChildrenSize():0,"element"),t.$setSelection(n)}else if(f){const r=n.observers.get(u.getKey());r||g(335,u.getKey());const[l]=r;if(a.is(c)||(l.$setAnchorCellForSelection(Fe(l,a)),l.$setFocusCellForSelection(Fe(l,c),!0)),"touch"===l.pointerType&&l.isSelecting&&e.isCollapsed()&&t.$isRangeSelection(o)&&o.isCollapsed()){const e=Re(o.anchor.getNode());e&&!e.is(c)&&(l.$setAnchorCellForSelection(Fe(l,e)),l.$setFocusCellForSelection(Fe(l,c),!0),l.pointerType=null)}}}(r,n);const a=Array.from(n.observers.entries()).map(([e,[n]])=>({tableNode:t.$getNodeByKeyOrThrow(e),tableObserver:n}));for(const{tableNode:e,tableObserver:t}of a)ue(o,e,t);return!1}function ue(e,n,o){const r=t.$getSelection(),l=t.$getPreviousSelection();r&&!r.is(l)&&(X(r)||X(l))&&o.tableSelection&&!o.tableSelection.is(l)&&(X(r)&&r.tableKey===o.tableNodeKey?o.$updateTableTableSelection(r):!X(r)&&X(l)&&l.tableKey===o.tableNodeKey&&o.$updateTableTableSelection(null)),o.hasHijackedSelectionStyles&&!n.isSelected()?function(e,t){t.$enableHighlightStyle(),pe(t.table,t=>{const n=t.elem;t.highlighted=!1,$e(e,t),n.getAttribute("style")||n.removeAttribute("style")})}(e,o):!o.hasHijackedSelectionStyles&&n.isSelected()&&function(e,t){t.$disableHighlightStyle(),pe(t.table,t=>{t.highlighted=!0,Te(e,t)})}(e,o)}function de(e){return e[Z]||null}function he(e){let t=e;for(;null!=t;){const e=t.nodeName;if("TD"===e||"TH"===e){const e=t._cell;return void 0===e?null:e}t=t.parentNode}return null}function ge(e,t){if(!e.contains(t))return null;let n=null;for(let o=t;null!=o;o=o.parentNode){if(o===e)return n;const t=o.nodeName;"TD"!==t&&"TH"!==t||(n=o._cell||null)}return null}function fe(e,t){const n=[],o={columns:0,domRows:n,rows:0};let r=te(e,t).querySelector("tr"),l=0,s=0;for(n.length=0;null!=r;){const e=r.nodeName;if("TD"===e||"TH"===e){const e={elem:r,hasBackgroundColor:""!==r.style.backgroundColor,highlighted:!1,x:l,y:s};r._cell=e;let t=n[s];void 0===t&&(t=n[s]=[]),t[l]=e}else{const e=r.firstChild;if(null!=e){r=e;continue}}const t=r.nextSibling;if(null!=t){l++,r=t;continue}const o=r.parentNode;if(null!=o){const e=o.nextSibling;if(null==e)break;s++,l=0,r=e}}return o.columns=l+1,o.rows=s+1,o}function me(e,t,n){const o=new Set(n?n.getNodes():[]);pe(t,(t,n)=>{const r=t.elem;o.has(n)?(t.highlighted=!0,Te(e,t)):(t.highlighted=!1,$e(e,t),r.getAttribute("style")||r.removeAttribute("style"))})}function pe(e,n){const{domRows:o}=e;for(let e=0;e<o.length;e++){const r=o[e];if(r)for(let o=0;o<r.length;o++){const l=r[o];if(!l)continue;const s=t.$getNearestNodeFromDOMNode(l.elem);null!==s&&n(l,s,{x:o,y:e})}}}const Ce=(e,t,n,o,r)=>{const l="forward"===r;switch(r){case"backward":case"forward":return n!==(l?e.table.columns-1:0)?ye(t.getCellNodeFromCordsOrThrow(n+(l?1:-1),o,e.table),l):o!==(l?e.table.rows-1:0)?ye(t.getCellNodeFromCordsOrThrow(l?0:e.table.columns-1,o+(l?1:-1),e.table),l):l?t.selectNext():t.selectPrevious(),!0;case"up":return 0!==o?ye(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case"down":return o!==e.table.rows-1?ye(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function _e(e,t){let n,o;if(t.startColumn===e.minColumn)n="minColumn";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n="maxColumn"}if(t.startRow===e.minRow)o="minRow";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;o="maxRow"}return[n,o]}function Se([e,t]){return["minColumn"===e?"maxColumn":"minColumn","minRow"===t?"maxRow":"minRow"]}function Ne(e,t,[n,o]){const r=t[o],l=e[r];void 0===l&&g(250,o,String(r));const s=t[n],i=l[s];return void 0===i&&g(250,n,String(s)),i}function be(e,t,n,o,r){const l=W(t,n,o),s=function(e,t){const{minColumn:n,maxColumn:o,minRow:r,maxRow:l}=t;let s=1,i=1,a=1,c=1;const u=e[r],d=e[l];for(let e=n;e<=o;e++)s=Math.max(s,u[e].cell.__rowSpan),c=Math.max(c,d[e].cell.__rowSpan);for(let t=r;t<=l;t++)i=Math.max(i,e[t][n].cell.__colSpan),a=Math.max(a,e[t][o].cell.__colSpan);return{bottomSpan:c,leftSpan:i,rightSpan:a,topSpan:s}}(t,l),{topSpan:i,leftSpan:a,bottomSpan:c,rightSpan:u}=s,d=function(e,t){const n=_e(e,t);return null===n&&g(249,t.cell.getKey()),n}(l,n),[h,f]=Se(d);let m=l[h],p=l[f];"forward"===r?m+="maxColumn"===h?1:a:"backward"===r?m-="minColumn"===h?1:u:"down"===r?p+="maxRow"===f?1:i:"up"===r&&(p-="minRow"===f?1:c);const C=t[p];if(void 0===C)return!1;const _=C[m];if(void 0===_)return!1;const[S,N]=function(e,t,n){const o=W(e,t,n),r=_e(o,t);if(r)return[Ne(e,o,r),Ne(e,o,Se(r))];const l=_e(o,n);if(l)return[Ne(e,o,Se(l)),Ne(e,o,l)];const s=["minColumn","minRow"];return[Ne(e,o,s),Ne(e,o,Se(s))]}(t,n,_),b=Fe(e,S.cell),w=Fe(e,N.cell);return e.$setAnchorCellForSelection(b),e.$setFocusCellForSelection(w,!0),!0}function we(e,n){if(t.$isRangeSelection(e)||X(e)){const t=n.isParentOf(e.anchor.getNode()),o=n.isParentOf(e.focus.getNode());return t&&o}return!1}function ye(e,t){t?e.selectStart():e.selectEnd()}function Te(n,o){const r=o.elem,l=n._config.theme;d(t.$getNearestNodeFromDOMNode(r))||g(131),e.addClassNamesToElement(r,l.tableCellSelected)}function $e(n,o){const r=o.elem;d(t.$getNearestNodeFromDOMNode(r))||g(131);const l=n._config.theme;e.removeClassNamesFromElement(r,l.tableCellSelected)}function Re(t){const n=e.$findMatchingParent(t,d);return d(n)?n:null}function xe(t){const n=e.$findMatchingParent(t,Ye);return Ye(n)?n:null}function Ee(n,o,r,l,s,i,a){const c=t.$caretFromPoint(r.focus,s?"previous":"next");if(t.$isExtendableTextPointCaret(c))return!1;let u=c;for(const e of t.$extendCaretToRange(c).iterNodeCarets("shadowRoot")){if(!t.$isSiblingCaret(e)||!t.$isElementNode(e.origin))return!1;u=e}const h=u.getParentAtCaret();if(!d(h))return!1;const g=h,f=function(e){for(const n of t.$extendCaretToRange(e).iterNodeCarets("root")){const{origin:o}=n;if(d(o)){if(t.$isChildCaret(n))return t.$getChildCaret(o,e.direction)}else if(!C(o))break}return null}(t.$getSiblingCaret(g,u.direction)),m=e.$findMatchingParent(g,Ye);if(!m||!m.is(i))return!1;const p=n.getElementByKey(g.getKey()),_=he(p);if(!p||!_)return!1;const S=We(n,m);if(a.table=S,f)if("extend"===l){const e=he(n.getElementByKey(f.origin.getKey()));if(!e)return!1;a.$setAnchorCellForSelection(_),a.$setFocusCellForSelection(e,!0)}else{const e=t.$normalizeCaret(f);t.$setPointFromCaret(r.anchor,e),t.$setPointFromCaret(r.focus,e)}else if("extend"===l)a.$setAnchorCellForSelection(_),a.$setFocusCellForSelection(_,!0);else{const e=function(e){const n=t.$getAdjacentChildCaret(e);return t.$isChildCaret(n)?t.$normalizeCaret(n):e}(t.$getSiblingCaret(m,c.direction));t.$setPointFromCaret(r.anchor,e),t.$setPointFromCaret(r.focus,e)}return Oe(o),!0}function Me(n,o,r,l,s,i){if(("up"===r||"down"===r)&&function(e){const t=e.getRootElement();if(!t)return!1;return t.hasAttribute("aria-controls")&&"typeahead-menu"===t.getAttribute("aria-controls")}(n))return!1;const a=t.$getSelection();if(!we(a,l)){if(t.$isRangeSelection(a)){if("backward"===r){if(a.focus.offset>0)return!1;const e=function(e){for(let n=e,o=e;null!==o;n=o,o=o.getParent())if(t.$isElementNode(o)){if(o!==n&&o.getFirstChild()!==n)return null;if(!o.isInline())return o}return null}(a.focus.getNode());if(!e)return!1;const n=e.getPreviousSibling();return!!Ye(n)&&(Oe(o),o.shiftKey?a.focus.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent(),"element"):n.selectEnd(),!0)}if(o.shiftKey&&("up"===r||"down"===r)){const n=a.focus.getNode();if(!a.isCollapsed()&&("up"===r&&!a.isBackward()||"down"===r&&a.isBackward())){let s=e.$findMatchingParent(n,e=>Ye(e));if(d(s)&&(s=e.$findMatchingParent(s,Ye)),s!==l)return!1;if(!s)return!1;const i="down"===r?s.getNextSibling():s.getPreviousSibling();if(!i)return!1;let c=0;"up"===r&&t.$isElementNode(i)&&(c=i.getChildrenSize());let u=i;if("up"===r&&t.$isElementNode(i)){const e=i.getLastChild();u=e||i,c=t.$isTextNode(u)?u.getTextContentSize():0}const h=a.clone();return h.focus.set(u.getKey(),c,t.$isTextNode(u)?"text":"element"),t.$setSelection(h),Oe(o),!0}if(t.$isRootOrShadowRoot(n)){const e="up"===r?a.getNodes()[a.getNodes().length-1]:a.getNodes()[0];if(e){if(null!==oe(l,e)){const e=l.getFirstDescendant(),t=l.getLastDescendant();if(!e||!t)return!1;const[n]=H(e),[o]=H(t),r=l.getCordsFromCellNode(n,s.table),i=l.getCordsFromCellNode(o,s.table),a=l.getDOMCellFromCordsOrThrow(r.x,r.y,s.table),c=l.getDOMCellFromCordsOrThrow(i.x,i.y,s.table);return s.$setAnchorCellForSelection(a),s.$setFocusCellForSelection(c,!0),!0}}return!1}{let l=e.$findMatchingParent(n,e=>t.$isElementNode(e)&&!e.isInline());if(d(l)&&(l=e.$findMatchingParent(l,Ye)),!l)return!1;const i="down"===r?l.getNextSibling():l.getPreviousSibling();if(Ye(i)&&s.tableNodeKey===i.getKey()){const e=i.getFirstDescendant(),n=i.getLastDescendant();if(!e||!n)return!1;const[l]=H(e),[s]=H(n),c=a.clone();return c.focus.set(("up"===r?l:s).getKey(),"up"===r?0:s.getChildrenSize(),"element"),Oe(o),t.$setSelection(c),!0}}}}return"down"===r&&ke(n)&&i.setShouldCheckSelectionForTable(l.getKey()),!1}if(t.$isRangeSelection(a)){if("backward"===r||"forward"===r){return Ee(n,o,a,o.shiftKey?"extend":"move","backward"===r,l,s)}if(a.isCollapsed()){const{anchor:c,focus:u}=a,h=e.$findMatchingParent(c.getNode(),d),g=e.$findMatchingParent(u.getNode(),d);if(!d(h)||!h.is(g))return!1;const f=xe(h);if(f!==l&&null!=f){const e=te(f,n.getElementByKey(f.getKey()));if(null!=e)return s.table=fe(f,e),Me(n,o,r,f,s,i)}const m=n.getElementByKey(h.__key),p=n.getElementByKey(c.key);if(null==p||null==m)return!1;let C;if("element"===c.type)C=p.getBoundingClientRect();else{const e=t.getDOMSelection(ne(n));if(null===e||0===e.rangeCount)return!1;C=e.getRangeAt(0).getBoundingClientRect()}const _="up"===r?h.getFirstChild():h.getLastChild();if(null==_)return!1;const S=n.getElementByKey(_.__key);if(null==S)return!1;const N=S.getBoundingClientRect();if("up"===r?N.top>C.top-C.height:C.bottom+C.height>N.bottom){Oe(o);const e=l.getCordsFromCellNode(h,s.table);if(!o.shiftKey)return Ce(s,l,e.x,e.y,r);{const t=l.getDOMCellFromCordsOrThrow(e.x,e.y,s.table);s.$setAnchorCellForSelection(t),s.$setFocusCellForSelection(t,!0)}return!0}}}else if(X(a)){const{anchor:t,focus:i,tableKey:c}=a;if(c!==l.getKey())return!1;const u=e.$findMatchingParent(t.getNode(),d),h=e.$findMatchingParent(i.getNode(),d),[f]=a.getNodes();Ye(f)||g(251);const m=te(f,n.getElementByKey(f.getKey()));if(!d(u)||!d(h)||!Ye(f)||null==m)return!1;s.$updateTableTableSelection(a);const p=fe(f,m),C=l.getCordsFromCellNode(u,p),_=l.getDOMCellFromCordsOrThrow(C.x,C.y,p);if(s.$setAnchorCellForSelection(_),Oe(o),o.shiftKey){const[e,t,n]=k(l,u,h);return be(s,e,t,n,r)}return h.selectEnd(),!0}return!1}function Oe(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function Ae(e,n,o){const r=t.$createParagraphNode();"first"===e?n.insertBefore(r):n.insertAfter(r),r.append(...o||[]),r.selectEnd()}function ve(n,o,r){const l=r.getParent();if(!l)return;const s=t.getDOMSelection(ne(n));if(!s)return;const i=s.anchorNode,a=n.getElementByKey(l.getKey()),c=te(r,n.getElementByKey(r.getKey()));if(!i||!a||!c||!a.contains(i)||c.contains(i))return;const u=e.$findMatchingParent(o.anchor.getNode(),e=>d(e));if(!u)return;const h=e.$findMatchingParent(u,e=>Ye(e));if(!Ye(h)||!h.is(r))return;const[g,f]=k(r,u,u),m=g[0][0],p=g[g.length-1][g[0].length-1],{startRow:C,startColumn:_}=f,S=C===m.startRow&&_===m.startColumn,N=C===p.startRow&&_===p.startColumn;return S?"first":N?"last":void 0}function Fe(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function Pe(e,n,o){return oe(e,t.$getNearestNodeFromDOMNode(n,o))}function Ke(e,t,n){const o=e.querySelector("colgroup");if(!o)return;const r=[];for(let e=0;e<t;e++){const t=document.createElement("col"),o=n&&n[e];o&&(t.style.width=`${o}px`),r.push(t)}o.replaceChildren(...r)}function De(t,n,o){if(!n.theme.tableAlignment)return;const r=[],l=[];for(const e of["center","right"]){const t=n.theme.tableAlignment[e];t&&(e===o?l:r).push(t)}e.removeClassNamesFromElement(t,...r),e.addClassNamesToElement(t,...l)}const Ie=new WeakSet;function ke(e=t.$getEditor()){return Ie.has(e)}function Le(e,t){t?Ie.add(e):Ie.delete(e)}class He extends t.ElementNode{__rowStriping;__frozenColumnCount;__frozenRowCount;__colWidths;static getType(){return"table"}getColWidths(){return this.getLatest().__colWidths}setColWidths(e){const t=this.getWritable();return t.__colWidths=e,t}static clone(e){return new He(e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__colWidths=e.__colWidths,this.__rowStriping=e.__rowStriping,this.__frozenColumnCount=e.__frozenColumnCount,this.__frozenRowCount=e.__frozenRowCount}static importDOM(){return{table:e=>({conversion:Be,priority:1})}}static importJSON(e){return ze().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setRowStriping(e.rowStriping||!1).setFrozenColumns(e.frozenColumnCount||0).setFrozenRows(e.frozenRowCount||0).setColWidths(e.colWidths)}constructor(e){super(e),this.__rowStriping=!1,this.__frozenColumnCount=0,this.__frozenRowCount=0,this.__colWidths=void 0}exportJSON(){return{...super.exportJSON(),colWidths:this.getColWidths(),frozenColumnCount:this.__frozenColumnCount?this.__frozenColumnCount:void 0,frozenRowCount:this.__frozenRowCount?this.__frozenRowCount:void 0,rowStriping:this.__rowStriping?this.__rowStriping:void 0}}extractWithChild(e,t,n){return"html"===n}getDOMSlot(e){const t=ee(e)?e:e.querySelector("table");return ee(t)||g(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector("colgroup"))}createDOM(n,o){const r=document.createElement("table");this.__style&&t.setDOMStyleFromCSS(r.style,this.__style);const l=document.createElement("colgroup");if(r.appendChild(l),t.setDOMUnmanaged(l),e.addClassNamesToElement(r,n.theme.table),this.updateTableElement(null,r,n),ke(o)){const t=document.createElement("div"),o=n.theme.tableScrollableWrapper;return o?e.addClassNamesToElement(t,o):t.style.overflowX="auto",t.appendChild(r),this.updateTableWrapper(null,t,r,n),t}return r}updateTableWrapper(t,n,o,r){this.__frozenColumnCount!==(t?t.__frozenColumnCount:0)&&function(t,n,o,r){r>0?(e.addClassNamesToElement(t,o.theme.tableFrozenColumn),n.setAttribute("data-lexical-frozen-column","true")):(e.removeClassNamesFromElement(t,o.theme.tableFrozenColumn),n.removeAttribute("data-lexical-frozen-column"))}(n,o,r,this.__frozenColumnCount),this.__frozenRowCount!==(t?t.__frozenRowCount:0)&&function(t,n,o,r){r>0?(e.addClassNamesToElement(t,o.theme.tableFrozenRow),n.setAttribute("data-lexical-frozen-row","true")):(e.removeClassNamesFromElement(t,o.theme.tableFrozenRow),n.removeAttribute("data-lexical-frozen-row"))}(n,o,r,this.__frozenRowCount)}updateTableElement(n,o,r){this.__style!==(n?n.__style:"")&&t.setDOMStyleFromCSS(o.style,this.__style,n?n.__style:""),this.__rowStriping!==(!!n&&n.__rowStriping)&&function(t,n,o){o?(e.addClassNamesToElement(t,n.theme.tableRowStriping),t.setAttribute("data-lexical-row-striping","true")):(e.removeClassNamesFromElement(t,n.theme.tableRowStriping),t.removeAttribute("data-lexical-row-striping"))}(o,r,this.__rowStriping);const l=n?n.getColumnCount():0,s=n?n.__colWidths:void 0;this.getColumnCount()===l&&this.getColWidths()===s||Ke(o,this.getColumnCount(),this.getColWidths()),De(o,r,this.getFormatType())}updateDOM(t,n,o){const r=te(this,n);return n===r===ke()||(l=n,e.isHTMLElement(l)&&"DIV"===l.nodeName&&this.updateTableWrapper(t,n,r,o),this.updateTableElement(t,r,o),!1);var l}scaleDOMColWidths(e,t){const n=this.getColWidths();if(!n)return;Ke(te(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(t){const n=super.exportDOM(t),{element:o}=n;return{after:o=>{if(n.after&&(o=n.after(o)),!ee(o)&&e.isHTMLElement(o)&&(o=o.querySelector("table")),!ee(o))return null;De(o,t._config,this.getFormatType());const[r]=L(this,null,null),l=new Map;for(const e of r)for(const t of e){const e=t.cell.getKey();l.has(e)||l.set(e,{colSpan:t.cell.getColSpan(),startColumn:t.startColumn})}const s=new Set;for(const e of o.querySelectorAll(":scope > tr > [data-temporary-table-cell-lexical-key]")){const t=e.getAttribute("data-temporary-table-cell-lexical-key");if(t){const n=l.get(t);if(e.removeAttribute("data-temporary-table-cell-lexical-key"),n){l.delete(t);for(let e=0;e<n.colSpan;e++)s.add(e+n.startColumn)}}}const i=o.querySelector(":scope > colgroup");if(i){const e=Array.from(o.querySelectorAll(":scope > colgroup > col")).filter((e,t)=>s.has(t));i.replaceChildren(...e)}const a=o.querySelectorAll(":scope > tr");if(a.length>0){const e=document.createElement("tbody");for(const t of a)e.appendChild(t);o.append(e)}return o},element:!ee(o)&&e.isHTMLElement(o)?o.querySelector("table"):o}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(e,t){const{rows:n,domRows:o}=t;for(let t=0;t<n;t++){const n=o[t];if(null!=n)for(let o=0;o<n.length;o++){const r=n[o];if(null==r)continue;const{elem:l}=r,s=Pe(this,l);if(null!==s&&e.is(s))return{x:o,y:t}}}throw new Error("Cell not found in table.")}getDOMCellFromCords(e,t,n){const{domRows:o}=n,r=o[t];if(null==r)return null;const l=r[e<r.length?e:r.length-1];return null==l?null:l}getDOMCellFromCordsOrThrow(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(!o)throw new Error("Cell not found at cords.");return o}getCellNodeFromCords(e,n,o){const r=this.getDOMCellFromCords(e,n,o);if(null==r)return null;const l=t.$getNearestNodeFromDOMNode(r.elem);return d(l)?l:null}getCellNodeFromCordsOrThrow(e,t,n){const o=this.getCellNodeFromCords(e,t,n);if(!o)throw new Error("Node at cords not TableCellNode.");return o}getRowStriping(){return Boolean(this.getLatest().__rowStriping)}setRowStriping(e){const t=this.getWritable();return t.__rowStriping=e,t}setFrozenColumns(e){const t=this.getWritable();return t.__frozenColumnCount=e,t}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(e){const t=this.getWritable();return t.__frozenRowCount=e,t}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const e=this.getFirstChild();if(!e)return 0;let t=0;return e.getChildren().forEach(e=>{d(e)&&(t+=e.getColSpan())}),t}}function We(e,t){const n=e.getElementByKey(t.getKey());return null===n&&g(230),fe(t,n)}function Be(t){const n=ze();t.hasAttribute("data-lexical-row-striping")&&n.setRowStriping(!0),t.hasAttribute("data-lexical-frozen-column")&&n.setFrozenColumns(1),t.hasAttribute("data-lexical-frozen-row")&&n.setFrozenRows(1);const o=t.querySelector(":scope > colgroup");if(o){let e=[];for(const t of o.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!l.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&n.setColWidths(e)}return{after:t=>e.$descendantsMatching(t,C),node:n}}function ze(){return t.$applyNodeReplacement(new He)}function Ye(e){return e instanceof He}function Ue(e){C(e.getParent())?e.isEmpty()&&e.append(t.$createParagraphNode()):e.remove()}function Xe(t){Ye(t.getParent())?e.$unwrapAndFilterDescendants(t,d):t.remove()}function Ge(n){e.$unwrapAndFilterDescendants(n,C);const[o]=L(n,null,null),r=o.reduce((e,t)=>Math.max(e,t.length),0),l=n.getChildren();for(let e=0;e<o.length;++e){const n=l[e];if(!n)continue;C(n)||g(254,n.constructor.name,n.getType());const s=o[e].reduce((e,t)=>t?1+e:e,0);if(s!==r)for(let e=s;e<r;++e){const e=u();e.append(t.$createParagraphNode()),n.append(e)}}const s=n.getColWidths(),i=n.getColumnCount();if(s&&s.length!==i){let e;if(i<s.length)e=s.slice(0,i);else if(s.length>0){const t=s[s.length-1];e=[...s,...Array(i-s.length).fill(t)]}n.setColWidths(e)}}function qe(n){if(n.detail<3||!t.isDOMNode(n.target))return!1;const o=t.$getNearestNodeFromDOMNode(n.target);if(null===o)return!1;const r=e.$findMatchingParent(o,e=>t.$isElementNode(e)&&!e.isInline());if(null===r)return!1;return!!d(r.getParent())&&(r.select(0),!0)}function Je(){const e=t.$getSelection();if(!t.$isRangeSelection(e))return!1;const n=xe(e.anchor.getNode());if(null===n)return!1;const o=t.$getRoot();if(!o.is(n.getParent())||1!==o.getChildrenSize())return!1;const[r]=L(n,null,null);if(0===r.length||0===r[0].length)return!1;const l=r[0][0];if(!l||!l.cell)return!1;const s=r[r.length-1],i=s[s.length-1];if(!i||!i.cell)return!1;const a=q(n,l.cell,i.cell);return t.$setSelection(a),!0}function je(t){return t.registerNodeTransform(i,t=>{if(t.getColSpan()>1||t.getRowSpan()>1){const[,,n]=H(t),[o]=k(n,t,t),r=o.length,l=o[0].length;let s=n.getFirstChild();C(s)||g(175);const i=[];for(let t=0;t<r;t++){0!==t&&(s=s.getNextSibling(),C(s)||g(175));let n=null;for(let r=0;r<l;r++){const l=o[t][r],a=l.cell;if(l.startRow===t&&l.startColumn===r)n=a,i.push(a);else if(a.getColSpan()>1||a.getRowSpan()>1){d(a)||g(176);const t=u(a.__headerState);null!==n?n.insertAfter(t):e.$insertFirst(s,t)}}}for(const e of i)e.setColSpan(1),e.setRowSpan(1)}})}function Ve(n,o=!0){const r=new V,l=(e,t,l)=>{const s=te(e,l),i=ae(e,s,n,o,r);r.observers.set(t,[i,s])};return e.mergeRegister(ie(n,r),n.registerCommand(t.SELECTION_CHANGE_COMMAND,()=>ce(r,n),t.COMMAND_PRIORITY_HIGH),n.registerMutationListener(He,e=>{n.getEditorState().read(()=>{for(const[t,n]of e){const e=r.observers.get(t);if("created"===n||"updated"===n){const{tableNode:n,tableElement:o}=j(t);void 0===e?l(n,t,o):o!==e[1]&&(e[0].removeListeners(),r.observers.delete(t),l(n,t,o))}else"destroyed"===n&&void 0!==e&&(e[0].removeListeners(),r.observers.delete(t))}},{editor:n})},{skipInitialization:!1}),()=>{for(const[,[e]]of r.observers)e.removeListeners()})}function Qe(o,r){o.hasNodes([He])||g(255);const{hasNestedTables:l=n.signal(!1)}=r??{};return e.mergeRegister(o.registerCommand(h,n=>function({rows:n,columns:o,includeHeaders:r},l){const s=t.$getSelection()||t.$getPreviousSelection();if(!s||!t.$isRangeSelection(s))return!1;if(!l&&xe(s.anchor.getNode()))return!1;const i=_(Number(n),Number(o),r);e.$insertNodeToNearestRoot(i);const a=i.getFirstDescendant();return t.$isTextNode(a)&&a.select(),!0}(n,l.peek()),t.COMMAND_PRIORITY_EDITOR),o.registerCommand(t.SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,(n,r)=>o===r&&function(n,o){const{nodes:r,selection:l}=n;if(!r.some(t=>Ye(t)||e.$dfs(t).some(e=>Ye(e.node))))return!1;const s=X(l),i=t.$isRangeSelection(l);if(!(i&&null!==e.$findMatchingParent(l.anchor.getNode(),e=>d(e))&&null!==e.$findMatchingParent(l.focus.getNode(),e=>d(e))||s))return!1;if(1===r.length&&Ye(r[0]))return function(n,o){const r=o.getStartEndPoints(),l=X(o);if(null===r)return!1;const[s,i]=r,[a,c,u]=H(s),h=e.$findMatchingParent(i.getNode(),e=>d(e));if(!(d(a)&&d(h)&&C(c)&&Ye(u)))return!1;const[g,f,m]=k(u,a,h),[p]=L(n,null,null),_=g.length,S=_>0?g[0].length:0;let N=f.startRow,b=f.startColumn,w=p.length,y=w>0?p[0].length:0;if(l){const e=W(g,f,m),t=e.maxRow-e.minRow+1,n=e.maxColumn-e.minColumn+1;N=e.minRow,b=e.minColumn,w=Math.min(w,t),y=Math.min(y,n)}let T=!1;const R=Math.min(_,N+w)-1,x=Math.min(S,b+y)-1,M=new Set;for(let e=N;e<=R;e++)for(let t=b;t<=x;t++){const n=g[e][t];M.has(n.cell.getKey())||(1===n.cell.__rowSpan&&1===n.cell.__colSpan||(I(n.cell),M.add(n.cell.getKey()),T=!0))}let[O]=L(u.getWritable(),null,null);const A=w-_+N;for(let e=0;e<A;e++){$(O[_-1][0].cell)}const v=y-S+b;for(let e=0;e<v;e++){E(O[0][S-1].cell,!0,!1)}[O]=L(u.getWritable(),null,null);for(let e=N;e<N+w;e++)for(let n=b;n<b+y;n++){const o=e-N,r=n-b,l=p[o][r];if(l.startRow!==o||l.startColumn!==r)continue;const s=l.cell;if(1!==s.__rowSpan||1!==s.__colSpan){const t=[],o=Math.min(e+s.__rowSpan,N+w)-1,r=Math.min(n+s.__colSpan,b+y)-1;for(let l=e;l<=o;l++)for(let e=n;e<=r;e++){const n=O[l][e];t.push(n.cell)}K(t),T=!0}const{cell:i}=O[e][n],a=s.getBackgroundColor();null!=a&&i.setBackgroundColor(a);const c=i.getChildren();s.getChildren().forEach(e=>{if(t.$isTextNode(e)){t.$createParagraphNode().append(e),i.append(e)}else i.append(e)}),c.forEach(e=>e.remove())}if(l&&T){const[e]=L(u.getWritable(),null,null);e[f.startRow][f.startColumn].cell.selectEnd()}return!0}(r[0],l);if(i&&o.peek()&&!function(e){if(X(e)&&!e.focus.getNode().is(e.anchor.getNode()))return!0;if(t.$isRangeSelection(e)&&d(e.anchor.getNode())&&!e.anchor.getNode().is(e.focus.getNode()))return!0;return!1}(l))return!1;return!0}(n,l),t.COMMAND_PRIORITY_EDITOR),o.registerCommand(t.SELECT_ALL_COMMAND,Je,t.COMMAND_PRIORITY_LOW),o.registerCommand(t.CLICK_COMMAND,qe,t.COMMAND_PRIORITY_EDITOR),o.registerNodeTransform(He,Ge),o.registerNodeTransform(f,Xe),o.registerNodeTransform(i,Ue))}const Ze=t.defineExtension({build:(e,t,o)=>n.namedSignals(t),config:t.safeCast({hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasTabHandler:!0}),name:"@lexical/table/Table",nodes:()=>[He,f,i],register(o,r,l){const s=l.getOutput();return e.mergeRegister(n.effect(()=>{const e=s.hasHorizontalScroll.value;ke(o)!==e&&(Le(o,e),o.update(t.$fullReconcile))}),Qe(o,s),n.effect(()=>Ve(o,s.hasTabHandler.value)),n.effect(()=>s.hasCellMerge.value?void 0:je(o)),n.effect(()=>s.hasCellBackgroundColor.value?void 0:o.registerNodeTransform(i,e=>{null!==e.getBackgroundColor()&&e.setBackgroundColor(null)})))}});function et(e){const n=[];let o=null;const r=()=>{if(null!==o){const e=o.getFirstChild();t.$isLineBreakNode(e)&&1===o.getChildrenSize()&&e.remove()}};for(const l of e)t.$isInlineElementOrDecoratorNode(l)||t.$isTextNode(l)||t.$isLineBreakNode(l)?null!==o?o.append(l):(o=t.$createParagraphNode().append(l),n.push(o)):(r(),n.push(l),o=null);return r(),0===n.length&&n.push(t.$createParagraphNode()),n}const tt={$accepts:C,$packageRun:e=>e.every(d)?[p().splice(0,0,e)]:[],name:"TableSchema"},nt={$accepts:d,name:"TableRowSchema"},ot=[r.defineImportRule({$import:(t,n)=>{const o=ze();n.hasAttribute("data-lexical-row-striping")&&o.setRowStriping(!0),n.hasAttribute("data-lexical-frozen-column")&&o.setFrozenColumns(1),n.hasAttribute("data-lexical-frozen-row")&&o.setFrozenRows(1);const r=n.querySelector(":scope > colgroup");if(r){let e=[];for(const t of r.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!l.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&o.setColWidths(e)}return[o.splice(0,0,e.$descendantsMatching(t.$importChildren(n),C))]},match:r.sel.tag("table"),name:"@lexical/table/table"}),r.defineImportRule({$import:(t,n)=>[p(l.test(n.style.height)?parseFloat(n.style.height):void 0).splice(0,0,e.$descendantsMatching(t.$importChildren(n),d))],match:r.sel.tag("tr"),name:"@lexical/table/tr"}),r.defineImportRule({$import:(e,n)=>{const o="TH"===n.nodeName,i=l.test(n.style.width)?parseFloat(n.style.width):void 0;let a=s.NO_STATUS;if(o){const e=n.getAttribute("scope");if("col"===e)a=s.COLUMN;else if("row"===e)a=s.ROW;else{const e=n.parentElement,o=t.isHTMLTableRowElement(e)&&(e.parentElement&&"THEAD"===e.parentElement.nodeName||0===e.rowIndex),r=0===n.cellIndex;o&&(a|=s.ROW),r&&(a|=s.COLUMN),a===s.NO_STATUS&&(a=s.ROW)}}const c=u(a,n.colSpan,i);c.__rowSpan=n.rowSpan;const d=n.style.backgroundColor;""!==d&&(c.__backgroundColor=d);const h=n.style.verticalAlign;(function(e){return"middle"===e||"bottom"===e})(h)&&(c.__verticalAlign=h);const g=e.get(r.ImportTextFormat),f=g|function(e){let n=0;const o=e.fontWeight;"700"!==o&&"bold"!==o||(n|=t.IS_BOLD),"italic"===e.fontStyle&&(n|=t.IS_ITALIC);const r=(e.textDecoration||"").split(" ");return r.includes("underline")&&(n|=t.IS_UNDERLINE),r.includes("line-through")&&(n|=t.IS_STRIKETHROUGH),n}(n.style),m=e.get(r.ImportTextStyle),p=n.style.color,C=p?{...m,color:p}:m,_=[];return f!==g&&_.push(r.contextValue(r.ImportTextFormat,f)),C!==m&&_.push(r.contextValue(r.ImportTextStyle,C)),[c.splice(0,0,et(e.$importChildren(n,{context:_})))]},match:r.sel.tag("td","th"),name:"@lexical/table/cell"})],rt=t.defineExtension({dependencies:[r.CoreImportExtension,Ze,t.configExtension(r.DOMImportExtension,{rules:ot})],name:"@lexical/table/Import"});exports.$computeTableMap=k,exports.$computeTableMapSkipCellCheck=L,exports.$createTableCellNode=u,exports.$createTableNode=ze,exports.$createTableNodeWithDimensions=_,exports.$createTableRowNode=p,exports.$createTableSelection=G,exports.$createTableSelectionFrom=q,exports.$deleteTableColumn=function(e,t){const n=e.getChildren();for(let e=0;e<n.length;e++){const o=n[e];if(C(o)){const e=o.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");e[t].remove()}}return e},exports.$deleteTableColumnAtSelection=A,exports.$deleteTableColumn__EXPERIMENTAL=v,exports.$deleteTableRowAtSelection=M,exports.$deleteTableRow__EXPERIMENTAL=O,exports.$findCellNode=Re,exports.$findTableNode=xe,exports.$getElementForTableNode=We,exports.$getNodeTriplet=H,exports.$getTableAndElementByKey=j,exports.$getTableCellNodeFromLexicalNode=function(t){const n=e.$findMatchingParent(t,e=>d(e));return d(n)?n:null},exports.$getTableCellNodeRect=z,exports.$getTableColumnIndexFromTableCellNode=function(e){return S(e).getChildren().findIndex(t=>t.is(e))},exports.$getTableNodeFromLexicalNodeOrThrow=N,exports.$getTableRowIndexFromTableCellNode=function(e){const t=S(e);return N(t).getChildren().findIndex(e=>e.is(t))},exports.$getTableRowNodeFromTableCellNodeOrThrow=S,exports.$insertTableColumn=function(e,n,o=!0,r,l){const i=e.getChildren(),a=[];for(let e=0;e<i.length;e++){const o=i[e];if(C(o))for(let e=0;e<r;e++){const e=o.getChildren();if(n>=e.length||n<0)throw new Error("Table column target index out of range");const r=e[n];d(r)||g(12);const{left:i,right:c}=b(r,l);let h=s.NO_STATUS;(i&&i.hasHeaderState(s.ROW)||c&&c.hasHeaderState(s.ROW))&&(h|=s.ROW);const f=u(h);f.append(t.$createParagraphNode()),a.push({newTableCell:f,targetCell:r})}}return a.forEach(({newTableCell:e,targetCell:t})=>{o?t.insertAfter(e):t.insertBefore(e)}),e},exports.$insertTableColumnAtSelection=R,exports.$insertTableColumn__EXPERIMENTAL=x,exports.$insertTableRow=function(e,n,o=!0,r,l){const i=e.getChildren();if(n>=i.length||n<0)throw new Error("Table row target index out of range");const a=i[n];if(!C(a))throw new Error("Row before insertion index does not exist.");for(let e=0;e<r;e++){const e=a.getChildren(),n=e.length,r=p();for(let o=0;o<n;o++){const n=e[o];d(n)||g(12);const{above:i,below:a}=b(n,l);let c=s.NO_STATUS;const h=i&&i.getWidth()||a&&a.getWidth()||void 0;(i&&i.hasHeaderState(s.COLUMN)||a&&a.hasHeaderState(s.COLUMN))&&(c|=s.COLUMN);const f=u(c,1,h);f.append(t.$createParagraphNode()),r.append(f)}o?a.insertAfter(r):a.insertBefore(r)}return e},exports.$insertTableRowAtSelection=y,exports.$insertTableRow__EXPERIMENTAL=T,exports.$isScrollableTablesActive=ke,exports.$isSimpleTable=B,exports.$isTableCellNode=d,exports.$isTableNode=Ye,exports.$isTableRowNode=C,exports.$isTableSelection=X,exports.$mergeCells=K,exports.$moveTableColumn=function(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!B(e))return;e.getChildren().filter(C).forEach(e=>{const o=e.getChildren(),[r]=o.splice(t,1);o.splice(n,0,r),e.splice(0,o.length,o)});const r=e.getColWidths();if(r&&r.length===o){const o=[...r],[l]=o.splice(t,1);o.splice(n,0,l),e.setColWidths(o)}},exports.$removeTableRowAtIndex=function(e,t){const n=e.getChildren();if(t>=n.length||t<0)throw new Error("Expected table cell to be inside of table row.");return n[t].remove(),e},exports.$unmergeCell=function(){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=e.$findMatchingParent(o,d);return d(r)||g(148),I(r)},exports.INSERT_TABLE_COMMAND=h,exports.TableCellHeaderStates=s,exports.TableCellNode=i,exports.TableExtension=Ze,exports.TableImportExtension=rt,exports.TableImportRules=ot,exports.TableNode=He,exports.TableObserver=Q,exports.TableRowNode=f,exports.TableRowSchema=nt,exports.TableSchema=tt,exports.applyTableHandlers=ae,exports.getDOMCellFromTarget=he,exports.getTableElement=te,exports.getTableObserverFromTableElement=de,exports.registerTableCellUnmergeTransform=je,exports.registerTablePlugin=Qe,exports.registerTableSelectionObserver=Ve,exports.setScrollableTablesActive=Le;
++"use strict";var e=require("@lexical/utils"),t=require("lexical"),n=require("@lexical/extension"),o=require("@lexical/clipboard"),r=require("@lexical/html");const l=/^(\d+(?:\.\d+)?)px$/,s={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1};class i extends t.ElementNode{__colSpan;__rowSpan;__headerState;__width;__backgroundColor;__verticalAlign;static getType(){return"tablecell"}static clone(e){return new i(e.__headerState,e.__colSpan,e.__width,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__rowSpan=e.__rowSpan,this.__backgroundColor=e.__backgroundColor,this.__verticalAlign=e.__verticalAlign,this.__colSpan=e.__colSpan,this.__headerState=e.__headerState,this.__width=e.__width}static importDOM(){return{td:e=>({conversion:c,priority:0}),th:e=>({conversion:c,priority:0})}}static importJSON(e){return u().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeaderStyles(e.headerState).setColSpan(e.colSpan||1).setRowSpan(e.rowSpan||1).setWidth(e.width||void 0).setBackgroundColor(e.backgroundColor||null).setVerticalAlign(e.verticalAlign||void 0)}constructor(e=s.NO_STATUS,t=1,n,o){super(o),this.__colSpan=t,this.__rowSpan=1,this.__headerState=e,this.__width=n,this.__backgroundColor=null,this.__verticalAlign=void 0}createDOM(t){const n=document.createElement(this.getTag());return this.__width&&(n.style.width=`${this.__width}px`),this.__colSpan>1&&(n.colSpan=this.__colSpan),this.__rowSpan>1&&(n.rowSpan=this.__rowSpan),null!==this.__backgroundColor&&(n.style.backgroundColor=this.__backgroundColor),a(this.__verticalAlign)&&(n.style.verticalAlign=this.__verticalAlign),e.addClassNamesToElement(n,t.theme.tableCell,this.hasHeader()&&t.theme.tableCellHeader),n}exportDOM(e){const n=super.exportDOM(e);if(t.isHTMLElement(n.element)){const e=n.element;e.setAttribute("data-temporary-table-cell-lexical-key",this.getKey()),e.style.border="1px solid black",this.__colSpan>1&&(e.colSpan=this.__colSpan),this.__rowSpan>1&&(e.rowSpan=this.__rowSpan),e.style.width=`${this.getWidth()||75}px`,e.style.verticalAlign=this.getVerticalAlign()||"top",e.style.textAlign="start",null===this.__backgroundColor&&this.hasHeader()&&(e.style.backgroundColor="#f2f3f5")}return n}exportJSON(){return{...super.exportJSON(),...a(this.__verticalAlign)&&{verticalAlign:this.__verticalAlign},backgroundColor:this.getBackgroundColor(),colSpan:this.__colSpan,headerState:this.__headerState,rowSpan:this.__rowSpan,width:this.getWidth()}}getColSpan(){return this.getLatest().__colSpan}setColSpan(e){const t=this.getWritable();return t.__colSpan=e,t}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(e){const t=this.getWritable();return t.__rowSpan=e,t}getTag(){return this.hasHeader()?"th":"td"}setHeaderStyles(e,t=s.BOTH){const n=this.getWritable();return n.__headerState=e&t|n.__headerState&~t,n}getHeaderStyles(){return this.getLatest().__headerState}setWidth(e){const t=this.getWritable();return t.__width=e,t}getWidth(){return this.getLatest().__width}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(e){const t=this.getWritable();return t.__backgroundColor=e,t}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(e){const t=this.getWritable();return t.__verticalAlign=e||void 0,t}toggleHeaderStyle(e){const t=this.getWritable();return(t.__headerState&e)===e?t.__headerState-=e:t.__headerState+=e,t}hasHeaderState(e){return(this.getHeaderStyles()&e)===e}hasHeader(){return this.getLatest().__headerState!==s.NO_STATUS}updateDOM(e){return e.__headerState!==this.__headerState||e.__width!==this.__width||e.__colSpan!==this.__colSpan||e.__rowSpan!==this.__rowSpan||e.__backgroundColor!==this.__backgroundColor||e.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}}function a(e){return"middle"===e||"bottom"===e}function c(e){const n=e,o=e.nodeName.toLowerCase();let r;l.test(n.style.width)&&(r=parseFloat(n.style.width));let i=s.NO_STATUS;if("th"===o){const e=n.getAttribute("scope");if("col"===e)i=s.COLUMN;else if("row"===e)i=s.ROW;else{const e=n.parentElement,o=t.isHTMLElement(e)&&"tr"===e.nodeName.toLowerCase()&&t.isHTMLElement(e.parentElement)&&("thead"===e.parentElement.nodeName.toLowerCase()||0===e.rowIndex),r=0===n.cellIndex;o&&(i|=s.ROW),r&&(i|=s.COLUMN),i===s.NO_STATUS&&(i=s.ROW)}}const c=u(i,n.colSpan,r);c.__rowSpan=n.rowSpan;const d=n.style.backgroundColor;""!==d&&(c.__backgroundColor=d);const h=n.style.verticalAlign;a(h)&&(c.__verticalAlign=h);const g=n.style,f=(g&&g.textDecoration||"").split(" "),m="700"===g.fontWeight||"bold"===g.fontWeight,p=f.includes("line-through"),C="italic"===g.fontStyle,_=f.includes("underline"),S=g.color;return{after:e=>{const n=[];let o=null;const r=()=>{if(o){const e=o.getFirstChild();t.$isLineBreakNode(e)&&1===o.getChildrenSize()&&e.remove()}};for(const l of e)if(t.$isInlineElementOrDecoratorNode(l)||t.$isTextNode(l)||t.$isLineBreakNode(l)){if(t.$isTextNode(l)&&(m&&l.toggleFormat("bold"),p&&l.toggleFormat("strikethrough"),C&&l.toggleFormat("italic"),_&&l.toggleFormat("underline"),S)){const e=l.getStyle();e.includes("color:")||l.setStyle(e+`color: ${S};`)}o?o.append(l):(o=t.$createParagraphNode().append(l),n.push(o))}else n.push(l),r(),o=null;return r(),0===n.length&&n.push(t.$createParagraphNode()),n},node:c}}function u(e=s.NO_STATUS,n=1,o){return t.$applyNodeReplacement(new i(e,n,o))}function d(e){return e instanceof i}const h=t.createCommand("INSERT_TABLE_COMMAND");function g(e,...t){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(const e of t)o.append("v",e);throw n.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}class f extends t.ElementNode{__height;static getType(){return"tablerow"}static clone(e){return new f(e.__height,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__height=e.__height}static importDOM(){return{tr:e=>({conversion:m,priority:0})}}static importJSON(e){return p().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeight(e.height)}constructor(e,t){super(t),this.__height=e}exportJSON(){const e=this.getHeight();return{...super.exportJSON(),...void 0===e?void 0:{height:e}}}createDOM(t){const n=document.createElement("tr");return this.__height&&(n.style.height=`${this.__height}px`),e.addClassNamesToElement(n,t.theme.tableRow),n}extractWithChild(e,t,n){return"html"===n}isShadowRoot(){return!0}setHeight(e){const t=this.getWritable();return t.__height=e,t}getHeight(){return this.getLatest().__height}updateDOM(e){return e.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}}function m(t){const n=t;let o;return l.test(n.style.height)&&(o=parseFloat(n.style.height)),{after:t=>e.$descendantsMatching(t,d),node:p(o)}}function p(e){return t.$applyNodeReplacement(new f(e))}function C(e){return e instanceof f}function _(e,n,o=!0){const r=ze();for(let l=0;l<e;l++){const e=p();for(let r=0;r<n;r++){let n=s.NO_STATUS;"object"==typeof o?(0===l&&o.rows&&(n|=s.ROW),0===r&&o.columns&&(n|=s.COLUMN)):o&&(0===l&&(n|=s.ROW),0===r&&(n|=s.COLUMN));const i=u(n),a=t.$createParagraphNode();a.append(t.$createTextNode()),i.append(a),e.append(i)}r.append(e)}return r}function S(t){const n=e.$findMatchingParent(t,e=>C(e));if(C(n))return n;throw new Error("Expected table cell to be inside of table row.")}function N(t){const n=e.$findMatchingParent(t,e=>Ye(e));if(Ye(n))return n;throw new Error("Expected table cell to be inside of table.")}function b(e,t){const n=N(e),{x:o,y:r}=n.getCordsFromCellNode(e,t);return{above:n.getCellNodeFromCords(o,r-1,t),below:n.getCellNodeFromCords(o,r+1,t),left:n.getCellNodeFromCords(o-1,r,t),right:n.getCellNodeFromCords(o+1,r,t)}}const w=(e,t)=>e===s.BOTH||e===t?t:s.NO_STATUS;function y(e=!0){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=n.focus.getNode(),[l]=H(o),[s,,i]=H(r),[,a,c]=k(i,s,l),{startRow:u}=c,{startRow:d}=a;return e?$(u+l.__rowSpan>d+s.__rowSpan?l:s,!0):$(d<u?s:l,!1)}const T=y;function $(e,n=!0){const[,,o]=H(e),[r,l]=k(o,e,e),i=r[0].length,{startRow:a}=l;let c=null;if(n){const n=a+e.__rowSpan-1,l=r[n],d=p();for(let e=0;e<i;e++){const{cell:o,startRow:r}=l[e];if(r+o.__rowSpan-1<=n){const n=l[e].cell.__headerState,o=w(n,s.COLUMN);d.append(u(o).append(t.$createParagraphNode()))}else o.setRowSpan(o.__rowSpan+1)}const h=o.getChildAtIndex(n);C(h)||g(256),h.insertAfter(d),c=d}else{const e=a,n=r[e],l=p();for(let o=0;o<i;o++){const{cell:r,startRow:i}=n[o];if(i===e){const e=n[o].cell.__headerState,r=w(e,s.COLUMN);l.append(u(r).append(t.$createParagraphNode()))}else r.setRowSpan(r.__rowSpan+1)}const d=o.getChildAtIndex(e);C(d)||g(257),d.insertBefore(l),c=l}return c}function R(e=!0){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=n.focus.getNode(),[l]=H(o),[s,,i]=H(r),[,a,c]=k(i,s,l),{startColumn:u}=c,{startColumn:d}=a;return e?E(u+l.__colSpan>d+s.__colSpan?l:s,!0):E(d<u?s:l,!1)}const x=R;function E(e,n=!0,o=!0){const[,,r]=H(e),[l,i]=k(r,e,e),a=l.length,{startColumn:c}=i,d=n?c+e.__colSpan-1:c-1,h=r.getFirstChild();C(h)||g(120);let f=null;function m(e=s.NO_STATUS){const n=u(e).append(t.$createParagraphNode());return null===f&&(f=n),n}let p=h;e:for(let e=0;e<a;e++){if(0!==e){const e=p.getNextSibling();C(e)||g(121),p=e}const t=l[e],n=t[d<0?0:d].cell.__headerState,o=w(n,s.ROW);if(d<0){P(p,m(o));continue}const{cell:r,startColumn:i,startRow:a}=t[d];if(i+r.__colSpan-1<=d){let n=r,l=a,s=d;for(;l!==e&&n.__rowSpan>1;){if(s-=r.__colSpan,!(s>=0)){p.append(m(o));continue e}{const{cell:e,startRow:o}=t[s];n=e,l=o}}n.insertAfter(m(o))}else r.setColSpan(r.__colSpan+1)}null!==f&&o&&F(f);const _=r.getColWidths();if(_){const e=[..._],t=d<0?0:d,n=e[t];e.splice(t,0,n),r.setColWidths(e)}return f}function M(){const e=t.$getSelection();t.$isRangeSelection(e)||X(e)||g(188);const[n,o]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[r,,l]=H(n),[s]=H(o),[i,a,c]=k(l,r,s),{startRow:u}=a,{startRow:d}=c,h=d+s.__rowSpan-1;if(i.length===h-u+1)return void l.remove();const f=i[0].length,m=i[h+1],p=l.getChildAtIndex(h+1);for(let e=h;e>=u;e--){for(let t=f-1;t>=0;t--){const{cell:n,startRow:o,startColumn:r}=i[e][t];if(r===t){if(o<u||o+n.__rowSpan-1>h){const e=Math.max(o,u),t=Math.min(n.__rowSpan+o-1,h),r=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-r)}if(o>=u&&o+n.__rowSpan-1>h&&e===h){null===p&&g(122);let o=null;for(let n=0;n<t;n++){const t=m[n],r=t.cell;t.startRow===e+1&&(o=r),r.__colSpan>1&&(n+=r.__colSpan-1)}null===o?P(p,n):o.insertAfter(n)}}}const t=l.getChildAtIndex(e);C(t)||g(206,String(e)),t.remove()}if(void 0!==m){const{cell:e}=m[0];F(e)}else{const e=i[u-1],{cell:t}=e[0];F(t)}}const O=M;function A(){const e=t.$getSelection();t.$isRangeSelection(e)||X(e)||g(188);const n=e.anchor.getNode(),o=e.focus.getNode(),[r,,l]=H(n),[s]=H(o),[i,a,c]=k(l,r,s),{startColumn:u}=a,{startRow:d,startColumn:h}=c,f=Math.min(u,h),m=Math.max(u+r.__colSpan-1,h+s.__colSpan-1),p=m-f+1;if(i[0].length===m-f+1)return l.selectPrevious(),void l.remove();const C=i.length;for(let e=0;e<C;e++)for(let t=f;t<=m;t++){const{cell:n,startColumn:o}=i[e][t];if(o<f){if(t===f){const e=f-o;n.setColSpan(n.__colSpan-Math.min(p,n.__colSpan-e))}}else if(o+n.__colSpan-1>m){if(t===m){const e=m-o+1;n.setColSpan(n.__colSpan-e)}}else n.remove()}const _=i[d],S=u>h?_[u+r.__colSpan]:_[h+s.__colSpan];if(void 0!==S){const{cell:e}=S;F(e)}else{const e=h<u?_[h-1]:_[u-1],{cell:t}=e;F(t)}const N=l.getColWidths();if(N){const e=[...N];e.splice(f,p),l.setColWidths(e)}}const v=A;function F(e){const t=e.getFirstDescendant();null==t?e.selectStart():t.getParentOrThrow().selectStart()}function P(e,t){const n=e.getFirstChild();null!==n?n.insertBefore(t):e.append(t)}function K(e){if(0===e.length)return null;const n=N(e[0]),[o]=L(n,null,null);let r=1/0,l=-1/0,s=1/0,i=-1/0;const a=new Set;for(const t of o)for(const n of t){if(!n||!n.cell)continue;const t=n.cell.getKey();if(!a.has(t)&&e.some(e=>e.is(n.cell))){a.add(t);const e=n.startRow,o=n.startColumn,c=n.cell.__rowSpan||1,u=n.cell.__colSpan||1;r=Math.min(r,e),l=Math.max(l,e+c-1),s=Math.min(s,o),i=Math.max(i,o+u-1)}}if(r===1/0||s===1/0)return null;const c=l-r+1,u=i-s+1,d=o[r][s];if(!d.cell)return null;const h=d.cell;h.setColSpan(u),h.setRowSpan(c);const g=new Set([h.getKey()]);for(let e=r;e<=l;e++)for(let t=s;t<=i;t++){const n=o[e][t];if(!n.cell)continue;const r=n.cell,l=r.getKey();if(!g.has(l)){g.add(l);D(r)||h.append(...r.getChildren()),r.remove()}}return 0===h.getChildrenSize()&&h.append(t.$createParagraphNode()),h}function D(e){if(1!==e.getChildrenSize())return!1;const n=e.getFirstChildOrThrow();return!(!t.$isParagraphNode(n)||!n.isEmpty())}function I(e){const[n,o,r]=H(e),l=n.__colSpan,i=n.__rowSpan;if(1===l&&1===i)return;const[a,c]=k(r,n,n),{startColumn:d,startRow:h}=c,f=n.__headerState&s.COLUMN,m=Array.from({length:l},(e,t)=>{let n=f;for(let e=0;0!==n&&e<a.length;e++)n&=a[e][t+d].cell.__headerState;return n}),p=n.__headerState&s.ROW,_=Array.from({length:i},(e,t)=>{let n=p;for(let e=0;0!==n&&e<a[0].length;e++)n&=a[t+h][e].cell.__headerState;return n});if(l>1){for(let e=1;e<l;e++)n.insertAfter(u(m[e]|_[0]).append(t.$createParagraphNode()));n.setColSpan(1)}if(i>1){let e;for(let n=1;n<i;n++){const r=h+n,s=a[r];e=(e||o).getNextSibling(),C(e)||g(125);let i=null;for(let e=0;e<d;e++){const t=s[e],n=t.cell;t.startRow===r&&(i=n),n.__colSpan>1&&(e+=n.__colSpan-1)}if(null===i)for(let o=l-1;o>=0;o--)P(e,u(m[o]|_[n]).append(t.$createParagraphNode()));else for(let e=l-1;e>=0;e--)i.insertAfter(u(m[e]|_[n]).append(t.$createParagraphNode()))}n.setRowSpan(1)}}function k(e,t,n){const[o,r,l]=L(e,t,n);return null===r&&g(207),null===l&&g(208),[o,r,l]}function L(e,t,n){const o=[];let r=null,l=null;function s(e){let t=o[e];return void 0===t&&(o[e]=t=[]),t}const i=e.getChildren();for(let e=0;e<i.length;e++){const o=i[e];C(o)||g(209);const a=s(e);for(let c=o.getFirstChild(),u=0;null!=c;c=c.getNextSibling()){for(d(c)||g(147);void 0!==a[u];)u++;const o={cell:c,startColumn:u,startRow:e},{__rowSpan:h,__colSpan:f}=c;for(let t=0;t<h&&!(e+t>=i.length);t++){const n=s(e+t);for(let e=0;e<f;e++)n[u+e]=o}null!==t&&null===r&&t.is(c)&&(r=o),null!==n&&null===l&&n.is(c)&&(l=o)}}return[o,r,l]}function H(t){let n;if(t instanceof i)n=t;else if("__type"in t){const o=e.$findMatchingParent(t,d);d(o)||g(148),n=o}else{const o=e.$findMatchingParent(t.getNode(),d);d(o)||g(148),n=o}const o=n.getParent();C(o)||g(149);const r=o.getParent();return Ye(r)||g(210),[n,o,r]}function W(e,t,n){let o,r=Math.min(t.startColumn,n.startColumn),l=Math.min(t.startRow,n.startRow),s=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),i=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{o=!1;for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const a=e[t][n];if(!a)continue;const c=a.startColumn+a.cell.__colSpan-1,u=a.startRow+a.cell.__rowSpan-1,d=a.startColumn<=s&&c>=r,h=a.startRow<=i&&u>=l;if(d&&h){const e=Math.min(r,a.startColumn),t=Math.max(s,c),n=Math.min(l,a.startRow),d=Math.max(i,u);e===r&&t===s&&n===l&&d===i||(r=e,s=t,l=n,i=d,o=!0)}}}while(o);return{maxColumn:s,maxRow:i,minColumn:r,minRow:l}}function B(e){const t=e.getChildren();let n=null;for(const e of t){if(!C(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!d(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function z(e){const[t,,n]=H(e),o=n.getChildren(),r=o.length,l=o[0].getChildren().length,s=new Array(r);for(let e=0;e<r;e++)s[e]=new Array(l);for(let e=0;e<r;e++){const n=o[e].getChildren();let r=0;for(let o=0;o<n.length;o++){for(;s[e][r];)r++;const l=n[o],i=l.__rowSpan||1,a=l.__colSpan||1;for(let t=0;t<i;t++)for(let n=0;n<a;n++)s[e+t][r+n]=l;if(t===l)return{colSpan:a,columnIndex:r,rowIndex:e,rowSpan:i};r+=a}}return null}function Y(t){const[[n,o,r,l],[s,i,a,c]]=["anchor","focus"].map(n=>{const o=t[n].getNode(),r=e.$findMatchingParent(o,d);d(r)||g(238,n,o.getKey(),o.getType());const l=r.getParent();C(l)||g(239,n);const s=l.getParent();return Ye(s)||g(240,n),[o,r,l,s]});return l.is(c)||g(241),{anchorCell:o,anchorNode:n,anchorRow:r,anchorTable:l,focusCell:i,focusNode:s,focusRow:a,focusTable:c}}class U{tableKey;anchor;focus;_cachedNodes;dirty;constructor(e,t,n){this.anchor=t,this.focus=n,t._selection=this,n._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=e}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if("root"===this.tableKey||"root"===this.anchor.key||"element"!==this.anchor.type||"root"===this.focus.key||"element"!==this.focus.type)return!1;const e=t.$getNodeByKey(this.tableKey),n=t.$getNodeByKey(this.anchor.key),o=t.$getNodeByKey(this.focus.key);return null!==e&&null!==n&&null!==o}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return X(e)&&this.tableKey===e.tableKey&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)}set(e,t,n){this.dirty=this.dirty||e!==this.tableKey||t!==this.anchor.key||n!==this.focus.key,this.tableKey=e,this.anchor.key=t,this.focus.key=n,this._cachedNodes=null}clone(){return new U(this.tableKey,t.$createPoint(this.anchor.key,this.anchor.offset,this.anchor.type),t.$createPoint(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(e){}insertText(){}hasFormat(e){let n=0;this.getNodes().filter(d).forEach(e=>{const o=e.getFirstChild();t.$isParagraphNode(o)&&(n|=o.getTextFormat())});const o=t.TEXT_TYPE_TO_FORMAT[e];return 0!==(n&o)}insertNodes(e){const n=this.focus.getNode();t.$isElementNode(n)||g(151);t.$normalizeSelection__EXPERIMENTAL(n.select(0,n.getChildrenSize())).insertNodes(e)}getShape(){const{anchorCell:e,focusCell:t}=Y(this),n=z(e);null===n&&g(153);const o=z(t);null===o&&g(155);const r=Math.min(n.columnIndex,o.columnIndex),l=Math.max(n.columnIndex+n.colSpan-1,o.columnIndex+o.colSpan-1),s=Math.min(n.rowIndex,o.rowIndex),i=Math.max(n.rowIndex+n.rowSpan-1,o.rowIndex+o.rowSpan-1);return{fromX:Math.min(r,l),fromY:Math.min(s,i),toX:Math.max(r,l),toY:Math.max(s,i)}}getNodes(){if(!this.isValid())return[];const e=this._cachedNodes;if(null!==e)return e;const{anchorTable:n,anchorCell:o,focusCell:r}=Y(this),l=r.getParents()[1];if(l!==n){if(n.isParentOf(r)){const e=l.getParent();null==e&&g(159),this.set(this.tableKey,r.getKey(),e.getKey())}else{const e=n.getParent();null==e&&g(158),this.set(this.tableKey,e.getKey(),r.getKey())}return this.getNodes()}const[s,i,a]=k(n,o,r),{minColumn:c,maxColumn:u,minRow:d,maxRow:h}=W(s,i,a),f=new Map([[n.getKey(),n]]);let m=null;for(let e=d;e<=h;e++)for(let t=c;t<=u;t++){const{cell:n}=s[e][t],o=n.getParent();C(o)||g(160),o!==m&&(f.set(o.getKey(),o),m=o),f.has(n.getKey())||J(n,e=>{f.set(e.getKey(),e)})}const p=Array.from(f.values());return t.isCurrentlyReadOnlyMode()||(this._cachedNodes=p),p}getTextContent(){const e=this.getNodes().filter(e=>d(e));let t="";for(let n=0;n<e.length;n++){const o=e[n],r=o.__parent,l=(e[n+1]||{}).__parent;t+=o.getTextContent()+(l!==r?"\n":"\t")}return t}}function X(e){return e instanceof U}function G(){const e=t.$createPoint("root",0,"element"),n=t.$createPoint("root",0,"element");return new U("root",e,n)}function q(e,n,o){e.getKey(),n.getKey(),o.getKey();const r=t.$getSelection(),l=X(r)?r.clone():G();return l.set(e.getKey(),n.getKey(),o.getKey()),l}function J(e,n){const o=[[e]];for(let e=o.at(-1);void 0!==e&&o.length>0;e=o.at(-1)){const r=e.pop();void 0===r?o.pop():!1!==n(r)&&t.$isElementNode(r)&&o.push(r.getChildren())}}function j(e,n=t.$getEditor()){const o=t.$getNodeByKey(e);Ye(o)||g(231,e);const r=te(o,n.getElementByKey(e));return null===r&&g(232,e),{tableElement:r,tableNode:o}}class V{observers;nextFocus;shouldCheckSelectionForTable;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null}setNextFocus(e){this.nextFocus=e}getAndClearNextFocus(){const{nextFocus:e}=this;return null!==e&&(this.nextFocus=null),e}setShouldCheckSelectionForTable(e){this.shouldCheckSelectionForTable=e}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:e}=this;return e?(this.shouldCheckSelectionForTable=null,e):null}}class Q{focusX;focusY;listenersToRemove;table;isHighlightingCells;anchorX;anchorY;tableNodeKey;anchorCell;focusCell;anchorCellNodeKey;focusCellNodeKey;editor;tableSelection;hasHijackedSelectionStyles;isSelecting;pointerType;abortController;listenerOptions;constructor(e,t){this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=t,this.editor=e,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort("removeListeners"),Array.from(this.listenersToRemove).forEach(e=>e()),this.listenersToRemove.clear()}$lookup(){return j(this.tableNodeKey,this.editor)}trackTable(){const e=new MutationObserver(e=>{this.editor.getEditorState().read(()=>{let t=!1;for(let n=0;n<e.length;n++){const o=e[n].target.nodeName;if("TABLE"===o||"TBODY"===o||"THEAD"===o||"TR"===o){t=!0;break}}if(!t)return;const{tableNode:n,tableElement:o}=this.$lookup();this.table=fe(n,o)},{editor:this.editor})});this.editor.getEditorState().read(()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=fe(t,n),e.observe(n,{attributes:!0,childList:!0,subtree:!0})},{editor:this.editor})}$clearHighlight(e=!0){const n=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:o,tableElement:r}=this.$lookup();me(n,fe(o,r),null),e&&null!==t.$getSelection()&&(t.$setSelection(null),n.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0))}$enableHighlightStyle(){const t=this.editor,{tableElement:n}=this.$lookup();e.removeClassNamesFromElement(n,t._config.theme.tableSelection),n.classList.remove("disable-selection"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:t}=this.$lookup();e.addClassNamesToElement(t,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(e){if(null!==e){e.tableKey!==this.tableNodeKey&&g(233,e.tableKey,this.tableNodeKey);const t=this.editor;this.tableSelection=e,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),me(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=t.getDOMSelection(this.editor._window);e&&e.rangeCount>0&&e.removeAllRanges()}}$setFocusCellForSelection(e,n=!1){const o=this.editor,{tableNode:r}=this.$lookup(),l=e.x,s=e.y;if(this.focusCell=e,!this.isHighlightingCells){(n||this.anchorX!==l||this.anchorY!==s||null!=this.tableSelection&&null!=this.anchorCellNodeKey)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle())}if(-1!==this.focusX&&-1!==this.focusY&&l===this.focusX&&s===this.focusY)return!1;if(this.focusX=l,this.focusY=s,this.isHighlightingCells){const i=Pe(r,e.elem);if(null!=this.tableSelection&&null!=this.anchorCellNodeKey){let e=i;if(null===e&&n&&(e=r.getCellNodeFromCords(l,s,this.table)),null!==e){const n=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=e.getKey(),this.tableSelection=q(r,n,e),t.$setSelection(this.tableSelection),o.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0),me(o,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){return this.anchorCellNodeKey?t.$getNodeByKey(this.anchorCellNodeKey):null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&g(234),e}$getFocusTableCell(){return this.focusCellNodeKey?t.$getNodeByKey(this.focusCellNodeKey):null}$getFocusTableCellOrThrow(){const e=this.$getFocusTableCell();return null===e&&g(235),e}$setAnchorCellForSelection(e){this.isHighlightingCells=!1,this.anchorCell=e,this.anchorX=e.x,this.anchorY=e.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:t}=this.$lookup(),n=Pe(t,e.elem);if(null!==n){const e=n.getKey();null!=this.tableSelection?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(t.getKey(),e,e)):this.tableSelection=q(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const n=t.$getSelection();X(n)||g(236);const o=t.$createRangeSelection(),r=o.anchor,l=o.focus,s=n.getNodes().filter(d);s.length>0||g(237);const i=s[0].getFirstChild(),a=t.$isParagraphNode(i)?i.getFormatFlags(e,null):null;s.forEach(t=>{r.set(t.getKey(),0,"element"),l.set(t.getKey(),t.getChildrenSize(),"element"),o.formatText(e,a)}),t.$setSelection(n),this.editor.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}$clearText(){const{editor:e}=this,n=t.$getNodeByKey(this.tableNodeKey);if(!Ye(n))throw new Error("Expected TableNode.");const o=t.$getSelection();X(o)||g(253);const r=o.getNodes().filter(d),l=n.getFirstChild(),s=n.getLastChild();if(r.length>0&&null!==l&&null!==s&&C(l)&&C(s)&&r[0]===l.getFirstChild()&&r[r.length-1]===s.getLastChild()){n.selectPrevious();const o=n.getParent();return n.remove(),void(t.$isRootNode(o)&&o.isEmpty()&&e.dispatchCommand(t.INSERT_PARAGRAPH_COMMAND,void 0))}r.forEach(e=>{if(t.$isElementNode(e)){const n=t.$createParagraphNode();e.append(n),e.getChildren().forEach(e=>{e!==n&&e.remove()})}}),me(e,this.table,null),t.$setSelection(null),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}}const Z="__lexicalTableSelection";function ee(e){return t.isHTMLElement(e)&&"TABLE"===e.nodeName}function te(e,t){if(!t)return t;const n=ee(t)?t:t.querySelector("table");return ee(n)||g(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function ne(e){return e._window}function oe(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;d(n)&&(o=n)}return null}const re=[[t.KEY_ARROW_DOWN_COMMAND,"down"],[t.KEY_ARROW_UP_COMMAND,"up"],[t.KEY_ARROW_LEFT_COMMAND,"backward"],[t.KEY_ARROW_RIGHT_COMMAND,"forward"]],le=[t.DELETE_WORD_COMMAND,t.DELETE_LINE_COMMAND,t.DELETE_CHARACTER_COMMAND],se=[t.KEY_BACKSPACE_COMMAND,t.KEY_DELETE_COMMAND];function ie(e,n){return e.registerRootListener(o=>{if(null===o)return;const r=e._window;if(null===r)return;const l=r=>{const l=r.target;if(0!==r.button||!t.isDOMNode(l)||!o.contains(l))return;const s=function(e){const t=he(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if("TABLE"===n.nodeName&&Z in n&&n[Z])return{cellElement:t,tableElement:n,tableObserver:n[Z]};n=n.parentNode}return null}(l);e.update(()=>{if(X(t.$getSelection())){for(const[e]of n.observers.values())e.$clearHighlight(!1);t.$setSelection(null),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0)}if(!s)return;const{tableObserver:o,tableElement:l,cellElement:i}=s;!function(e,n,o,r,l,s){const i=e._window;if(!i)return;const a=n=>{if(l.isSelecting)return;l.isSelecting=!0,null!==n&&null===l.anchorCell&&e.update(()=>{l.$setAnchorCellForSelection(n)});const o=()=>{l.isSelecting=!1,i.removeEventListener("pointerup",o),i.removeEventListener("pointermove",a)},a=n=>{if(!(e=>!(1&~e.buttons))(n)&&l.isSelecting)return l.isSelecting=!1,i.removeEventListener("pointerup",o),void i.removeEventListener("pointermove",a);if(!t.isDOMNode(n.target))return;let c=null;const u=!(t.IS_FIREFOX||r.contains(n.target));if(u)c=ge(r,n.target);else for(const e of document.elementsFromPoint(n.clientX,n.clientY))if(c=ge(r,e),c)break;if(c){const n=c;null===l.anchorCell&&e.update(()=>{l.$setAnchorCellForSelection(n)}),null!==l.focusCell&&c.elem===l.focusCell.elem||(s.setNextFocus({focusCell:c,override:u,tableKey:l.tableNodeKey}),e.dispatchCommand(t.SELECTION_CHANGE_COMMAND,void 0))}};i.addEventListener("pointerup",o,l.listenerOptions),i.addEventListener("pointermove",a,l.listenerOptions)};l.pointerType=n.pointerType;const c=t.$getNodeByKeyOrThrow(l.tableNodeKey),u=t.$getPreviousSelection();if(t.IS_FIREFOX&&n.shiftKey&&we(u,c)&&(t.$isRangeSelection(u)||X(u))){const e=u.anchor.getNode(),t=oe(c,u.anchor.getNode());if(t)l.$setAnchorCellForSelection(Fe(l,t)),l.$setFocusCellForSelection(o),Oe(n);else{(c.isBefore(e)?c.selectStart():c.selectEnd()).anchor.set(u.anchor.key,u.anchor.offset,u.anchor.type)}}else"touch"!==n.pointerType&&l.$setAnchorCellForSelection(o);a(o)}(e,r,i,l,o,n)})};return r.addEventListener("pointerdown",l),()=>{r.removeEventListener("pointerdown",l)}})}function ae(n,r,l,s,i){const a=l.getRootElement(),c=ne(l);null!==a&&null!==c||g(246);const u=new Q(l,n.getKey()),h=te(n,r);!function(e,t){null!==de(e)&&g(205);e[Z]=t}(h,u),u.listenersToRemove.add(()=>function(e,t){de(e)===t&&delete e[Z]}(h,u));const f=e=>{if(e.detail>=3&&t.isDOMNode(e.target)){null!==he(e.target)&&e.preventDefault()}};h.addEventListener("mousedown",f,u.listenerOptions),u.listenersToRemove.add(()=>{h.removeEventListener("mousedown",f)});for(const[e,o]of re)u.listenersToRemove.add(l.registerCommand(e,e=>Me(l,e,o,n,u,i),t.COMMAND_PRIORITY_HIGH));u.listenersToRemove.add(l.registerCommand(t.KEY_ESCAPE_COMMAND,e=>{const o=t.$getSelection();if(X(o)){const t=oe(n,o.focus.getNode());if(null!==t)return Oe(e),t.selectEnd(),!0}return!1},t.COMMAND_PRIORITY_HIGH));const m=o=>()=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$clearText(),!0;if(t.$isRangeSelection(r)){if(!d(oe(n,r.anchor.getNode())))return!1;const l=r.anchor.getNode(),s=r.focus.getNode(),i=n.isParentOf(l),a=n.isParentOf(s);if(i&&!a||a&&!i)return u.$clearText(),!0;const c=e.$findMatchingParent(r.anchor.getNode(),e=>t.$isElementNode(e)),h=c&&e.$findMatchingParent(c,e=>t.$isElementNode(e)&&d(e.getParent()));if(!t.$isElementNode(h)||!t.$isElementNode(c))return!1;if(o===t.DELETE_LINE_COMMAND&&null===h.getPreviousSibling())return!0}return!1};for(const e of le)u.listenersToRemove.add(l.registerCommand(e,m(e),t.COMMAND_PRIORITY_HIGH));const p=e=>{const o=t.$getSelection();if(!X(o)&&!t.$isRangeSelection(o))return!1;const r=n.isParentOf(o.anchor.getNode());if(r!==n.isParentOf(o.focus.getNode())){const e=r?"anchor":"focus",t=r?"focus":"anchor",{key:l,offset:s,type:i}=o[t];return n[o[e].isBefore(o[t])?"selectPrevious":"selectNext"]()[t].set(l,s,i),!1}return!!we(o,n)&&(!!X(o)&&(e&&(e.preventDefault(),e.stopPropagation()),u.$clearText(),!0))};for(const e of se)u.listenersToRemove.add(l.registerCommand(e,p,t.COMMAND_PRIORITY_HIGH));return u.listenersToRemove.add(l.registerCommand(t.CUT_COMMAND,n=>{const r=t.$getSelection();if(r){if(!X(r)&&!t.$isRangeSelection(r))return!1;o.copyToClipboard(l,e.objectKlassEquals(n,ClipboardEvent)?n:null,o.$getClipboardDataFromSelection(r));const s=p(n);return t.$isRangeSelection(r)?(r.removeText(),!0):s}return!1},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FORMAT_TEXT_COMMAND,o=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$formatCells(o),!0;if(t.$isRangeSelection(r)){const t=e.$findMatchingParent(r.anchor.getNode(),e=>d(e));if(!d(t))return!1}return!1},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FORMAT_ELEMENT_COMMAND,e=>{const o=t.$getSelection();if(!X(o)||!we(o,n))return!1;const r=o.anchor.getNode(),l=o.focus.getNode();if(!d(r)||!d(l))return!1;if(function(e,t){if(X(e)){const n=e.anchor.getNode(),o=e.focus.getNode();if(t&&n&&o){const[e]=k(t,n,o);return n.getKey()===e[0][0].cell.getKey()&&o.getKey()===e[e.length-1].at(-1).cell.getKey()}}return!1}(o,n))return n.setFormat(e),!0;const[s,i,a]=k(n,r,l),c=Math.max(i.startRow+i.cell.__rowSpan-1,a.startRow+a.cell.__rowSpan-1),u=Math.max(i.startColumn+i.cell.__colSpan-1,a.startColumn+a.cell.__colSpan-1),h=Math.min(i.startRow,a.startRow),g=Math.min(i.startColumn,a.startColumn),f=new Set;for(let n=h;n<=c;n++)for(let o=g;o<=u;o++){const r=s[n][o].cell;if(f.has(r))continue;f.add(r),r.setFormat(e);const l=r.getChildren();for(let n=0;n<l.length;n++){const o=l[n];t.$isElementNode(o)&&!o.isInline()&&o.setFormat(e)}}return!0},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.CONTROLLED_TEXT_INSERTION_COMMAND,o=>{const r=t.$getSelection();if(!we(r,n))return!1;if(X(r))return u.$clearHighlight(),!1;if(t.$isRangeSelection(r)){const s=e.$findMatchingParent(r.anchor.getNode(),e=>d(e));if(!d(s))return!1;if("string"==typeof o){const e=ve(l,r,n);if(e)return Ae(e,n,[t.$createTextNode(o)]),!0}}return!1},t.COMMAND_PRIORITY_HIGH)),s&&u.listenersToRemove.add(l.registerCommand(t.KEY_TAB_COMMAND,o=>{const r=t.$getSelection();if(!t.$isRangeSelection(r)||!r.isCollapsed()||!we(r,n))return!1;const l=Re(r.anchor.getNode());return!(null===l||!n.is(xe(l)))&&(Oe(o),function(n,o){const r="next"===o?"getNextSibling":"getPreviousSibling",l="next"===o?"getFirstChild":"getLastChild",s=n[r]();if(t.$isElementNode(s))return s.selectEnd();const i=e.$findMatchingParent(n,C);null===i&&g(247);for(let e=i[r]();C(e);e=e[r]()){const n=e[l]();if(t.$isElementNode(n))return n.selectEnd()}const a=e.$findMatchingParent(i,Ye);null===a&&g(248);"next"===o?a.selectNext():a.selectPrevious()}(l,o.shiftKey?"previous":"next"),!0)},t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.FOCUS_COMMAND,e=>n.isSelected(),t.COMMAND_PRIORITY_HIGH)),u.listenersToRemove.add(l.registerCommand(t.INSERT_PARAGRAPH_COMMAND,()=>{const e=t.$getSelection();if(!t.$isRangeSelection(e)||!e.isCollapsed()||!we(e,n))return!1;const o=ve(l,e,n);return!!o&&(Ae(o,n),!0)},t.COMMAND_PRIORITY_HIGH)),u}function ce(n,o){const r=t.$getSelection(),l=t.$getPreviousSelection(),s=n.getAndClearNextFocus();if(null!==s){const{tableKey:e,focusCell:t}=s,o=n.observers.get(e);o||g(335,e);const[l]=o;if(X(r)&&r.tableKey===l.tableNodeKey)return(t.x!==l.focusX||t.y!==l.focusY)&&(l.$setFocusCellForSelection(t),!0);if(null!==l.anchorCell&&null!==l.anchorCellNodeKey&&t.elem!==l.anchorCell.elem&&null!==l.tableSelection)return l.$setFocusCellForSelection(t,!0),!0}const i=n.getAndClearShouldCheckSelectionForTable();if(i&&t.$isRangeSelection(l)&&t.$isRangeSelection(r)&&r.isCollapsed()){const n=t.$getNodeByKeyOrThrow(i),o=r.anchor.getNode(),l=n.getFirstChild(),s=Re(o);if(null!==s&&C(l)){const t=l.getFirstChild();if(d(t)&&n.is(e.$findMatchingParent(s,e=>e.is(n)||e.is(t))))return t.selectStart(),!0}}X(r)&&function(e,n){const o=ne(e),r=t.$getPreviousSelection();if(!n.is(r))return;const l=t.$getNodeByKeyOrThrow(n.tableKey),s=t.getDOMSelection(o);if(s&&s.anchorNode&&s.focusNode){const o=t.$getNearestNodeFromDOMNode(s.focusNode),r=o&&!l.isParentOf(o),i=t.$getNearestNodeFromDOMNode(s.anchorNode),a=i&&l.isParentOf(i);if(r&&a&&s.rangeCount>0){const o=t.$createRangeSelectionFromDom(s,e);o&&(o.anchor.set(l.getKey(),n.isBackward()?l.getChildrenSize():0,"element"),s.removeAllRanges(),t.$setSelection(o))}}}(o,r),t.$isRangeSelection(r)&&function(e,n){const o=t.$getPreviousSelection(),{anchor:r,focus:l}=e,s=r.getNode(),i=l.getNode(),a=Re(s),c=Re(i),u=a?xe(a):null,d=c?xe(c):null,h=e.isBackward(),f=a&&c&&u&&d&&u.is(d),m=d&&(!u||u.isParentOf(d)),p=u&&(!d||d.isParentOf(u));if(m){const n=e.clone(),[o]=k(d,c,c),r=o[0][0].cell,l=o[o.length-1].at(-1).cell;n.focus.set(h?r.getKey():l.getKey(),h?0:l.getChildrenSize(),"element"),t.$setSelection(n)}else if(p){const n=e.clone(),[o]=k(u,a,a),r=o[0][0].cell,l=o[o.length-1].at(-1).cell;n.anchor.set(h?l.getKey():r.getKey(),h?l.getChildrenSize():0,"element"),t.$setSelection(n)}else if(f){const r=n.observers.get(u.getKey());r||g(335,u.getKey());const[l]=r;if(a.is(c)||(l.$setAnchorCellForSelection(Fe(l,a)),l.$setFocusCellForSelection(Fe(l,c),!0)),"touch"===l.pointerType&&l.isSelecting&&e.isCollapsed()&&t.$isRangeSelection(o)&&o.isCollapsed()){const e=Re(o.anchor.getNode());e&&!e.is(c)&&(l.$setAnchorCellForSelection(Fe(l,e)),l.$setFocusCellForSelection(Fe(l,c),!0),l.pointerType=null)}}}(r,n);const a=Array.from(n.observers.entries()).map(([e,[n]])=>({tableNode:t.$getNodeByKeyOrThrow(e),tableObserver:n}));for(const{tableNode:e,tableObserver:t}of a)ue(o,e,t);return!1}function ue(e,n,o){const r=t.$getSelection(),l=t.$getPreviousSelection();r&&!r.is(l)&&(X(r)||X(l))&&o.tableSelection&&!o.tableSelection.is(l)&&(X(r)&&r.tableKey===o.tableNodeKey?o.$updateTableTableSelection(r):!X(r)&&X(l)&&l.tableKey===o.tableNodeKey&&o.$updateTableTableSelection(null)),o.hasHijackedSelectionStyles&&!n.isSelected()?function(e,t){t.$enableHighlightStyle(),pe(t.table,t=>{const n=t.elem;t.highlighted=!1,$e(e,t),n.getAttribute("style")||n.removeAttribute("style")})}(e,o):!o.hasHijackedSelectionStyles&&n.isSelected()&&function(e,t){t.$disableHighlightStyle(),pe(t.table,t=>{t.highlighted=!0,Te(e,t)})}(e,o)}function de(e){return e[Z]||null}function he(e){let t=e;for(;null!=t;){const e=t.nodeName;if("TD"===e||"TH"===e){const e=t._cell;return void 0===e?null:e}t=t.parentNode}return null}function ge(e,t){if(!e.contains(t))return null;let n=null;for(let o=t;null!=o;o=o.parentNode){if(o===e)return n;const t=o.nodeName;"TD"!==t&&"TH"!==t||(n=o._cell||null)}return null}function fe(e,t){const n=[],o={columns:0,domRows:n,rows:0};let r=te(e,t).querySelector("tr"),l=0,s=0;for(n.length=0;null!=r;){const e=r.nodeName;if("TD"===e||"TH"===e){const e={elem:r,hasBackgroundColor:""!==r.style.backgroundColor,highlighted:!1,x:l,y:s};r._cell=e;let t=n[s];void 0===t&&(t=n[s]=[]),t[l]=e}else{const e=r.firstChild;if(null!=e){r=e;continue}}const t=r.nextSibling;if(null!=t){l++,r=t;continue}const o=r.parentNode;if(null!=o){const e=o.nextSibling;if(null==e)break;s++,l=0,r=e}}return o.columns=l+1,o.rows=s+1,o}function me(e,t,n){const o=new Set(n?n.getNodes():[]);pe(t,(t,n)=>{const r=t.elem;o.has(n)?(t.highlighted=!0,Te(e,t)):(t.highlighted=!1,$e(e,t),r.getAttribute("style")||r.removeAttribute("style"))})}function pe(e,n){const{domRows:o}=e;for(let e=0;e<o.length;e++){const r=o[e];if(r)for(let o=0;o<r.length;o++){const l=r[o];if(!l)continue;const s=t.$getNearestNodeFromDOMNode(l.elem);null!==s&&n(l,s,{x:o,y:e})}}}const Ce=(e,t,n,o,r)=>{const l="forward"===r;switch(r){case"backward":case"forward":return n!==(l?e.table.columns-1:0)?ye(t.getCellNodeFromCordsOrThrow(n+(l?1:-1),o,e.table),l):o!==(l?e.table.rows-1:0)?ye(t.getCellNodeFromCordsOrThrow(l?0:e.table.columns-1,o+(l?1:-1),e.table),l):l?t.selectNext():t.selectPrevious(),!0;case"up":return 0!==o?ye(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case"down":return o!==e.table.rows-1?ye(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function _e(e,t){let n,o;if(t.startColumn===e.minColumn)n="minColumn";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n="maxColumn"}if(t.startRow===e.minRow)o="minRow";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;o="maxRow"}return[n,o]}function Se([e,t]){return["minColumn"===e?"maxColumn":"minColumn","minRow"===t?"maxRow":"minRow"]}function Ne(e,t,[n,o]){const r=t[o],l=e[r];void 0===l&&g(250,o,String(r));const s=t[n],i=l[s];return void 0===i&&g(250,n,String(s)),i}function be(e,t,n,o,r){const l=W(t,n,o),s=function(e,t){const{minColumn:n,maxColumn:o,minRow:r,maxRow:l}=t;let s=1,i=1,a=1,c=1;const u=e[r],d=e[l];for(let e=n;e<=o;e++)s=Math.max(s,u[e].cell.__rowSpan),c=Math.max(c,d[e].cell.__rowSpan);for(let t=r;t<=l;t++)i=Math.max(i,e[t][n].cell.__colSpan),a=Math.max(a,e[t][o].cell.__colSpan);return{bottomSpan:c,leftSpan:i,rightSpan:a,topSpan:s}}(t,l),{topSpan:i,leftSpan:a,bottomSpan:c,rightSpan:u}=s,d=function(e,t){const n=_e(e,t);return null===n&&g(249,t.cell.getKey()),n}(l,n),[h,f]=Se(d);let m=l[h],p=l[f];"forward"===r?m+="maxColumn"===h?1:a:"backward"===r?m-="minColumn"===h?1:u:"down"===r?p+="maxRow"===f?1:i:"up"===r&&(p-="minRow"===f?1:c);const C=t[p];if(void 0===C)return!1;const _=C[m];if(void 0===_)return!1;const[S,N]=function(e,t,n){const o=W(e,t,n),r=_e(o,t);if(r)return[Ne(e,o,r),Ne(e,o,Se(r))];const l=_e(o,n);if(l)return[Ne(e,o,Se(l)),Ne(e,o,l)];const s=["minColumn","minRow"];return[Ne(e,o,s),Ne(e,o,Se(s))]}(t,n,_),b=Fe(e,S.cell),w=Fe(e,N.cell);return e.$setAnchorCellForSelection(b),e.$setFocusCellForSelection(w,!0),!0}function we(e,n){if(t.$isRangeSelection(e)||X(e)){const t=n.isParentOf(e.anchor.getNode()),o=n.isParentOf(e.focus.getNode());return t&&o}return!1}function ye(e,t){t?e.selectStart():e.selectEnd()}function Te(n,o){const r=o.elem,l=n._config.theme;d(t.$getNearestNodeFromDOMNode(r))||g(131),e.addClassNamesToElement(r,l.tableCellSelected)}function $e(n,o){const r=o.elem;d(t.$getNearestNodeFromDOMNode(r))||g(131);const l=n._config.theme;e.removeClassNamesFromElement(r,l.tableCellSelected)}function Re(t){const n=e.$findMatchingParent(t,d);return d(n)?n:null}function xe(t){const n=e.$findMatchingParent(t,Ye);return Ye(n)?n:null}function Ee(n,o,r,l,s,i,a){const c=t.$caretFromPoint(r.focus,s?"previous":"next");if(t.$isExtendableTextPointCaret(c))return!1;let u=c;for(const e of t.$extendCaretToRange(c).iterNodeCarets("shadowRoot")){if(!t.$isSiblingCaret(e)||!t.$isElementNode(e.origin))return!1;u=e}const h=u.getParentAtCaret();if(!d(h))return!1;const g=h,f=function(e){for(const n of t.$extendCaretToRange(e).iterNodeCarets("root")){const{origin:o}=n;if(d(o)){if(t.$isChildCaret(n))return t.$getChildCaret(o,e.direction)}else if(!C(o))break}return null}(t.$getSiblingCaret(g,u.direction)),m=e.$findMatchingParent(g,Ye);if(!m||!m.is(i))return!1;const p=n.getElementByKey(g.getKey()),_=he(p);if(!p||!_)return!1;const S=We(n,m);if(a.table=S,f)if("extend"===l){const e=he(n.getElementByKey(f.origin.getKey()));if(!e)return!1;a.$setAnchorCellForSelection(_),a.$setFocusCellForSelection(e,!0)}else{const e=t.$normalizeCaret(f);t.$setPointFromCaret(r.anchor,e),t.$setPointFromCaret(r.focus,e)}else if("extend"===l)a.$setAnchorCellForSelection(_),a.$setFocusCellForSelection(_,!0);else{const e=function(e){const n=t.$getAdjacentChildCaret(e);return t.$isChildCaret(n)?t.$normalizeCaret(n):e}(t.$getSiblingCaret(m,c.direction));t.$setPointFromCaret(r.anchor,e),t.$setPointFromCaret(r.focus,e)}return Oe(o),!0}function Me(n,o,r,l,s,i){if(("up"===r||"down"===r)&&function(e){const t=e.getRootElement();if(!t)return!1;return t.hasAttribute("aria-controls")&&"typeahead-menu"===t.getAttribute("aria-controls")}(n))return!1;const a=t.$getSelection();if(!we(a,l)){if(t.$isRangeSelection(a)){if("backward"===r){if(a.focus.offset>0)return!1;const e=function(e){for(let n=e,o=e;null!==o;n=o,o=o.getParent())if(t.$isElementNode(o)){if(o!==n&&o.getFirstChild()!==n)return null;if(!o.isInline())return o}return null}(a.focus.getNode());if(!e)return!1;const n=e.getPreviousSibling();return!!Ye(n)&&(Oe(o),o.shiftKey?a.focus.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent(),"element"):n.selectEnd(),!0)}if(o.shiftKey&&("up"===r||"down"===r)){const n=a.focus.getNode();if(!a.isCollapsed()&&("up"===r&&!a.isBackward()||"down"===r&&a.isBackward())){let s=e.$findMatchingParent(n,e=>Ye(e));if(d(s)&&(s=e.$findMatchingParent(s,Ye)),s!==l)return!1;if(!s)return!1;const i="down"===r?s.getNextSibling():s.getPreviousSibling();if(!i)return!1;let c=0;"up"===r&&t.$isElementNode(i)&&(c=i.getChildrenSize());let u=i;if("up"===r&&t.$isElementNode(i)){const e=i.getLastChild();u=e||i,c=t.$isTextNode(u)?u.getTextContentSize():0}const h=a.clone();return h.focus.set(u.getKey(),c,t.$isTextNode(u)?"text":"element"),t.$setSelection(h),Oe(o),!0}if(t.$isRootOrShadowRoot(n)){const e="up"===r?a.getNodes()[a.getNodes().length-1]:a.getNodes()[0];if(e){if(null!==oe(l,e)){const e=l.getFirstDescendant(),t=l.getLastDescendant();if(!e||!t)return!1;const[n]=H(e),[o]=H(t),r=l.getCordsFromCellNode(n,s.table),i=l.getCordsFromCellNode(o,s.table),a=l.getDOMCellFromCordsOrThrow(r.x,r.y,s.table),c=l.getDOMCellFromCordsOrThrow(i.x,i.y,s.table);return s.$setAnchorCellForSelection(a),s.$setFocusCellForSelection(c,!0),!0}}return!1}{let l=e.$findMatchingParent(n,e=>t.$isElementNode(e)&&!e.isInline());if(d(l)&&(l=e.$findMatchingParent(l,Ye)),!l)return!1;const i="down"===r?l.getNextSibling():l.getPreviousSibling();if(Ye(i)&&s.tableNodeKey===i.getKey()){const e=i.getFirstDescendant(),n=i.getLastDescendant();if(!e||!n)return!1;const[l]=H(e),[s]=H(n),c=a.clone();return c.focus.set(("up"===r?l:s).getKey(),"up"===r?0:s.getChildrenSize(),"element"),Oe(o),t.$setSelection(c),!0}}}}return"down"===r&&ke(n)&&i.setShouldCheckSelectionForTable(l.getKey()),!1}if(t.$isRangeSelection(a)){if("backward"===r||"forward"===r){return Ee(n,o,a,o.shiftKey?"extend":"move","backward"===r,l,s)}if(a.isCollapsed()){const{anchor:c,focus:u}=a,h=e.$findMatchingParent(c.getNode(),d),g=e.$findMatchingParent(u.getNode(),d);if(!d(h)||!h.is(g))return!1;const f=xe(h);if(f!==l&&null!=f){const e=te(f,n.getElementByKey(f.getKey()));if(null!=e)return s.table=fe(f,e),Me(n,o,r,f,s,i)}const m=n.getElementByKey(h.__key),p=n.getElementByKey(c.key);if(null==p||null==m)return!1;let C;if("element"===c.type)C=p.getBoundingClientRect();else{const e=t.getDOMSelection(ne(n));if(null===e||0===e.rangeCount)return!1;C=e.getRangeAt(0).getBoundingClientRect()}const _="up"===r?h.getFirstChild():h.getLastChild();if(null==_)return!1;const S=n.getElementByKey(_.__key);if(null==S)return!1;const N=S.getBoundingClientRect();if("up"===r?N.top>C.top-C.height:C.bottom+C.height>N.bottom){Oe(o);const e=l.getCordsFromCellNode(h,s.table);if(!o.shiftKey)return Ce(s,l,e.x,e.y,r);{const t=l.getDOMCellFromCordsOrThrow(e.x,e.y,s.table);s.$setAnchorCellForSelection(t),s.$setFocusCellForSelection(t,!0)}return!0}}}else if(X(a)){const{anchor:t,focus:i,tableKey:c}=a;if(c!==l.getKey())return!1;const u=e.$findMatchingParent(t.getNode(),d),h=e.$findMatchingParent(i.getNode(),d),[f]=a.getNodes();Ye(f)||g(251);const m=te(f,n.getElementByKey(f.getKey()));if(!d(u)||!d(h)||!Ye(f)||null==m)return!1;s.$updateTableTableSelection(a);const p=fe(f,m),C=l.getCordsFromCellNode(u,p),_=l.getDOMCellFromCordsOrThrow(C.x,C.y,p);if(s.$setAnchorCellForSelection(_),Oe(o),o.shiftKey){const[e,t,n]=k(l,u,h);return be(s,e,t,n,r)}return h.selectEnd(),!0}return!1}function Oe(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function Ae(e,n,o){const r=t.$createParagraphNode();"first"===e?n.insertBefore(r):n.insertAfter(r),r.append(...o||[]),r.selectEnd()}function ve(n,o,r){const l=r.getParent();if(!l)return;const s=t.getDOMSelection(ne(n));if(!s)return;const i=s.anchorNode,a=n.getElementByKey(l.getKey()),c=te(r,n.getElementByKey(r.getKey()));if(!i||!a||!c||!a.contains(i)||c.contains(i))return;const u=e.$findMatchingParent(o.anchor.getNode(),e=>d(e));if(!u)return;const h=e.$findMatchingParent(u,e=>Ye(e));if(!Ye(h)||!h.is(r))return;const[g,f]=k(r,u,u),m=g[0][0],p=g[g.length-1][g[0].length-1],{startRow:C,startColumn:_}=f,S=C===m.startRow&&_===m.startColumn,N=C===p.startRow&&_===p.startColumn;return S?"first":N?"last":void 0}function Fe(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function Pe(e,n,o){return oe(e,t.$getNearestNodeFromDOMNode(n,o))}function Ke(e,t,n){const o=e.querySelector("colgroup");if(!o)return;const r=[];for(let e=0;e<t;e++){const t=document.createElement("col"),o=n&&n[e];o&&(t.style.width=`${o}px`),r.push(t)}o.replaceChildren(...r)}function De(t,n,o){if(!n.theme.tableAlignment)return;const r=[],l=[];for(const e of["center","right"]){const t=n.theme.tableAlignment[e];t&&(e===o?l:r).push(t)}e.removeClassNamesFromElement(t,...r),e.addClassNamesToElement(t,...l)}const Ie=new WeakSet;function ke(e=t.$getEditor()){return Ie.has(e)}function Le(e,t){t?Ie.add(e):Ie.delete(e)}class He extends t.ElementNode{__rowStriping;__frozenColumnCount;__frozenRowCount;__colWidths;static getType(){return"table"}getColWidths(){return this.getLatest().__colWidths}setColWidths(e){const t=this.getWritable();return t.__colWidths=e,t}static clone(e){return new He(e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__colWidths=e.__colWidths,this.__rowStriping=e.__rowStriping,this.__frozenColumnCount=e.__frozenColumnCount,this.__frozenRowCount=e.__frozenRowCount}static importDOM(){return{table:e=>({conversion:Be,priority:1})}}static importJSON(e){return ze().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setRowStriping(e.rowStriping||!1).setFrozenColumns(e.frozenColumnCount||0).setFrozenRows(e.frozenRowCount||0).setColWidths(e.colWidths)}constructor(e){super(e),this.__rowStriping=!1,this.__frozenColumnCount=0,this.__frozenRowCount=0,this.__colWidths=void 0}exportJSON(){return{...super.exportJSON(),colWidths:this.getColWidths(),frozenColumnCount:this.__frozenColumnCount?this.__frozenColumnCount:void 0,frozenRowCount:this.__frozenRowCount?this.__frozenRowCount:void 0,rowStriping:this.__rowStriping?this.__rowStriping:void 0}}extractWithChild(e,t,n){return"html"===n}getDOMSlot(e){const t=ee(e)?e:e.querySelector("table");return ee(t)||g(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector("colgroup"))}createDOM(n,o){const r=document.createElement("table");this.__style&&t.setDOMStyleFromCSS(r.style,this.__style);const l=document.createElement("colgroup");if(r.appendChild(l),t.setDOMUnmanaged(l),e.addClassNamesToElement(r,n.theme.table),this.updateTableElement(null,r,n),ke(o)){const t=document.createElement("div"),o=n.theme.tableScrollableWrapper;return o?e.addClassNamesToElement(t,o):t.style.overflowX="auto",t.appendChild(r),this.updateTableWrapper(null,t,r,n),t}return r}updateTableWrapper(t,n,o,r){this.__frozenColumnCount!==(t?t.__frozenColumnCount:0)&&function(t,n,o,r){r>0?(e.addClassNamesToElement(t,o.theme.tableFrozenColumn),n.setAttribute("data-lexical-frozen-column","true")):(e.removeClassNamesFromElement(t,o.theme.tableFrozenColumn),n.removeAttribute("data-lexical-frozen-column"))}(n,o,r,this.__frozenColumnCount),this.__frozenRowCount!==(t?t.__frozenRowCount:0)&&function(t,n,o,r){r>0?(e.addClassNamesToElement(t,o.theme.tableFrozenRow),n.setAttribute("data-lexical-frozen-row","true")):(e.removeClassNamesFromElement(t,o.theme.tableFrozenRow),n.removeAttribute("data-lexical-frozen-row"))}(n,o,r,this.__frozenRowCount)}updateTableElement(n,o,r){this.__style!==(n?n.__style:"")&&t.setDOMStyleFromCSS(o.style,this.__style,n?n.__style:""),this.__rowStriping!==(!!n&&n.__rowStriping)&&function(t,n,o){o?(e.addClassNamesToElement(t,n.theme.tableRowStriping),t.setAttribute("data-lexical-row-striping","true")):(e.removeClassNamesFromElement(t,n.theme.tableRowStriping),t.removeAttribute("data-lexical-row-striping"))}(o,r,this.__rowStriping);const l=n?n.getColumnCount():0,s=n?n.__colWidths:void 0;this.getColumnCount()===l&&this.getColWidths()===s||Ke(o,this.getColumnCount(),this.getColWidths()),De(o,r,this.getFormatType())}updateDOM(t,n,o){const r=te(this,n);return n===r===ke()||(l=n,e.isHTMLElement(l)&&"DIV"===l.nodeName&&this.updateTableWrapper(t,n,r,o),this.updateTableElement(t,r,o),!1);var l}scaleDOMColWidths(e,t){const n=this.getColWidths();if(!n)return;Ke(te(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(t){const n=super.exportDOM(t),{element:o}=n;return{after:o=>{if(n.after&&(o=n.after(o)),!ee(o)&&e.isHTMLElement(o)&&(o=o.querySelector("table")),!ee(o))return null;De(o,t._config,this.getFormatType());const[r]=L(this,null,null),l=new Map;for(const e of r)for(const t of e){const e=t.cell.getKey();l.has(e)||l.set(e,{colSpan:t.cell.getColSpan(),startColumn:t.startColumn})}const s=new Set;for(const e of o.querySelectorAll(":scope > tr > [data-temporary-table-cell-lexical-key]")){const t=e.getAttribute("data-temporary-table-cell-lexical-key");if(t){const n=l.get(t);if(e.removeAttribute("data-temporary-table-cell-lexical-key"),n){l.delete(t);for(let e=0;e<n.colSpan;e++)s.add(e+n.startColumn)}}}const i=o.querySelector(":scope > colgroup");if(i){const e=Array.from(o.querySelectorAll(":scope > colgroup > col")).filter((e,t)=>s.has(t));i.replaceChildren(...e)}const a=o.querySelectorAll(":scope > tr");if(a.length>0){const e=document.createElement("tbody");for(const t of a)e.appendChild(t);o.append(e)}return o},element:!ee(o)&&e.isHTMLElement(o)?o.querySelector("table"):o}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(e,t){const{rows:n,domRows:o}=t;for(let t=0;t<n;t++){const n=o[t];if(null!=n)for(let o=0;o<n.length;o++){const r=n[o];if(null==r)continue;const{elem:l}=r,s=Pe(this,l);if(null!==s&&e.is(s))return{x:o,y:t}}}throw new Error("Cell not found in table.")}getDOMCellFromCords(e,t,n){const{domRows:o}=n,r=o[t];if(null==r)return null;const l=r[e<r.length?e:r.length-1];return null==l?null:l}getDOMCellFromCordsOrThrow(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(!o)throw new Error("Cell not found at cords.");return o}getCellNodeFromCords(e,n,o){const r=this.getDOMCellFromCords(e,n,o);if(null==r)return null;const l=t.$getNearestNodeFromDOMNode(r.elem);return d(l)?l:null}getCellNodeFromCordsOrThrow(e,t,n){const o=this.getCellNodeFromCords(e,t,n);if(!o)throw new Error("Node at cords not TableCellNode.");return o}getRowStriping(){return Boolean(this.getLatest().__rowStriping)}setRowStriping(e){const t=this.getWritable();return t.__rowStriping=e,t}setFrozenColumns(e){const t=this.getWritable();return t.__frozenColumnCount=e,t}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(e){const t=this.getWritable();return t.__frozenRowCount=e,t}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const e=this.getFirstChild();if(!e)return 0;let t=0;return e.getChildren().forEach(e=>{d(e)&&(t+=e.getColSpan())}),t}}function We(e,t){const n=e.getElementByKey(t.getKey());return null===n&&g(230),fe(t,n)}function Be(t){const n=ze();t.hasAttribute("data-lexical-row-striping")&&n.setRowStriping(!0),t.hasAttribute("data-lexical-frozen-column")&&n.setFrozenColumns(1),t.hasAttribute("data-lexical-frozen-row")&&n.setFrozenRows(1);const o=t.querySelector(":scope > colgroup");if(o){let e=[];for(const t of o.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!l.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&n.setColWidths(e)}return{after:t=>e.$descendantsMatching(t,C),node:n}}function ze(){return t.$applyNodeReplacement(new He)}function Ye(e){return e instanceof He}function Ue(e){C(e.getParent())?e.isEmpty()&&e.append(t.$createParagraphNode()):e.remove()}function Xe(t){Ye(t.getParent())?e.$unwrapAndFilterDescendants(t,d):t.remove()}function Ge(n){e.$unwrapAndFilterDescendants(n,C);const[o]=L(n,null,null),r=o.reduce((e,t)=>Math.max(e,t.length),0),l=n.getChildren();for(let e=0;e<o.length;++e){const n=l[e];if(!n)continue;C(n)||g(254,n.constructor.name,n.getType());const s=o[e].reduce((e,t)=>t?1+e:e,0);if(s!==r)for(let e=s;e<r;++e){const e=u();e.append(t.$createParagraphNode()),n.append(e)}}const s=n.getColWidths(),i=n.getColumnCount();if(s&&s.length!==i){let e;if(i<s.length)e=s.slice(0,i);else if(s.length>0){const t=s[s.length-1];e=[...s,...Array(i-s.length).fill(t)]}n.setColWidths(e)}}function qe(n){if(n.detail<3||!t.isDOMNode(n.target))return!1;const o=t.$getNearestNodeFromDOMNode(n.target);if(null===o)return!1;const r=e.$findMatchingParent(o,e=>t.$isElementNode(e)&&!e.isInline());if(null===r)return!1;return!!d(r.getParent())&&(r.select(0),!0)}function Je(){const e=t.$getSelection();if(!t.$isRangeSelection(e))return!1;const n=xe(e.anchor.getNode());if(null===n)return!1;const o=t.$getRoot();if(!o.is(n.getParent())||1!==o.getChildrenSize())return!1;const[r]=L(n,null,null);if(0===r.length||0===r[0].length)return!1;const l=r[0][0];if(!l||!l.cell)return!1;const s=r[r.length-1],i=s[s.length-1];if(!i||!i.cell)return!1;const a=q(n,l.cell,i.cell);return t.$setSelection(a),!0}function je(t){return t.registerNodeTransform(i,t=>{if(t.getColSpan()>1||t.getRowSpan()>1){const[,,n]=H(t),[o]=k(n,t,t),r=o.length,l=o[0].length;let s=n.getFirstChild();C(s)||g(175);const i=[];for(let t=0;t<r;t++){0!==t&&(s=s.getNextSibling(),C(s)||g(175));let n=null;for(let r=0;r<l;r++){const l=o[t][r],a=l.cell;if(l.startRow===t&&l.startColumn===r)n=a,i.push(a);else if(a.getColSpan()>1||a.getRowSpan()>1){d(a)||g(176);const t=u(a.__headerState);null!==n?n.insertAfter(t):e.$insertFirst(s,t)}}}for(const e of i)e.setColSpan(1),e.setRowSpan(1)}})}function Ve(n,o=!0){const r=new V,l=(e,t,l)=>{const s=te(e,l),i=ae(e,s,n,o,r);r.observers.set(t,[i,s])};return e.mergeRegister(ie(n,r),n.registerCommand(t.SELECTION_CHANGE_COMMAND,()=>ce(r,n),t.COMMAND_PRIORITY_HIGH),n.registerMutationListener(He,e=>{n.getEditorState().read(()=>{for(const[t,n]of e){const e=r.observers.get(t);if("created"===n||"updated"===n){const{tableNode:n,tableElement:o}=j(t);void 0===e?l(n,t,o):o!==e[1]&&(e[0].removeListeners(),r.observers.delete(t),l(n,t,o))}else"destroyed"===n&&void 0!==e&&(e[0].removeListeners(),r.observers.delete(t))}},{editor:n})},{skipInitialization:!1}),()=>{for(const[,[e]]of r.observers)e.removeListeners()})}function Qe(o,r){o.hasNodes([He])||g(255);const{hasNestedTables:l=n.signal(!1)}=r??{};return e.mergeRegister(o.registerCommand(h,n=>function({rows:n,columns:o,includeHeaders:r},l){const s=t.$getSelection()||t.$getPreviousSelection();if(!s||!t.$isRangeSelection(s))return!1;if(!l&&xe(s.anchor.getNode()))return!1;const i=_(Number(n),Number(o),r);e.$insertNodeToNearestRoot(i);const a=i.getFirstDescendant();return t.$isTextNode(a)&&a.select(),!0}(n,l.peek()),t.COMMAND_PRIORITY_EDITOR),o.registerCommand(t.SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,(n,r)=>o===r&&function(n,o){const{nodes:r,selection:l}=n;if(!r.some(t=>Ye(t)||e.$dfs(t).some(e=>Ye(e.node))))return!1;const s=X(l),i=t.$isRangeSelection(l);if(!(i&&null!==e.$findMatchingParent(l.anchor.getNode(),e=>d(e))&&null!==e.$findMatchingParent(l.focus.getNode(),e=>d(e))||s))return!1;if(1===r.length&&Ye(r[0]))return function(n,o){const r=o.getStartEndPoints(),l=X(o);if(null===r)return!1;const[s,i]=r,[a,c,u]=H(s),h=e.$findMatchingParent(i.getNode(),e=>d(e));if(!(d(a)&&d(h)&&C(c)&&Ye(u)))return!1;const[g,f,m]=k(u,a,h),[p]=L(n,null,null),_=g.length,S=_>0?g[0].length:0;let N=f.startRow,b=f.startColumn,w=p.length,y=w>0?p[0].length:0;if(l){const e=W(g,f,m),t=e.maxRow-e.minRow+1,n=e.maxColumn-e.minColumn+1;N=e.minRow,b=e.minColumn,w=Math.min(w,t),y=Math.min(y,n)}let T=!1;const R=Math.min(_,N+w)-1,x=Math.min(S,b+y)-1,M=new Set;for(let e=N;e<=R;e++)for(let t=b;t<=x;t++){const n=g[e][t];M.has(n.cell.getKey())||(1===n.cell.__rowSpan&&1===n.cell.__colSpan||(I(n.cell),M.add(n.cell.getKey()),T=!0))}let[O]=L(u.getWritable(),null,null);const A=w-_+N;for(let e=0;e<A;e++){$(O[_-1][0].cell)}const v=y-S+b;for(let e=0;e<v;e++){E(O[0][S-1].cell,!0,!1)}[O]=L(u.getWritable(),null,null);for(let e=N;e<N+w;e++)for(let n=b;n<b+y;n++){const o=e-N,r=n-b,l=p[o][r];if(l.startRow!==o||l.startColumn!==r)continue;const s=l.cell;if(1!==s.__rowSpan||1!==s.__colSpan){const t=[],o=Math.min(e+s.__rowSpan,N+w)-1,r=Math.min(n+s.__colSpan,b+y)-1;for(let l=e;l<=o;l++)for(let e=n;e<=r;e++){const n=O[l][e];t.push(n.cell)}K(t),T=!0}const{cell:i}=O[e][n],a=s.getBackgroundColor();null!=a&&i.setBackgroundColor(a);const c=i.getChildren();s.getChildren().forEach(e=>{if(t.$isTextNode(e)){t.$createParagraphNode().append(e),i.append(e)}else i.append(e)}),c.forEach(e=>e.remove())}if(l&&T){const[e]=L(u.getWritable(),null,null);e[f.startRow][f.startColumn].cell.selectEnd()}return!0}(r[0],l);if(i&&o.peek()&&!function(e){if(X(e)&&!e.focus.getNode().is(e.anchor.getNode()))return!0;if(t.$isRangeSelection(e)&&d(e.anchor.getNode())&&!e.anchor.getNode().is(e.focus.getNode()))return!0;return!1}(l))return!1;return!0}(n,l),t.COMMAND_PRIORITY_EDITOR),o.registerCommand(t.SELECT_ALL_COMMAND,Je,t.COMMAND_PRIORITY_LOW),o.registerCommand(t.CLICK_COMMAND,qe,t.COMMAND_PRIORITY_EDITOR),o.registerNodeTransform(He,Ge),o.registerNodeTransform(f,Xe),o.registerNodeTransform(i,Ue))}const Ze=t.defineExtension({build:(e,t,o)=>n.namedSignals(t),config:t.safeCast({hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasTabHandler:!0}),name:"@lexical/table/Table",nodes:()=>[He,f,i],register(o,r,l){const s=l.getOutput();return e.mergeRegister(n.effect(()=>{const e=s.hasHorizontalScroll.value;ke(o)!==e&&(Le(o,e),o.update(t.$fullReconcile))}),Qe(o,s),n.effect(()=>Ve(o,s.hasTabHandler.value)),n.effect(()=>s.hasCellMerge.value?void 0:je(o)),n.effect(()=>s.hasCellBackgroundColor.value?void 0:o.registerNodeTransform(i,e=>{null!==e.getBackgroundColor()&&e.setBackgroundColor(null)})))}});function et(e){const n=[];let o=null;const r=()=>{if(null!==o){const e=o.getFirstChild();t.$isLineBreakNode(e)&&1===o.getChildrenSize()&&e.remove()}};for(const l of e)t.$isInlineElementOrDecoratorNode(l)||t.$isTextNode(l)||t.$isLineBreakNode(l)?null!==o?o.append(l):(o=t.$createParagraphNode().append(l),n.push(o)):(r(),n.push(l),o=null);return r(),0===n.length&&n.push(t.$createParagraphNode()),n}const tt={$accepts:C,$packageRun:e=>e.every(d)?[p().splice(0,0,e)]:[],name:"TableSchema"},nt={$accepts:d,name:"TableRowSchema"},ot=[r.defineImportRule({$import:(t,n)=>{const o=ze();n.hasAttribute("data-lexical-row-striping")&&o.setRowStriping(!0),n.hasAttribute("data-lexical-frozen-column")&&o.setFrozenColumns(1),n.hasAttribute("data-lexical-frozen-row")&&o.setFrozenRows(1);const r=n.querySelector(":scope > colgroup");if(r){let e=[];for(const t of r.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!l.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&o.setColWidths(e)}return[o.splice(0,0,e.$descendantsMatching(t.$importChildren(n),C))]},match:r.sel.tag("table"),name:"@lexical/table/table"}),r.defineImportRule({$import:(t,n)=>[p(l.test(n.style.height)?parseFloat(n.style.height):void 0).splice(0,0,e.$descendantsMatching(t.$importChildren(n),d))],match:r.sel.tag("tr"),name:"@lexical/table/tr"}),r.defineImportRule({$import:(e,n)=>{const o="TH"===n.nodeName,i=l.test(n.style.width)?parseFloat(n.style.width):void 0;let a=s.NO_STATUS;if(o){const e=n.getAttribute("scope");if("col"===e)a=s.COLUMN;else if("row"===e)a=s.ROW;else{const e=n.parentElement,o=t.isHTMLTableRowElement(e)&&(e.parentElement&&"THEAD"===e.parentElement.nodeName||0===e.rowIndex),r=0===n.cellIndex;o&&(a|=s.ROW),r&&(a|=s.COLUMN),a===s.NO_STATUS&&(a=s.ROW)}}const c=u(a,n.colSpan,i);c.__rowSpan=n.rowSpan;const d=n.style.backgroundColor;""!==d&&(c.__backgroundColor=d);const h=n.style.verticalAlign;(function(e){return"middle"===e||"bottom"===e})(h)&&(c.__verticalAlign=h);const g=e.get(r.ImportTextFormat),f=g|function(e){let n=0;const o=e.fontWeight;"700"!==o&&"bold"!==o||(n|=t.IS_BOLD),"italic"===e.fontStyle&&(n|=t.IS_ITALIC);const r=(e.textDecoration||"").split(" ");return r.includes("underline")&&(n|=t.IS_UNDERLINE),r.includes("line-through")&&(n|=t.IS_STRIKETHROUGH),n}(n.style),m=e.get(r.ImportTextStyle),p=n.style.color,C=p?{...m,color:p}:m,_=[];return f!==g&&_.push(r.contextValue(r.ImportTextFormat,f)),C!==m&&_.push(r.contextValue(r.ImportTextStyle,C)),[c.splice(0,0,et(e.$importChildren(n,{context:_})))]},match:r.sel.tag("td","th"),name:"@lexical/table/cell"})],rt=t.defineExtension({dependencies:[r.CoreImportExtension,Ze,t.configExtension(r.DOMImportExtension,{rules:ot})],name:"@lexical/table/Import"});exports.$computeTableMap=k,exports.$computeTableMapSkipCellCheck=L,exports.$createTableCellNode=u,exports.$createTableNode=ze,exports.$createTableNodeWithDimensions=_,exports.$createTableRowNode=p,exports.$createTableSelection=G,exports.$createTableSelectionFrom=q,exports.$deleteTableColumn=function(e,t){const n=e.getChildren();for(let e=0;e<n.length;e++){const o=n[e];if(C(o)){const e=o.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");e[t].remove()}}return e},exports.$deleteTableColumnAtSelection=A,exports.$deleteTableColumn__EXPERIMENTAL=v,exports.$deleteTableRowAtSelection=M,exports.$deleteTableRow__EXPERIMENTAL=O,exports.$findCellNode=Re,exports.$findTableNode=xe,exports.$getElementForTableNode=We,exports.$getNodeTriplet=H,exports.$getTableAndElementByKey=j,exports.$getTableCellNodeFromLexicalNode=function(t){const n=e.$findMatchingParent(t,e=>d(e));return d(n)?n:null},exports.$getTableCellNodeRect=z,exports.$getTableColumnIndexFromTableCellNode=function(e){return S(e).getChildren().findIndex(t=>t.is(e))},exports.$getTableNodeFromLexicalNodeOrThrow=N,exports.$getTableRowIndexFromTableCellNode=function(e){const t=S(e);return N(t).getChildren().findIndex(e=>e.is(t))},exports.$getTableRowNodeFromTableCellNodeOrThrow=S,exports.$insertTableColumn=function(e,n,o=!0,r,l){const i=e.getChildren(),a=[];for(let e=0;e<i.length;e++){const o=i[e];if(C(o))for(let e=0;e<r;e++){const e=o.getChildren();if(n>=e.length||n<0)throw new Error("Table column target index out of range");const r=e[n];d(r)||g(12);const{left:i,right:c}=b(r,l);let h=s.NO_STATUS;(i&&i.hasHeaderState(s.ROW)||c&&c.hasHeaderState(s.ROW))&&(h|=s.ROW);const f=u(h);f.append(t.$createParagraphNode()),a.push({newTableCell:f,targetCell:r})}}return a.forEach(({newTableCell:e,targetCell:t})=>{o?t.insertAfter(e):t.insertBefore(e)}),e},exports.$insertTableColumnAtSelection=R,exports.$insertTableColumn__EXPERIMENTAL=x,exports.$insertTableRow=function(e,n,o=!0,r,l){const i=e.getChildren();if(n>=i.length||n<0)throw new Error("Table row target index out of range");const a=i[n];if(!C(a))throw new Error("Row before insertion index does not exist.");for(let e=0;e<r;e++){const e=a.getChildren(),n=e.length,r=p();for(let o=0;o<n;o++){const n=e[o];d(n)||g(12);const{above:i,below:a}=b(n,l);let c=s.NO_STATUS;const h=i&&i.getWidth()||a&&a.getWidth()||void 0;(i&&i.hasHeaderState(s.COLUMN)||a&&a.hasHeaderState(s.COLUMN))&&(c|=s.COLUMN);const f=u(c,1,h);f.append(t.$createParagraphNode()),r.append(f)}o?a.insertAfter(r):a.insertBefore(r)}return e},exports.$insertTableRowAtSelection=y,exports.$insertTableRow__EXPERIMENTAL=T,exports.$isScrollableTablesActive=ke,exports.$isSimpleTable=B,exports.$isTableCellNode=d,exports.$isTableNode=Ye,exports.$isTableRowNode=C,exports.$isTableSelection=X,exports.$mergeCells=K,exports.$moveTableColumn=function(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!B(e))return;e.getChildren().filter(C).forEach(e=>{const o=e.getChildren(),[r]=o.splice(t,1);o.splice(n,0,r),e.splice(0,o.length,o)});const r=e.getColWidths();if(r&&r.length===o){const o=[...r],[l]=o.splice(t,1);o.splice(n,0,l),e.setColWidths(o)}},exports.$removeTableRowAtIndex=function(e,t){const n=e.getChildren();if(t>=n.length||t<0)throw new Error("Expected table cell to be inside of table row.");return n[t].remove(),e},exports.$unmergeCell=function(){const n=t.$getSelection();t.$isRangeSelection(n)||X(n)||g(188);const o=n.anchor.getNode(),r=e.$findMatchingParent(o,d);return d(r)||g(148),I(r)},exports.INSERT_TABLE_COMMAND=h,exports.TableCellHeaderStates=s,exports.TableCellNode=i,exports.TableExtension=Ze,exports.TableImportExtension=rt,exports.TableImportRules=ot,exports.TableNode=He,exports.TableObserver=Q,exports.TableRowNode=f,exports.TableRowSchema=nt,exports.TableSchema=tt,exports.applyTableHandlers=ae,exports.getDOMCellFromTarget=he,exports.getTableElement=te,exports.getTableObserverFromTableElement=de,exports.registerTableCellUnmergeTransform=je,exports.registerTablePlugin=Qe,exports.registerTableSelectionObserver=Ve,exports.setScrollableTablesActive=Le;
+diff --git a/dist/LexicalTable.prod.mjs b/dist/LexicalTable.prod.mjs
+index ee050d11d7039aca7ad2782d61cdc4f7df91a4c1..995f960edd5c95de93079581da2d6d5863d82548 100644
+--- a/dist/LexicalTable.prod.mjs
++++ b/dist/LexicalTable.prod.mjs
+@@ -6,4 +6,4 @@
+ *
+ */
+
+-import{addClassNamesToElement as e,$descendantsMatching as t,$findMatchingParent as n,removeClassNamesFromElement as o,objectKlassEquals as r,isHTMLElement as l,$insertFirst as s,mergeRegister as i,$insertNodeToNearestRoot as c,$dfs as a,$unwrapAndFilterDescendants as u}from"@lexical/utils";import{ElementNode as h,isHTMLElement as d,$isInlineElementOrDecoratorNode as f,$isTextNode as g,$isLineBreakNode as m,$createParagraphNode as p,$applyNodeReplacement as C,createCommand as _,$createTextNode as S,$getSelection as b,$isRangeSelection as w,$isParagraphNode as y,$createPoint as N,$getNodeByKey as v,$isElementNode as x,$normalizeSelection__EXPERIMENTAL as T,isCurrentlyReadOnlyMode as F,TEXT_TYPE_TO_FORMAT as R,$getEditor as O,$setSelection as A,SELECTION_CHANGE_COMMAND as K,getDOMSelection as E,$createRangeSelection as k,$isRootNode as M,INSERT_PARAGRAPH_COMMAND as $,KEY_ARROW_DOWN_COMMAND as W,KEY_ARROW_UP_COMMAND as z,KEY_ARROW_LEFT_COMMAND as L,KEY_ARROW_RIGHT_COMMAND as H,COMMAND_PRIORITY_HIGH as B,KEY_ESCAPE_COMMAND as P,DELETE_WORD_COMMAND as D,DELETE_LINE_COMMAND as I,DELETE_CHARACTER_COMMAND as U,KEY_BACKSPACE_COMMAND as J,KEY_DELETE_COMMAND as X,CUT_COMMAND as Y,FORMAT_TEXT_COMMAND as q,FORMAT_ELEMENT_COMMAND as j,CONTROLLED_TEXT_INSERTION_COMMAND as V,KEY_TAB_COMMAND as G,FOCUS_COMMAND as Q,$getNearestNodeFromDOMNode as Z,isDOMNode as ee,$isRootOrShadowRoot as te,$getPreviousSelection as ne,$getNodeByKeyOrThrow as oe,$caretFromPoint as re,$isExtendableTextPointCaret as le,$extendCaretToRange as se,$isSiblingCaret as ie,$getSiblingCaret as ce,$setPointFromCaret as ae,$normalizeCaret as ue,$createRangeSelectionFromDom as he,$isChildCaret as de,$getChildCaret as fe,$getAdjacentChildCaret as ge,IS_FIREFOX as me,setDOMStyleFromCSS as pe,setDOMUnmanaged as Ce,COMMAND_PRIORITY_EDITOR as _e,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND as Se,SELECT_ALL_COMMAND as be,COMMAND_PRIORITY_LOW as we,CLICK_COMMAND as ye,$getRoot as Ne,defineExtension as ve,$fullReconcile as xe,safeCast as Te,configExtension as Fe,isHTMLTableRowElement as Re,IS_BOLD as Oe,IS_ITALIC as Ae,IS_UNDERLINE as Ke,IS_STRIKETHROUGH as Ee}from"lexical";import{signal as ke,effect as Me,namedSignals as $e}from"@lexical/extension";import{copyToClipboard as We,$getClipboardDataFromSelection as ze}from"@lexical/clipboard";import{CoreImportExtension as Le,DOMImportExtension as He,defineImportRule as Be,sel as Pe,ImportTextFormat as De,ImportTextStyle as Ie,contextValue as Ue}from"@lexical/html";const Je=/^(\d+(?:\.\d+)?)px$/,Xe={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1};class Ye extends h{__colSpan;__rowSpan;__headerState;__width;__backgroundColor;__verticalAlign;static getType(){return"tablecell"}static clone(e){return new Ye(e.__headerState,e.__colSpan,e.__width,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__rowSpan=e.__rowSpan,this.__backgroundColor=e.__backgroundColor,this.__verticalAlign=e.__verticalAlign,this.__colSpan=e.__colSpan,this.__headerState=e.__headerState,this.__width=e.__width}static importDOM(){return{td:e=>({conversion:je,priority:0}),th:e=>({conversion:je,priority:0})}}static importJSON(e){return Ve().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeaderStyles(e.headerState).setColSpan(e.colSpan||1).setRowSpan(e.rowSpan||1).setWidth(e.width||void 0).setBackgroundColor(e.backgroundColor||null).setVerticalAlign(e.verticalAlign||void 0)}constructor(e=Xe.NO_STATUS,t=1,n,o){super(o),this.__colSpan=t,this.__rowSpan=1,this.__headerState=e,this.__width=n,this.__backgroundColor=null,this.__verticalAlign=void 0}createDOM(t){const n=document.createElement(this.getTag());return this.__width&&(n.style.width=`${this.__width}px`),this.__colSpan>1&&(n.colSpan=this.__colSpan),this.__rowSpan>1&&(n.rowSpan=this.__rowSpan),null!==this.__backgroundColor&&(n.style.backgroundColor=this.__backgroundColor),qe(this.__verticalAlign)&&(n.style.verticalAlign=this.__verticalAlign),e(n,t.theme.tableCell,this.hasHeader()&&t.theme.tableCellHeader),n}exportDOM(e){const t=super.exportDOM(e);if(d(t.element)){const e=t.element;e.setAttribute("data-temporary-table-cell-lexical-key",this.getKey()),e.style.border="1px solid black",this.__colSpan>1&&(e.colSpan=this.__colSpan),this.__rowSpan>1&&(e.rowSpan=this.__rowSpan),e.style.width=`${this.getWidth()||75}px`,e.style.verticalAlign=this.getVerticalAlign()||"top",e.style.textAlign="start",null===this.__backgroundColor&&this.hasHeader()&&(e.style.backgroundColor="#f2f3f5")}return t}exportJSON(){return{...super.exportJSON(),...qe(this.__verticalAlign)&&{verticalAlign:this.__verticalAlign},backgroundColor:this.getBackgroundColor(),colSpan:this.__colSpan,headerState:this.__headerState,rowSpan:this.__rowSpan,width:this.getWidth()}}getColSpan(){return this.getLatest().__colSpan}setColSpan(e){const t=this.getWritable();return t.__colSpan=e,t}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(e){const t=this.getWritable();return t.__rowSpan=e,t}getTag(){return this.hasHeader()?"th":"td"}setHeaderStyles(e,t=Xe.BOTH){const n=this.getWritable();return n.__headerState=e&t|n.__headerState&~t,n}getHeaderStyles(){return this.getLatest().__headerState}setWidth(e){const t=this.getWritable();return t.__width=e,t}getWidth(){return this.getLatest().__width}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(e){const t=this.getWritable();return t.__backgroundColor=e,t}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(e){const t=this.getWritable();return t.__verticalAlign=e||void 0,t}toggleHeaderStyle(e){const t=this.getWritable();return(t.__headerState&e)===e?t.__headerState-=e:t.__headerState+=e,t}hasHeaderState(e){return(this.getHeaderStyles()&e)===e}hasHeader(){return this.getLatest().__headerState!==Xe.NO_STATUS}updateDOM(e){return e.__headerState!==this.__headerState||e.__width!==this.__width||e.__colSpan!==this.__colSpan||e.__rowSpan!==this.__rowSpan||e.__backgroundColor!==this.__backgroundColor||e.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}}function qe(e){return"middle"===e||"bottom"===e}function je(e){const t=e,n=e.nodeName.toLowerCase();let o;Je.test(t.style.width)&&(o=parseFloat(t.style.width));let r=Xe.NO_STATUS;if("th"===n){const e=t.getAttribute("scope");if("col"===e)r=Xe.COLUMN;else if("row"===e)r=Xe.ROW;else{const e=t.parentElement,n=d(e)&&"tr"===e.nodeName.toLowerCase()&&d(e.parentElement)&&("thead"===e.parentElement.nodeName.toLowerCase()||0===e.rowIndex),o=0===t.cellIndex;n&&(r|=Xe.ROW),o&&(r|=Xe.COLUMN),r===Xe.NO_STATUS&&(r=Xe.ROW)}}const l=Ve(r,t.colSpan,o);l.__rowSpan=t.rowSpan;const s=t.style.backgroundColor;""!==s&&(l.__backgroundColor=s);const i=t.style.verticalAlign;qe(i)&&(l.__verticalAlign=i);const c=t.style,a=(c&&c.textDecoration||"").split(" "),u="700"===c.fontWeight||"bold"===c.fontWeight,h=a.includes("line-through"),C="italic"===c.fontStyle,_=a.includes("underline"),S=c.color;return{after:e=>{const t=[];let n=null;const o=()=>{if(n){const e=n.getFirstChild();m(e)&&1===n.getChildrenSize()&&e.remove()}};for(const r of e)if(f(r)||g(r)||m(r)){if(g(r)&&(u&&r.toggleFormat("bold"),h&&r.toggleFormat("strikethrough"),C&&r.toggleFormat("italic"),_&&r.toggleFormat("underline"),S)){const e=r.getStyle();e.includes("color:")||r.setStyle(e+`color: ${S};`)}n?n.append(r):(n=p().append(r),t.push(n))}else t.push(r),o(),n=null;return o(),0===t.length&&t.push(p()),t},node:l}}function Ve(e=Xe.NO_STATUS,t=1,n){return C(new Ye(e,t,n))}function Ge(e){return e instanceof Ye}const Qe=_("INSERT_TABLE_COMMAND");function Ze(e,...t){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(const e of t)o.append("v",e);throw n.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}class et extends h{__height;static getType(){return"tablerow"}static clone(e){return new et(e.__height,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__height=e.__height}static importDOM(){return{tr:e=>({conversion:tt,priority:0})}}static importJSON(e){return nt().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeight(e.height)}constructor(e,t){super(t),this.__height=e}exportJSON(){const e=this.getHeight();return{...super.exportJSON(),...void 0===e?void 0:{height:e}}}createDOM(t){const n=document.createElement("tr");return this.__height&&(n.style.height=`${this.__height}px`),e(n,t.theme.tableRow),n}extractWithChild(e,t,n){return"html"===n}isShadowRoot(){return!0}setHeight(e){const t=this.getWritable();return t.__height=e,t}getHeight(){return this.getLatest().__height}updateDOM(e){return e.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}}function tt(e){const n=e;let o;return Je.test(n.style.height)&&(o=parseFloat(n.style.height)),{after:e=>t(e,Ge),node:nt(o)}}function nt(e){return C(new et(e))}function ot(e){return e instanceof et}function rt(e,t,n=!0){const o=Hn();for(let r=0;r<e;r++){const e=nt();for(let o=0;o<t;o++){let t=Xe.NO_STATUS;"object"==typeof n?(0===r&&n.rows&&(t|=Xe.ROW),0===o&&n.columns&&(t|=Xe.COLUMN)):n&&(0===r&&(t|=Xe.ROW),0===o&&(t|=Xe.COLUMN));const l=Ve(t),s=p();s.append(S()),l.append(s),e.append(l)}o.append(e)}return o}function lt(e){const t=n(e,e=>Ge(e));return Ge(t)?t:null}function st(e){const t=n(e,e=>ot(e));if(ot(t))return t;throw new Error("Expected table cell to be inside of table row.")}function it(e){const t=n(e,e=>Bn(e));if(Bn(t))return t;throw new Error("Expected table cell to be inside of table.")}function ct(e){const t=st(e);return it(t).getChildren().findIndex(e=>e.is(t))}function at(e){return st(e).getChildren().findIndex(t=>t.is(e))}function ut(e,t){const n=it(e),{x:o,y:r}=n.getCordsFromCellNode(e,t);return{above:n.getCellNodeFromCords(o,r-1,t),below:n.getCellNodeFromCords(o,r+1,t),left:n.getCellNodeFromCords(o-1,r,t),right:n.getCellNodeFromCords(o+1,r,t)}}function ht(e,t){const n=e.getChildren();if(t>=n.length||t<0)throw new Error("Expected table cell to be inside of table row.");return n[t].remove(),e}function dt(e,t,n=!0,o,r){const l=e.getChildren();if(t>=l.length||t<0)throw new Error("Table row target index out of range");const s=l[t];if(!ot(s))throw new Error("Row before insertion index does not exist.");for(let e=0;e<o;e++){const e=s.getChildren(),t=e.length,o=nt();for(let n=0;n<t;n++){const t=e[n];Ge(t)||Ze(12);const{above:l,below:s}=ut(t,r);let i=Xe.NO_STATUS;const c=l&&l.getWidth()||s&&s.getWidth()||void 0;(l&&l.hasHeaderState(Xe.COLUMN)||s&&s.hasHeaderState(Xe.COLUMN))&&(i|=Xe.COLUMN);const a=Ve(i,1,c);a.append(p()),o.append(a)}n?s.insertAfter(o):s.insertBefore(o)}return e}const ft=(e,t)=>e===Xe.BOTH||e===t?t:Xe.NO_STATUS;function gt(e=!0){const t=b();w(t)||Pt(t)||Ze(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[r]=Mt(n),[l,,s]=Mt(o),[,i,c]=Et(s,l,r),{startRow:a}=c,{startRow:u}=i;return e?pt(a+r.__rowSpan>u+l.__rowSpan?r:l,!0):pt(u<a?l:r,!1)}const mt=gt;function pt(e,t=!0){const[,,n]=Mt(e),[o,r]=Et(n,e,e),l=o[0].length,{startRow:s}=r;let i=null;if(t){const t=s+e.__rowSpan-1,r=o[t],c=nt();for(let e=0;e<l;e++){const{cell:n,startRow:o}=r[e];if(o+n.__rowSpan-1<=t){const t=r[e].cell.__headerState,n=ft(t,Xe.COLUMN);c.append(Ve(n).append(p()))}else n.setRowSpan(n.__rowSpan+1)}const a=n.getChildAtIndex(t);ot(a)||Ze(256),a.insertAfter(c),i=c}else{const e=s,t=o[e],r=nt();for(let n=0;n<l;n++){const{cell:o,startRow:l}=t[n];if(l===e){const e=t[n].cell.__headerState,o=ft(e,Xe.COLUMN);r.append(Ve(o).append(p()))}else o.setRowSpan(o.__rowSpan+1)}const c=n.getChildAtIndex(e);ot(c)||Ze(257),c.insertBefore(r),i=r}return i}function Ct(e,t,n=!0,o,r){const l=e.getChildren(),s=[];for(let e=0;e<l.length;e++){const n=l[e];if(ot(n))for(let e=0;e<o;e++){const e=n.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");const o=e[t];Ge(o)||Ze(12);const{left:l,right:i}=ut(o,r);let c=Xe.NO_STATUS;(l&&l.hasHeaderState(Xe.ROW)||i&&i.hasHeaderState(Xe.ROW))&&(c|=Xe.ROW);const a=Ve(c);a.append(p()),s.push({newTableCell:a,targetCell:o})}}return s.forEach(({newTableCell:e,targetCell:t})=>{n?t.insertAfter(e):t.insertBefore(e)}),e}function _t(e=!0){const t=b();w(t)||Pt(t)||Ze(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[r]=Mt(n),[l,,s]=Mt(o),[,i,c]=Et(s,l,r),{startColumn:a}=c,{startColumn:u}=i;return e?bt(a+r.__colSpan>u+l.__colSpan?r:l,!0):bt(u<a?l:r,!1)}const St=_t;function bt(e,t=!0,n=!0){const[,,o]=Mt(e),[r,l]=Et(o,e,e),s=r.length,{startColumn:i}=l,c=t?i+e.__colSpan-1:i-1,a=o.getFirstChild();ot(a)||Ze(120);let u=null;function h(e=Xe.NO_STATUS){const t=Ve(e).append(p());return null===u&&(u=t),t}let d=a;e:for(let e=0;e<s;e++){if(0!==e){const e=d.getNextSibling();ot(e)||Ze(121),d=e}const t=r[e],n=t[c<0?0:c].cell.__headerState,o=ft(n,Xe.ROW);if(c<0){Ft(d,h(o));continue}const{cell:l,startColumn:s,startRow:i}=t[c];if(s+l.__colSpan-1<=c){let n=l,r=i,s=c;for(;r!==e&&n.__rowSpan>1;){if(s-=l.__colSpan,!(s>=0)){d.append(h(o));continue e}{const{cell:e,startRow:o}=t[s];n=e,r=o}}n.insertAfter(h(o))}else l.setColSpan(l.__colSpan+1)}null!==u&&n&&Tt(u);const f=o.getColWidths();if(f){const e=[...f],t=c<0?0:c,n=e[t];e.splice(t,0,n),o.setColWidths(e)}return u}function wt(e,t){const n=e.getChildren();for(let e=0;e<n.length;e++){const o=n[e];if(ot(o)){const e=o.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");e[t].remove()}}return e}function yt(){const e=b();w(e)||Pt(e)||Ze(188);const[t,n]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[o,,r]=Mt(t),[l]=Mt(n),[s,i,c]=Et(r,o,l),{startRow:a}=i,{startRow:u}=c,h=u+l.__rowSpan-1;if(s.length===h-a+1)return void r.remove();const d=s[0].length,f=s[h+1],g=r.getChildAtIndex(h+1);for(let e=h;e>=a;e--){for(let t=d-1;t>=0;t--){const{cell:n,startRow:o,startColumn:r}=s[e][t];if(r===t){if(o<a||o+n.__rowSpan-1>h){const e=Math.max(o,a),t=Math.min(n.__rowSpan+o-1,h),r=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-r)}if(o>=a&&o+n.__rowSpan-1>h&&e===h){null===g&&Ze(122);let o=null;for(let n=0;n<t;n++){const t=f[n],r=t.cell;t.startRow===e+1&&(o=r),r.__colSpan>1&&(n+=r.__colSpan-1)}null===o?Ft(g,n):o.insertAfter(n)}}}const t=r.getChildAtIndex(e);ot(t)||Ze(206,String(e)),t.remove()}if(void 0!==f){const{cell:e}=f[0];Tt(e)}else{const e=s[a-1],{cell:t}=e[0];Tt(t)}}const Nt=yt;function vt(){const e=b();w(e)||Pt(e)||Ze(188);const t=e.anchor.getNode(),n=e.focus.getNode(),[o,,r]=Mt(t),[l]=Mt(n),[s,i,c]=Et(r,o,l),{startColumn:a}=i,{startRow:u,startColumn:h}=c,d=Math.min(a,h),f=Math.max(a+o.__colSpan-1,h+l.__colSpan-1),g=f-d+1;if(s[0].length===f-d+1)return r.selectPrevious(),void r.remove();const m=s.length;for(let e=0;e<m;e++)for(let t=d;t<=f;t++){const{cell:n,startColumn:o}=s[e][t];if(o<d){if(t===d){const e=d-o;n.setColSpan(n.__colSpan-Math.min(g,n.__colSpan-e))}}else if(o+n.__colSpan-1>f){if(t===f){const e=f-o+1;n.setColSpan(n.__colSpan-e)}}else n.remove()}const p=s[u],C=a>h?p[a+o.__colSpan]:p[h+l.__colSpan];if(void 0!==C){const{cell:e}=C;Tt(e)}else{const e=h<a?p[h-1]:p[a-1],{cell:t}=e;Tt(t)}const _=r.getColWidths();if(_){const e=[..._];e.splice(d,g),r.setColWidths(e)}}const xt=vt;function Tt(e){const t=e.getFirstDescendant();null==t?e.selectStart():t.getParentOrThrow().selectStart()}function Ft(e,t){const n=e.getFirstChild();null!==n?n.insertBefore(t):e.append(t)}function Rt(e){if(0===e.length)return null;const t=it(e[0]),[n]=kt(t,null,null);let o=1/0,r=-1/0,l=1/0,s=-1/0;const i=new Set;for(const t of n)for(const n of t){if(!n||!n.cell)continue;const t=n.cell.getKey();if(!i.has(t)&&e.some(e=>e.is(n.cell))){i.add(t);const e=n.startRow,c=n.startColumn,a=n.cell.__rowSpan||1,u=n.cell.__colSpan||1;o=Math.min(o,e),r=Math.max(r,e+a-1),l=Math.min(l,c),s=Math.max(s,c+u-1)}}if(o===1/0||l===1/0)return null;const c=r-o+1,a=s-l+1,u=n[o][l];if(!u.cell)return null;const h=u.cell;h.setColSpan(a),h.setRowSpan(c);const d=new Set([h.getKey()]);for(let e=o;e<=r;e++)for(let t=l;t<=s;t++){const o=n[e][t];if(!o.cell)continue;const r=o.cell,l=r.getKey();if(!d.has(l)){d.add(l);Ot(r)||h.append(...r.getChildren()),r.remove()}}return 0===h.getChildrenSize()&&h.append(p()),h}function Ot(e){if(1!==e.getChildrenSize())return!1;const t=e.getFirstChildOrThrow();return!(!y(t)||!t.isEmpty())}function At(){const e=b();w(e)||Pt(e)||Ze(188);const t=e.anchor.getNode(),o=n(t,Ge);return Ge(o)||Ze(148),Kt(o)}function Kt(e){const[t,n,o]=Mt(e),r=t.__colSpan,l=t.__rowSpan;if(1===r&&1===l)return;const[s,i]=Et(o,t,t),{startColumn:c,startRow:a}=i,u=t.__headerState&Xe.COLUMN,h=Array.from({length:r},(e,t)=>{let n=u;for(let e=0;0!==n&&e<s.length;e++)n&=s[e][t+c].cell.__headerState;return n}),d=t.__headerState&Xe.ROW,f=Array.from({length:l},(e,t)=>{let n=d;for(let e=0;0!==n&&e<s[0].length;e++)n&=s[t+a][e].cell.__headerState;return n});if(r>1){for(let e=1;e<r;e++)t.insertAfter(Ve(h[e]|f[0]).append(p()));t.setColSpan(1)}if(l>1){let e;for(let t=1;t<l;t++){const o=a+t,l=s[o];e=(e||n).getNextSibling(),ot(e)||Ze(125);let i=null;for(let e=0;e<c;e++){const t=l[e],n=t.cell;t.startRow===o&&(i=n),n.__colSpan>1&&(e+=n.__colSpan-1)}if(null===i)for(let n=r-1;n>=0;n--)Ft(e,Ve(h[n]|f[t]).append(p()));else for(let e=r-1;e>=0;e--)i.insertAfter(Ve(h[e]|f[t]).append(p()))}t.setRowSpan(1)}}function Et(e,t,n){const[o,r,l]=kt(e,t,n);return null===r&&Ze(207),null===l&&Ze(208),[o,r,l]}function kt(e,t,n){const o=[];let r=null,l=null;function s(e){let t=o[e];return void 0===t&&(o[e]=t=[]),t}const i=e.getChildren();for(let e=0;e<i.length;e++){const o=i[e];ot(o)||Ze(209);const c=s(e);for(let a=o.getFirstChild(),u=0;null!=a;a=a.getNextSibling()){for(Ge(a)||Ze(147);void 0!==c[u];)u++;const o={cell:a,startColumn:u,startRow:e},{__rowSpan:h,__colSpan:d}=a;for(let t=0;t<h&&!(e+t>=i.length);t++){const n=s(e+t);for(let e=0;e<d;e++)n[u+e]=o}null!==t&&null===r&&t.is(a)&&(r=o),null!==n&&null===l&&n.is(a)&&(l=o)}}return[o,r,l]}function Mt(e){let t;if(e instanceof Ye)t=e;else if("__type"in e){const o=n(e,Ge);Ge(o)||Ze(148),t=o}else{const o=n(e.getNode(),Ge);Ge(o)||Ze(148),t=o}const o=t.getParent();ot(o)||Ze(149);const r=o.getParent();return Bn(r)||Ze(210),[t,o,r]}function $t(e,t,n){let o,r=Math.min(t.startColumn,n.startColumn),l=Math.min(t.startRow,n.startRow),s=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),i=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{o=!1;for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const c=e[t][n];if(!c)continue;const a=c.startColumn+c.cell.__colSpan-1,u=c.startRow+c.cell.__rowSpan-1,h=c.startColumn<=s&&a>=r,d=c.startRow<=i&&u>=l;if(h&&d){const e=Math.min(r,c.startColumn),t=Math.max(s,a),n=Math.min(l,c.startRow),h=Math.max(i,u);e===r&&t===s&&n===l&&h===i||(r=e,s=t,l=n,i=h,o=!0)}}}while(o);return{maxColumn:s,maxRow:i,minColumn:r,minRow:l}}function Wt(e){const t=e.getChildren();let n=null;for(const e of t){if(!ot(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!Ge(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function zt(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!Wt(e))return;e.getChildren().filter(ot).forEach(e=>{const o=e.getChildren(),[r]=o.splice(t,1);o.splice(n,0,r),e.splice(0,o.length,o)});const r=e.getColWidths();if(r&&r.length===o){const o=[...r],[l]=o.splice(t,1);o.splice(n,0,l),e.setColWidths(o)}}function Lt(e){const[t,,n]=Mt(e),o=n.getChildren(),r=o.length,l=o[0].getChildren().length,s=new Array(r);for(let e=0;e<r;e++)s[e]=new Array(l);for(let e=0;e<r;e++){const n=o[e].getChildren();let r=0;for(let o=0;o<n.length;o++){for(;s[e][r];)r++;const l=n[o],i=l.__rowSpan||1,c=l.__colSpan||1;for(let t=0;t<i;t++)for(let n=0;n<c;n++)s[e+t][r+n]=l;if(t===l)return{colSpan:c,columnIndex:r,rowIndex:e,rowSpan:i};r+=c}}return null}function Ht(e){const[[t,o,r,l],[s,i,c,a]]=["anchor","focus"].map(t=>{const o=e[t].getNode(),r=n(o,Ge);Ge(r)||Ze(238,t,o.getKey(),o.getType());const l=r.getParent();ot(l)||Ze(239,t);const s=l.getParent();return Bn(s)||Ze(240,t),[o,r,l,s]});return l.is(a)||Ze(241),{anchorCell:o,anchorNode:t,anchorRow:r,anchorTable:l,focusCell:i,focusNode:s,focusRow:c,focusTable:a}}class Bt{tableKey;anchor;focus;_cachedNodes;dirty;constructor(e,t,n){this.anchor=t,this.focus=n,t._selection=this,n._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=e}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if("root"===this.tableKey||"root"===this.anchor.key||"element"!==this.anchor.type||"root"===this.focus.key||"element"!==this.focus.type)return!1;const e=v(this.tableKey),t=v(this.anchor.key),n=v(this.focus.key);return null!==e&&null!==t&&null!==n}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return Pt(e)&&this.tableKey===e.tableKey&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)}set(e,t,n){this.dirty=this.dirty||e!==this.tableKey||t!==this.anchor.key||n!==this.focus.key,this.tableKey=e,this.anchor.key=t,this.focus.key=n,this._cachedNodes=null}clone(){return new Bt(this.tableKey,N(this.anchor.key,this.anchor.offset,this.anchor.type),N(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(e){}insertText(){}hasFormat(e){let t=0;this.getNodes().filter(Ge).forEach(e=>{const n=e.getFirstChild();y(n)&&(t|=n.getTextFormat())});const n=R[e];return 0!==(t&n)}insertNodes(e){const t=this.focus.getNode();x(t)||Ze(151);T(t.select(0,t.getChildrenSize())).insertNodes(e)}getShape(){const{anchorCell:e,focusCell:t}=Ht(this),n=Lt(e);null===n&&Ze(153);const o=Lt(t);null===o&&Ze(155);const r=Math.min(n.columnIndex,o.columnIndex),l=Math.max(n.columnIndex+n.colSpan-1,o.columnIndex+o.colSpan-1),s=Math.min(n.rowIndex,o.rowIndex),i=Math.max(n.rowIndex+n.rowSpan-1,o.rowIndex+o.rowSpan-1);return{fromX:Math.min(r,l),fromY:Math.min(s,i),toX:Math.max(r,l),toY:Math.max(s,i)}}getNodes(){if(!this.isValid())return[];const e=this._cachedNodes;if(null!==e)return e;const{anchorTable:t,anchorCell:n,focusCell:o}=Ht(this),r=o.getParents()[1];if(r!==t){if(t.isParentOf(o)){const e=r.getParent();null==e&&Ze(159),this.set(this.tableKey,o.getKey(),e.getKey())}else{const e=t.getParent();null==e&&Ze(158),this.set(this.tableKey,e.getKey(),o.getKey())}return this.getNodes()}const[l,s,i]=Et(t,n,o),{minColumn:c,maxColumn:a,minRow:u,maxRow:h}=$t(l,s,i),d=new Map([[t.getKey(),t]]);let f=null;for(let e=u;e<=h;e++)for(let t=c;t<=a;t++){const{cell:n}=l[e][t],o=n.getParent();ot(o)||Ze(160),o!==f&&(d.set(o.getKey(),o),f=o),d.has(n.getKey())||Ut(n,e=>{d.set(e.getKey(),e)})}const g=Array.from(d.values());return F()||(this._cachedNodes=g),g}getTextContent(){const e=this.getNodes().filter(e=>Ge(e));let t="";for(let n=0;n<e.length;n++){const o=e[n],r=o.__parent,l=(e[n+1]||{}).__parent;t+=o.getTextContent()+(l!==r?"\n":"\t")}return t}}function Pt(e){return e instanceof Bt}function Dt(){const e=N("root",0,"element"),t=N("root",0,"element");return new Bt("root",e,t)}function It(e,t,n){e.getKey(),t.getKey(),n.getKey();const o=b(),r=Pt(o)?o.clone():Dt();return r.set(e.getKey(),t.getKey(),n.getKey()),r}function Ut(e,t){const n=[[e]];for(let e=n.at(-1);void 0!==e&&n.length>0;e=n.at(-1)){const o=e.pop();void 0===o?n.pop():!1!==t(o)&&x(o)&&n.push(o.getChildren())}}function Jt(e,t=O()){const n=v(e);Bn(n)||Ze(231,e);const o=Vt(n,t.getElementByKey(e));return null===o&&Ze(232,e),{tableElement:o,tableNode:n}}class Xt{observers;nextFocus;shouldCheckSelectionForTable;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null}setNextFocus(e){this.nextFocus=e}getAndClearNextFocus(){const{nextFocus:e}=this;return null!==e&&(this.nextFocus=null),e}setShouldCheckSelectionForTable(e){this.shouldCheckSelectionForTable=e}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:e}=this;return e?(this.shouldCheckSelectionForTable=null,e):null}}class Yt{focusX;focusY;listenersToRemove;table;isHighlightingCells;anchorX;anchorY;tableNodeKey;anchorCell;focusCell;anchorCellNodeKey;focusCellNodeKey;editor;tableSelection;hasHijackedSelectionStyles;isSelecting;pointerType;abortController;listenerOptions;constructor(e,t){this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=t,this.editor=e,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort("removeListeners"),Array.from(this.listenersToRemove).forEach(e=>e()),this.listenersToRemove.clear()}$lookup(){return Jt(this.tableNodeKey,this.editor)}trackTable(){const e=new MutationObserver(e=>{this.editor.getEditorState().read(()=>{let t=!1;for(let n=0;n<e.length;n++){const o=e[n].target.nodeName;if("TABLE"===o||"TBODY"===o||"THEAD"===o||"TR"===o){t=!0;break}}if(!t)return;const{tableNode:n,tableElement:o}=this.$lookup();this.table=un(n,o)},{editor:this.editor})});this.editor.getEditorState().read(()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=un(t,n),e.observe(n,{attributes:!0,childList:!0,subtree:!0})},{editor:this.editor})}$clearHighlight(e=!0){const t=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:n,tableElement:o}=this.$lookup();hn(t,un(n,o),null),e&&null!==b()&&(A(null),t.dispatchCommand(K,void 0))}$enableHighlightStyle(){const e=this.editor,{tableElement:t}=this.$lookup();o(t,e._config.theme.tableSelection),t.classList.remove("disable-selection"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:t}=this.$lookup();e(t,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(e){if(null!==e){e.tableKey!==this.tableNodeKey&&Ze(233,e.tableKey,this.tableNodeKey);const t=this.editor;this.tableSelection=e,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),hn(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=E(this.editor._window);e&&e.rangeCount>0&&e.removeAllRanges()}}$setFocusCellForSelection(e,t=!1){const n=this.editor,{tableNode:o}=this.$lookup(),r=e.x,l=e.y;if(this.focusCell=e,!this.isHighlightingCells){(t||this.anchorX!==r||this.anchorY!==l||null!=this.tableSelection&&null!=this.anchorCellNodeKey)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle())}if(-1!==this.focusX&&-1!==this.focusY&&r===this.focusX&&l===this.focusY)return!1;if(this.focusX=r,this.focusY=l,this.isHighlightingCells){const s=An(o,e.elem);if(null!=this.tableSelection&&null!=this.anchorCellNodeKey){let e=s;if(null===e&&t&&(e=o.getCellNodeFromCords(r,l,this.table)),null!==e){const t=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=e.getKey(),this.tableSelection=It(o,t,e),A(this.tableSelection),n.dispatchCommand(K,void 0),hn(n,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){return this.anchorCellNodeKey?v(this.anchorCellNodeKey):null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&Ze(234),e}$getFocusTableCell(){return this.focusCellNodeKey?v(this.focusCellNodeKey):null}$getFocusTableCellOrThrow(){const e=this.$getFocusTableCell();return null===e&&Ze(235),e}$setAnchorCellForSelection(e){this.isHighlightingCells=!1,this.anchorCell=e,this.anchorX=e.x,this.anchorY=e.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:t}=this.$lookup(),n=An(t,e.elem);if(null!==n){const e=n.getKey();null!=this.tableSelection?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(t.getKey(),e,e)):this.tableSelection=It(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const t=b();Pt(t)||Ze(236);const n=k(),o=n.anchor,r=n.focus,l=t.getNodes().filter(Ge);l.length>0||Ze(237);const s=l[0].getFirstChild(),i=y(s)?s.getFormatFlags(e,null):null;l.forEach(t=>{o.set(t.getKey(),0,"element"),r.set(t.getKey(),t.getChildrenSize(),"element"),n.formatText(e,i)}),A(t),this.editor.dispatchCommand(K,void 0)}$clearText(){const{editor:e}=this,t=v(this.tableNodeKey);if(!Bn(t))throw new Error("Expected TableNode.");const n=b();Pt(n)||Ze(253);const o=n.getNodes().filter(Ge),r=t.getFirstChild(),l=t.getLastChild();if(o.length>0&&null!==r&&null!==l&&ot(r)&&ot(l)&&o[0]===r.getFirstChild()&&o[o.length-1]===l.getLastChild()){t.selectPrevious();const n=t.getParent();return t.remove(),void(M(n)&&n.isEmpty()&&e.dispatchCommand($,void 0))}o.forEach(e=>{if(x(e)){const t=p(),n=S();t.append(n),e.append(t),e.getChildren().forEach(e=>{e!==t&&e.remove()})}}),hn(e,this.table,null),A(null),e.dispatchCommand(K,void 0)}}const qt="__lexicalTableSelection";function jt(e){return d(e)&&"TABLE"===e.nodeName}function Vt(e,t){if(!t)return t;const n=jt(t)?t:t.querySelector("table");return jt(n)||Ze(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function Gt(e){return e._window}function Qt(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;Ge(n)&&(o=n)}return null}const Zt=[[W,"down"],[z,"up"],[L,"backward"],[H,"forward"]],en=[D,I,U],tn=[J,X];function nn(e,t){return e.registerRootListener(n=>{if(null===n)return;const o=e._window;if(null===o)return;const r=o=>{const r=o.target;if(0!==o.button||!ee(r)||!n.contains(r))return;const l=function(e){const t=cn(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if("TABLE"===n.nodeName&&qt in n&&n[qt])return{cellElement:t,tableElement:n,tableObserver:n[qt]};n=n.parentNode}return null}(r);e.update(()=>{if(Pt(b())){for(const[e]of t.observers.values())e.$clearHighlight(!1);A(null),e.dispatchCommand(K,void 0)}if(!l)return;const{tableObserver:n,tableElement:r,cellElement:s}=l;!function(e,t,n,o,r,l){const s=e._window;if(!s)return;const i=t=>{if(r.isSelecting)return;r.isSelecting=!0,null!==t&&null===r.anchorCell&&e.update(()=>{r.$setAnchorCellForSelection(t)});const n=()=>{r.isSelecting=!1,s.removeEventListener("pointerup",n),s.removeEventListener("pointermove",i)},i=t=>{if(!(e=>!(1&~e.buttons))(t)&&r.isSelecting)return r.isSelecting=!1,s.removeEventListener("pointerup",n),void s.removeEventListener("pointermove",i);if(!ee(t.target))return;let c=null;const a=!(me||o.contains(t.target));if(a)c=an(o,t.target);else for(const e of document.elementsFromPoint(t.clientX,t.clientY))if(c=an(o,e),c)break;if(c){const t=c;null===r.anchorCell&&e.update(()=>{r.$setAnchorCellForSelection(t)}),null!==r.focusCell&&c.elem===r.focusCell.elem||(l.setNextFocus({focusCell:c,override:a,tableKey:r.tableNodeKey}),e.dispatchCommand(K,void 0))}};s.addEventListener("pointerup",n,r.listenerOptions),s.addEventListener("pointermove",i,r.listenerOptions)};r.pointerType=t.pointerType;const c=oe(r.tableNodeKey),a=ne();if(me&&t.shiftKey&&_n(a,c)&&(w(a)||Pt(a))){const e=a.anchor.getNode(),o=Qt(c,a.anchor.getNode());if(o)r.$setAnchorCellForSelection(On(r,o)),r.$setFocusCellForSelection(n),Tn(t);else{(c.isBefore(e)?c.selectStart():c.selectEnd()).anchor.set(a.anchor.key,a.anchor.offset,a.anchor.type)}}else"touch"!==t.pointerType&&r.$setAnchorCellForSelection(n);i(n)}(e,o,s,r,n,t)})};return o.addEventListener("pointerdown",r),()=>{o.removeEventListener("pointerdown",r)}})}function on(e,t,o,l,s){const i=o.getRootElement(),c=Gt(o);null!==i&&null!==c||Ze(246);const a=new Yt(o,e.getKey()),u=Vt(e,t);!function(e,t){null!==sn(e)&&Ze(205);e[qt]=t}(u,a),a.listenersToRemove.add(()=>function(e,t){sn(e)===t&&delete e[qt]}(u,a));const h=e=>{if(e.detail>=3&&ee(e.target)){null!==cn(e.target)&&e.preventDefault()}};u.addEventListener("mousedown",h,a.listenerOptions),a.listenersToRemove.add(()=>{u.removeEventListener("mousedown",h)});for(const[t,n]of Zt)a.listenersToRemove.add(o.registerCommand(t,t=>xn(o,t,n,e,a,s),B));a.listenersToRemove.add(o.registerCommand(P,t=>{const n=b();if(Pt(n)){const o=Qt(e,n.focus.getNode());if(null!==o)return Tn(t),o.selectEnd(),!0}return!1},B));const d=t=>()=>{const o=b();if(!_n(o,e))return!1;if(Pt(o))return a.$clearText(),!0;if(w(o)){if(!Ge(Qt(e,o.anchor.getNode())))return!1;const r=o.anchor.getNode(),l=o.focus.getNode(),s=e.isParentOf(r),i=e.isParentOf(l);if(s&&!i||i&&!s)return a.$clearText(),!0;const c=n(o.anchor.getNode(),e=>x(e)),u=c&&n(c,e=>x(e)&&Ge(e.getParent()));if(!x(u)||!x(c))return!1;if(t===I&&null===u.getPreviousSibling())return!0}return!1};for(const e of en)a.listenersToRemove.add(o.registerCommand(e,d(e),B));const f=t=>{const n=b();if(!Pt(n)&&!w(n))return!1;const o=e.isParentOf(n.anchor.getNode());if(o!==e.isParentOf(n.focus.getNode())){const t=o?"anchor":"focus",r=o?"focus":"anchor",{key:l,offset:s,type:i}=n[r];return e[n[t].isBefore(n[r])?"selectPrevious":"selectNext"]()[r].set(l,s,i),!1}return!!_n(n,e)&&(!!Pt(n)&&(t&&(t.preventDefault(),t.stopPropagation()),a.$clearText(),!0))};for(const e of tn)a.listenersToRemove.add(o.registerCommand(e,f,B));return a.listenersToRemove.add(o.registerCommand(Y,e=>{const t=b();if(t){if(!Pt(t)&&!w(t))return!1;We(o,r(e,ClipboardEvent)?e:null,ze(t));const n=f(e);return w(t)?(t.removeText(),!0):n}return!1},B)),a.listenersToRemove.add(o.registerCommand(q,t=>{const o=b();if(!_n(o,e))return!1;if(Pt(o))return a.$formatCells(t),!0;if(w(o)){const e=n(o.anchor.getNode(),e=>Ge(e));if(!Ge(e))return!1}return!1},B)),a.listenersToRemove.add(o.registerCommand(j,t=>{const n=b();if(!Pt(n)||!_n(n,e))return!1;const o=n.anchor.getNode(),r=n.focus.getNode();if(!Ge(o)||!Ge(r))return!1;if(function(e,t){if(Pt(e)){const n=e.anchor.getNode(),o=e.focus.getNode();if(t&&n&&o){const[e]=Et(t,n,o);return n.getKey()===e[0][0].cell.getKey()&&o.getKey()===e[e.length-1].at(-1).cell.getKey()}}return!1}(n,e))return e.setFormat(t),!0;const[l,s,i]=Et(e,o,r),c=Math.max(s.startRow+s.cell.__rowSpan-1,i.startRow+i.cell.__rowSpan-1),a=Math.max(s.startColumn+s.cell.__colSpan-1,i.startColumn+i.cell.__colSpan-1),u=Math.min(s.startRow,i.startRow),h=Math.min(s.startColumn,i.startColumn),d=new Set;for(let e=u;e<=c;e++)for(let n=h;n<=a;n++){const o=l[e][n].cell;if(d.has(o))continue;d.add(o),o.setFormat(t);const r=o.getChildren();for(let e=0;e<r.length;e++){const n=r[e];x(n)&&!n.isInline()&&n.setFormat(t)}}return!0},B)),a.listenersToRemove.add(o.registerCommand(V,t=>{const r=b();if(!_n(r,e))return!1;if(Pt(r))return a.$clearHighlight(),!1;if(w(r)){const l=n(r.anchor.getNode(),e=>Ge(e));if(!Ge(l))return!1;if("string"==typeof t){const n=Rn(o,r,e);if(n)return Fn(n,e,[S(t)]),!0}}return!1},B)),l&&a.listenersToRemove.add(o.registerCommand(G,t=>{const o=b();if(!w(o)||!o.isCollapsed()||!_n(o,e))return!1;const r=yn(o.anchor.getNode());return!(null===r||!e.is(Nn(r)))&&(Tn(t),function(e,t){const o="next"===t?"getNextSibling":"getPreviousSibling",r="next"===t?"getFirstChild":"getLastChild",l=e[o]();if(x(l))return l.selectEnd();const s=n(e,ot);null===s&&Ze(247);for(let e=s[o]();ot(e);e=e[o]()){const t=e[r]();if(x(t))return t.selectEnd()}const i=n(s,Bn);null===i&&Ze(248);"next"===t?i.selectNext():i.selectPrevious()}(r,t.shiftKey?"previous":"next"),!0)},B)),a.listenersToRemove.add(o.registerCommand(Q,t=>e.isSelected(),B)),a.listenersToRemove.add(o.registerCommand($,()=>{const t=b();if(!w(t)||!t.isCollapsed()||!_n(t,e))return!1;const n=Rn(o,t,e);return!!n&&(Fn(n,e),!0)},B)),a}function rn(e,t){const o=b(),r=ne(),l=e.getAndClearNextFocus();if(null!==l){const{tableKey:t,focusCell:n}=l,r=e.observers.get(t);r||Ze(335,t);const[s]=r;if(Pt(o)&&o.tableKey===s.tableNodeKey)return(n.x!==s.focusX||n.y!==s.focusY)&&(s.$setFocusCellForSelection(n),!0);if(null!==s.anchorCell&&null!==s.anchorCellNodeKey&&n.elem!==s.anchorCell.elem&&null!==s.tableSelection)return s.$setFocusCellForSelection(n,!0),!0}const s=e.getAndClearShouldCheckSelectionForTable();if(s&&w(r)&&w(o)&&o.isCollapsed()){const e=oe(s),t=o.anchor.getNode(),r=e.getFirstChild(),l=yn(t);if(null!==l&&ot(r)){const t=r.getFirstChild();if(Ge(t)&&e.is(n(l,n=>n.is(e)||n.is(t))))return t.selectStart(),!0}}Pt(o)&&function(e,t){const n=Gt(e),o=ne();if(!t.is(o))return;const r=oe(t.tableKey),l=E(n);if(l&&l.anchorNode&&l.focusNode){const n=Z(l.focusNode),o=n&&!r.isParentOf(n),s=Z(l.anchorNode),i=s&&r.isParentOf(s);if(o&&i&&l.rangeCount>0){const n=he(l,e);n&&(n.anchor.set(r.getKey(),t.isBackward()?r.getChildrenSize():0,"element"),l.removeAllRanges(),A(n))}}}(t,o),w(o)&&function(e,t){const n=ne(),{anchor:o,focus:r}=e,l=o.getNode(),s=r.getNode(),i=yn(l),c=yn(s),a=i?Nn(i):null,u=c?Nn(c):null,h=e.isBackward(),d=i&&c&&a&&u&&a.is(u),f=u&&(!a||a.isParentOf(u)),g=a&&(!u||u.isParentOf(a));if(f){const t=e.clone(),[n]=Et(u,c,c),o=n[0][0].cell,r=n[n.length-1].at(-1).cell;t.focus.set(h?o.getKey():r.getKey(),h?0:r.getChildrenSize(),"element"),A(t)}else if(g){const t=e.clone(),[n]=Et(a,i,i),o=n[0][0].cell,r=n[n.length-1].at(-1).cell;t.anchor.set(h?r.getKey():o.getKey(),h?r.getChildrenSize():0,"element"),A(t)}else if(d){const o=t.observers.get(a.getKey());o||Ze(335,a.getKey());const[r]=o;if(i.is(c)||(r.$setAnchorCellForSelection(On(r,i)),r.$setFocusCellForSelection(On(r,c),!0)),"touch"===r.pointerType&&r.isSelecting&&e.isCollapsed()&&w(n)&&n.isCollapsed()){const e=yn(n.anchor.getNode());e&&!e.is(c)&&(r.$setAnchorCellForSelection(On(r,e)),r.$setFocusCellForSelection(On(r,c),!0),r.pointerType=null)}}}(o,e);const i=Array.from(e.observers.entries()).map(([e,[t]])=>({tableNode:oe(e),tableObserver:t}));for(const{tableNode:e,tableObserver:n}of i)ln(t,e,n);return!1}function ln(e,t,n){const o=b(),r=ne();o&&!o.is(r)&&(Pt(o)||Pt(r))&&n.tableSelection&&!n.tableSelection.is(r)&&(Pt(o)&&o.tableKey===n.tableNodeKey?n.$updateTableTableSelection(o):!Pt(o)&&Pt(r)&&r.tableKey===n.tableNodeKey&&n.$updateTableTableSelection(null)),n.hasHijackedSelectionStyles&&!t.isSelected()?function(e,t){t.$enableHighlightStyle(),dn(t.table,t=>{const n=t.elem;t.highlighted=!1,wn(e,t),n.getAttribute("style")||n.removeAttribute("style")})}(e,n):!n.hasHijackedSelectionStyles&&t.isSelected()&&function(e,t){t.$disableHighlightStyle(),dn(t.table,t=>{t.highlighted=!0,bn(e,t)})}(e,n)}function sn(e){return e[qt]||null}function cn(e){let t=e;for(;null!=t;){const e=t.nodeName;if("TD"===e||"TH"===e){const e=t._cell;return void 0===e?null:e}t=t.parentNode}return null}function an(e,t){if(!e.contains(t))return null;let n=null;for(let o=t;null!=o;o=o.parentNode){if(o===e)return n;const t=o.nodeName;"TD"!==t&&"TH"!==t||(n=o._cell||null)}return null}function un(e,t){const n=[],o={columns:0,domRows:n,rows:0};let r=Vt(e,t).querySelector("tr"),l=0,s=0;for(n.length=0;null!=r;){const e=r.nodeName;if("TD"===e||"TH"===e){const e={elem:r,hasBackgroundColor:""!==r.style.backgroundColor,highlighted:!1,x:l,y:s};r._cell=e;let t=n[s];void 0===t&&(t=n[s]=[]),t[l]=e}else{const e=r.firstChild;if(null!=e){r=e;continue}}const t=r.nextSibling;if(null!=t){l++,r=t;continue}const o=r.parentNode;if(null!=o){const e=o.nextSibling;if(null==e)break;s++,l=0,r=e}}return o.columns=l+1,o.rows=s+1,o}function hn(e,t,n){const o=new Set(n?n.getNodes():[]);dn(t,(t,n)=>{const r=t.elem;o.has(n)?(t.highlighted=!0,bn(e,t)):(t.highlighted=!1,wn(e,t),r.getAttribute("style")||r.removeAttribute("style"))})}function dn(e,t){const{domRows:n}=e;for(let e=0;e<n.length;e++){const o=n[e];if(o)for(let n=0;n<o.length;n++){const r=o[n];if(!r)continue;const l=Z(r.elem);null!==l&&t(r,l,{x:n,y:e})}}}const fn=(e,t,n,o,r)=>{const l="forward"===r;switch(r){case"backward":case"forward":return n!==(l?e.table.columns-1:0)?Sn(t.getCellNodeFromCordsOrThrow(n+(l?1:-1),o,e.table),l):o!==(l?e.table.rows-1:0)?Sn(t.getCellNodeFromCordsOrThrow(l?0:e.table.columns-1,o+(l?1:-1),e.table),l):l?t.selectNext():t.selectPrevious(),!0;case"up":return 0!==o?Sn(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case"down":return o!==e.table.rows-1?Sn(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function gn(e,t){let n,o;if(t.startColumn===e.minColumn)n="minColumn";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n="maxColumn"}if(t.startRow===e.minRow)o="minRow";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;o="maxRow"}return[n,o]}function mn([e,t]){return["minColumn"===e?"maxColumn":"minColumn","minRow"===t?"maxRow":"minRow"]}function pn(e,t,[n,o]){const r=t[o],l=e[r];void 0===l&&Ze(250,o,String(r));const s=t[n],i=l[s];return void 0===i&&Ze(250,n,String(s)),i}function Cn(e,t,n,o,r){const l=$t(t,n,o),s=function(e,t){const{minColumn:n,maxColumn:o,minRow:r,maxRow:l}=t;let s=1,i=1,c=1,a=1;const u=e[r],h=e[l];for(let e=n;e<=o;e++)s=Math.max(s,u[e].cell.__rowSpan),a=Math.max(a,h[e].cell.__rowSpan);for(let t=r;t<=l;t++)i=Math.max(i,e[t][n].cell.__colSpan),c=Math.max(c,e[t][o].cell.__colSpan);return{bottomSpan:a,leftSpan:i,rightSpan:c,topSpan:s}}(t,l),{topSpan:i,leftSpan:c,bottomSpan:a,rightSpan:u}=s,h=function(e,t){const n=gn(e,t);return null===n&&Ze(249,t.cell.getKey()),n}(l,n),[d,f]=mn(h);let g=l[d],m=l[f];"forward"===r?g+="maxColumn"===d?1:c:"backward"===r?g-="minColumn"===d?1:u:"down"===r?m+="maxRow"===f?1:i:"up"===r&&(m-="minRow"===f?1:a);const p=t[m];if(void 0===p)return!1;const C=p[g];if(void 0===C)return!1;const[_,S]=function(e,t,n){const o=$t(e,t,n),r=gn(o,t);if(r)return[pn(e,o,r),pn(e,o,mn(r))];const l=gn(o,n);if(l)return[pn(e,o,mn(l)),pn(e,o,l)];const s=["minColumn","minRow"];return[pn(e,o,s),pn(e,o,mn(s))]}(t,n,C),b=On(e,_.cell),w=On(e,S.cell);return e.$setAnchorCellForSelection(b),e.$setFocusCellForSelection(w,!0),!0}function _n(e,t){if(w(e)||Pt(e)){const n=t.isParentOf(e.anchor.getNode()),o=t.isParentOf(e.focus.getNode());return n&&o}return!1}function Sn(e,t){t?e.selectStart():e.selectEnd()}function bn(t,n){const o=n.elem,r=t._config.theme;Ge(Z(o))||Ze(131),e(o,r.tableCellSelected)}function wn(e,t){const n=t.elem;Ge(Z(n))||Ze(131);const r=e._config.theme;o(n,r.tableCellSelected)}function yn(e){const t=n(e,Ge);return Ge(t)?t:null}function Nn(e){const t=n(e,Bn);return Bn(t)?t:null}function vn(e,t,o,r,l,s,i){const c=re(o.focus,l?"previous":"next");if(le(c))return!1;let a=c;for(const e of se(c).iterNodeCarets("shadowRoot")){if(!ie(e)||!x(e.origin))return!1;a=e}const u=a.getParentAtCaret();if(!Ge(u))return!1;const h=u,d=function(e){for(const t of se(e).iterNodeCarets("root")){const{origin:n}=t;if(Ge(n)){if(de(t))return fe(n,e.direction)}else if(!ot(n))break}return null}(ce(h,a.direction)),f=n(h,Bn);if(!f||!f.is(s))return!1;const g=e.getElementByKey(h.getKey()),m=cn(g);if(!g||!m)return!1;const p=zn(e,f);if(i.table=p,d)if("extend"===r){const t=cn(e.getElementByKey(d.origin.getKey()));if(!t)return!1;i.$setAnchorCellForSelection(m),i.$setFocusCellForSelection(t,!0)}else{const e=ue(d);ae(o.anchor,e),ae(o.focus,e)}else if("extend"===r)i.$setAnchorCellForSelection(m),i.$setFocusCellForSelection(m,!0);else{const e=function(e){const t=ge(e);return de(t)?ue(t):e}(ce(f,c.direction));ae(o.anchor,e),ae(o.focus,e)}return Tn(t),!0}function xn(e,t,o,r,l,s){if(("up"===o||"down"===o)&&function(e){const t=e.getRootElement();if(!t)return!1;return t.hasAttribute("aria-controls")&&"typeahead-menu"===t.getAttribute("aria-controls")}(e))return!1;const i=b();if(!_n(i,r)){if(w(i)){if("backward"===o){if(i.focus.offset>0)return!1;const e=function(e){for(let t=e,n=e;null!==n;t=n,n=n.getParent())if(x(n)){if(n!==t&&n.getFirstChild()!==t)return null;if(!n.isInline())return n}return null}(i.focus.getNode());if(!e)return!1;const n=e.getPreviousSibling();return!!Bn(n)&&(Tn(t),t.shiftKey?i.focus.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent(),"element"):n.selectEnd(),!0)}if(t.shiftKey&&("up"===o||"down"===o)){const e=i.focus.getNode();if(!i.isCollapsed()&&("up"===o&&!i.isBackward()||"down"===o&&i.isBackward())){let l=n(e,e=>Bn(e));if(Ge(l)&&(l=n(l,Bn)),l!==r)return!1;if(!l)return!1;const s="down"===o?l.getNextSibling():l.getPreviousSibling();if(!s)return!1;let c=0;"up"===o&&x(s)&&(c=s.getChildrenSize());let a=s;if("up"===o&&x(s)){const e=s.getLastChild();a=e||s,c=g(a)?a.getTextContentSize():0}const u=i.clone();return u.focus.set(a.getKey(),c,g(a)?"text":"element"),A(u),Tn(t),!0}if(te(e)){const e="up"===o?i.getNodes()[i.getNodes().length-1]:i.getNodes()[0];if(e){if(null!==Qt(r,e)){const e=r.getFirstDescendant(),t=r.getLastDescendant();if(!e||!t)return!1;const[n]=Mt(e),[o]=Mt(t),s=r.getCordsFromCellNode(n,l.table),i=r.getCordsFromCellNode(o,l.table),c=r.getDOMCellFromCordsOrThrow(s.x,s.y,l.table),a=r.getDOMCellFromCordsOrThrow(i.x,i.y,l.table);return l.$setAnchorCellForSelection(c),l.$setFocusCellForSelection(a,!0),!0}}return!1}{let r=n(e,e=>x(e)&&!e.isInline());if(Ge(r)&&(r=n(r,Bn)),!r)return!1;const s="down"===o?r.getNextSibling():r.getPreviousSibling();if(Bn(s)&&l.tableNodeKey===s.getKey()){const e=s.getFirstDescendant(),n=s.getLastDescendant();if(!e||!n)return!1;const[r]=Mt(e),[l]=Mt(n),c=i.clone();return c.focus.set(("up"===o?r:l).getKey(),"up"===o?0:l.getChildrenSize(),"element"),Tn(t),A(c),!0}}}}return"down"===o&&Mn(e)&&s.setShouldCheckSelectionForTable(r.getKey()),!1}if(w(i)){if("backward"===o||"forward"===o){return vn(e,t,i,t.shiftKey?"extend":"move","backward"===o,r,l)}if(i.isCollapsed()){const{anchor:c,focus:a}=i,u=n(c.getNode(),Ge),h=n(a.getNode(),Ge);if(!Ge(u)||!u.is(h))return!1;const d=Nn(u);if(d!==r&&null!=d){const n=Vt(d,e.getElementByKey(d.getKey()));if(null!=n)return l.table=un(d,n),xn(e,t,o,d,l,s)}const f=e.getElementByKey(u.__key),g=e.getElementByKey(c.key);if(null==g||null==f)return!1;let m;if("element"===c.type)m=g.getBoundingClientRect();else{const t=E(Gt(e));if(null===t||0===t.rangeCount)return!1;m=t.getRangeAt(0).getBoundingClientRect()}const p="up"===o?u.getFirstChild():u.getLastChild();if(null==p)return!1;const C=e.getElementByKey(p.__key);if(null==C)return!1;const _=C.getBoundingClientRect();if("up"===o?_.top>m.top-m.height:m.bottom+m.height>_.bottom){Tn(t);const e=r.getCordsFromCellNode(u,l.table);if(!t.shiftKey)return fn(l,r,e.x,e.y,o);{const t=r.getDOMCellFromCordsOrThrow(e.x,e.y,l.table);l.$setAnchorCellForSelection(t),l.$setFocusCellForSelection(t,!0)}return!0}}}else if(Pt(i)){const{anchor:s,focus:c,tableKey:a}=i;if(a!==r.getKey())return!1;const u=n(s.getNode(),Ge),h=n(c.getNode(),Ge),[d]=i.getNodes();Bn(d)||Ze(251);const f=Vt(d,e.getElementByKey(d.getKey()));if(!Ge(u)||!Ge(h)||!Bn(d)||null==f)return!1;l.$updateTableTableSelection(i);const g=un(d,f),m=r.getCordsFromCellNode(u,g),p=r.getDOMCellFromCordsOrThrow(m.x,m.y,g);if(l.$setAnchorCellForSelection(p),Tn(t),t.shiftKey){const[e,t,n]=Et(r,u,h);return Cn(l,e,t,n,o)}return h.selectEnd(),!0}return!1}function Tn(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function Fn(e,t,n){const o=p();"first"===e?t.insertBefore(o):t.insertAfter(o),o.append(...n||[]),o.selectEnd()}function Rn(e,t,o){const r=o.getParent();if(!r)return;const l=E(Gt(e));if(!l)return;const s=l.anchorNode,i=e.getElementByKey(r.getKey()),c=Vt(o,e.getElementByKey(o.getKey()));if(!s||!i||!c||!i.contains(s)||c.contains(s))return;const a=n(t.anchor.getNode(),e=>Ge(e));if(!a)return;const u=n(a,e=>Bn(e));if(!Bn(u)||!u.is(o))return;const[h,d]=Et(o,a,a),f=h[0][0],g=h[h.length-1][h[0].length-1],{startRow:m,startColumn:p}=d,C=m===f.startRow&&p===f.startColumn,_=m===g.startRow&&p===g.startColumn;return C?"first":_?"last":void 0}function On(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function An(e,t,n){return Qt(e,Z(t,n))}function Kn(e,t,n){const o=e.querySelector("colgroup");if(!o)return;const r=[];for(let e=0;e<t;e++){const t=document.createElement("col"),o=n&&n[e];o&&(t.style.width=`${o}px`),r.push(t)}o.replaceChildren(...r)}function En(t,n,r){if(!n.theme.tableAlignment)return;const l=[],s=[];for(const e of["center","right"]){const t=n.theme.tableAlignment[e];t&&(e===r?s:l).push(t)}o(t,...l),e(t,...s)}const kn=new WeakSet;function Mn(e=O()){return kn.has(e)}function $n(e,t){t?kn.add(e):kn.delete(e)}class Wn extends h{__rowStriping;__frozenColumnCount;__frozenRowCount;__colWidths;static getType(){return"table"}getColWidths(){return this.getLatest().__colWidths}setColWidths(e){const t=this.getWritable();return t.__colWidths=e,t}static clone(e){return new Wn(e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__colWidths=e.__colWidths,this.__rowStriping=e.__rowStriping,this.__frozenColumnCount=e.__frozenColumnCount,this.__frozenRowCount=e.__frozenRowCount}static importDOM(){return{table:e=>({conversion:Ln,priority:1})}}static importJSON(e){return Hn().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setRowStriping(e.rowStriping||!1).setFrozenColumns(e.frozenColumnCount||0).setFrozenRows(e.frozenRowCount||0).setColWidths(e.colWidths)}constructor(e){super(e),this.__rowStriping=!1,this.__frozenColumnCount=0,this.__frozenRowCount=0,this.__colWidths=void 0}exportJSON(){return{...super.exportJSON(),colWidths:this.getColWidths(),frozenColumnCount:this.__frozenColumnCount?this.__frozenColumnCount:void 0,frozenRowCount:this.__frozenRowCount?this.__frozenRowCount:void 0,rowStriping:this.__rowStriping?this.__rowStriping:void 0}}extractWithChild(e,t,n){return"html"===n}getDOMSlot(e){const t=jt(e)?e:e.querySelector("table");return jt(t)||Ze(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector("colgroup"))}createDOM(t,n){const o=document.createElement("table");this.__style&&pe(o.style,this.__style);const r=document.createElement("colgroup");if(o.appendChild(r),Ce(r),e(o,t.theme.table),this.updateTableElement(null,o,t),Mn(n)){const n=document.createElement("div"),r=t.theme.tableScrollableWrapper;return r?e(n,r):n.style.overflowX="auto",n.appendChild(o),this.updateTableWrapper(null,n,o,t),n}return o}updateTableWrapper(t,n,r,l){this.__frozenColumnCount!==(t?t.__frozenColumnCount:0)&&function(t,n,r,l){l>0?(e(t,r.theme.tableFrozenColumn),n.setAttribute("data-lexical-frozen-column","true")):(o(t,r.theme.tableFrozenColumn),n.removeAttribute("data-lexical-frozen-column"))}(n,r,l,this.__frozenColumnCount),this.__frozenRowCount!==(t?t.__frozenRowCount:0)&&function(t,n,r,l){l>0?(e(t,r.theme.tableFrozenRow),n.setAttribute("data-lexical-frozen-row","true")):(o(t,r.theme.tableFrozenRow),n.removeAttribute("data-lexical-frozen-row"))}(n,r,l,this.__frozenRowCount)}updateTableElement(t,n,r){this.__style!==(t?t.__style:"")&&pe(n.style,this.__style,t?t.__style:""),this.__rowStriping!==(!!t&&t.__rowStriping)&&function(t,n,r){r?(e(t,n.theme.tableRowStriping),t.setAttribute("data-lexical-row-striping","true")):(o(t,n.theme.tableRowStriping),t.removeAttribute("data-lexical-row-striping"))}(n,r,this.__rowStriping);const l=t?t.getColumnCount():0,s=t?t.__colWidths:void 0;this.getColumnCount()===l&&this.getColWidths()===s||Kn(n,this.getColumnCount(),this.getColWidths()),En(n,r,this.getFormatType())}updateDOM(e,t,n){const o=Vt(this,t);return t===o===Mn()||(l(r=t)&&"DIV"===r.nodeName&&this.updateTableWrapper(e,t,o,n),this.updateTableElement(e,o,n),!1);var r}scaleDOMColWidths(e,t){const n=this.getColWidths();if(!n)return;Kn(Vt(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(e){const t=super.exportDOM(e),{element:n}=t;return{after:n=>{if(t.after&&(n=t.after(n)),!jt(n)&&l(n)&&(n=n.querySelector("table")),!jt(n))return null;En(n,e._config,this.getFormatType());const[o]=kt(this,null,null),r=new Map;for(const e of o)for(const t of e){const e=t.cell.getKey();r.has(e)||r.set(e,{colSpan:t.cell.getColSpan(),startColumn:t.startColumn})}const s=new Set;for(const e of n.querySelectorAll(":scope > tr > [data-temporary-table-cell-lexical-key]")){const t=e.getAttribute("data-temporary-table-cell-lexical-key");if(t){const n=r.get(t);if(e.removeAttribute("data-temporary-table-cell-lexical-key"),n){r.delete(t);for(let e=0;e<n.colSpan;e++)s.add(e+n.startColumn)}}}const i=n.querySelector(":scope > colgroup");if(i){const e=Array.from(n.querySelectorAll(":scope > colgroup > col")).filter((e,t)=>s.has(t));i.replaceChildren(...e)}const c=n.querySelectorAll(":scope > tr");if(c.length>0){const e=document.createElement("tbody");for(const t of c)e.appendChild(t);n.append(e)}return n},element:!jt(n)&&l(n)?n.querySelector("table"):n}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(e,t){const{rows:n,domRows:o}=t;for(let t=0;t<n;t++){const n=o[t];if(null!=n)for(let o=0;o<n.length;o++){const r=n[o];if(null==r)continue;const{elem:l}=r,s=An(this,l);if(null!==s&&e.is(s))return{x:o,y:t}}}throw new Error("Cell not found in table.")}getDOMCellFromCords(e,t,n){const{domRows:o}=n,r=o[t];if(null==r)return null;const l=r[e<r.length?e:r.length-1];return null==l?null:l}getDOMCellFromCordsOrThrow(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(!o)throw new Error("Cell not found at cords.");return o}getCellNodeFromCords(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(null==o)return null;const r=Z(o.elem);return Ge(r)?r:null}getCellNodeFromCordsOrThrow(e,t,n){const o=this.getCellNodeFromCords(e,t,n);if(!o)throw new Error("Node at cords not TableCellNode.");return o}getRowStriping(){return Boolean(this.getLatest().__rowStriping)}setRowStriping(e){const t=this.getWritable();return t.__rowStriping=e,t}setFrozenColumns(e){const t=this.getWritable();return t.__frozenColumnCount=e,t}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(e){const t=this.getWritable();return t.__frozenRowCount=e,t}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const e=this.getFirstChild();if(!e)return 0;let t=0;return e.getChildren().forEach(e=>{Ge(e)&&(t+=e.getColSpan())}),t}}function zn(e,t){const n=e.getElementByKey(t.getKey());return null===n&&Ze(230),un(t,n)}function Ln(e){const n=Hn();e.hasAttribute("data-lexical-row-striping")&&n.setRowStriping(!0),e.hasAttribute("data-lexical-frozen-column")&&n.setFrozenColumns(1),e.hasAttribute("data-lexical-frozen-row")&&n.setFrozenRows(1);const o=e.querySelector(":scope > colgroup");if(o){let e=[];for(const t of o.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!Je.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&n.setColWidths(e)}return{after:e=>t(e,ot),node:n}}function Hn(){return C(new Wn)}function Bn(e){return e instanceof Wn}function Pn(e){ot(e.getParent())?e.isEmpty()&&e.append(p()):e.remove()}function Dn(e){Bn(e.getParent())?u(e,Ge):e.remove()}function In(e){u(e,ot);const[t]=kt(e,null,null),n=t.reduce((e,t)=>Math.max(e,t.length),0),o=e.getChildren();for(let e=0;e<t.length;++e){const r=o[e];if(!r)continue;ot(r)||Ze(254,r.constructor.name,r.getType());const l=t[e].reduce((e,t)=>t?1+e:e,0);if(l!==n)for(let e=l;e<n;++e){const e=Ve();e.append(p()),r.append(e)}}const r=e.getColWidths(),l=e.getColumnCount();if(r&&r.length!==l){let t;if(l<r.length)t=r.slice(0,l);else if(r.length>0){const e=r[r.length-1];t=[...r,...Array(l-r.length).fill(e)]}e.setColWidths(t)}}function Un(e){if(e.detail<3||!ee(e.target))return!1;const t=Z(e.target);if(null===t)return!1;const o=n(t,e=>x(e)&&!e.isInline());if(null===o)return!1;return!!Ge(o.getParent())&&(o.select(0),!0)}function Jn(){const e=b();if(!w(e))return!1;const t=Nn(e.anchor.getNode());if(null===t)return!1;const n=Ne();if(!n.is(t.getParent())||1!==n.getChildrenSize())return!1;const[o]=kt(t,null,null);if(0===o.length||0===o[0].length)return!1;const r=o[0][0];if(!r||!r.cell)return!1;const l=o[o.length-1],s=l[l.length-1];if(!s||!s.cell)return!1;const i=It(t,r.cell,s.cell);return A(i),!0}function Xn(e){return e.registerNodeTransform(Ye,e=>{if(e.getColSpan()>1||e.getRowSpan()>1){const[,,t]=Mt(e),[n]=Et(t,e,e),o=n.length,r=n[0].length;let l=t.getFirstChild();ot(l)||Ze(175);const i=[];for(let e=0;e<o;e++){0!==e&&(l=l.getNextSibling(),ot(l)||Ze(175));let t=null;for(let o=0;o<r;o++){const r=n[e][o],c=r.cell;if(r.startRow===e&&r.startColumn===o)t=c,i.push(c);else if(c.getColSpan()>1||c.getRowSpan()>1){Ge(c)||Ze(176);const e=Ve(c.__headerState);null!==t?t.insertAfter(e):s(l,e)}}}for(const e of i)e.setColSpan(1),e.setRowSpan(1)}})}function Yn(e,t=!0){const n=new Xt,o=(o,r,l)=>{const s=Vt(o,l),i=on(o,s,e,t,n);n.observers.set(r,[i,s])};return i(nn(e,n),e.registerCommand(K,()=>rn(n,e),B),e.registerMutationListener(Wn,t=>{e.getEditorState().read(()=>{for(const[e,r]of t){const t=n.observers.get(e);if("created"===r||"updated"===r){const{tableNode:r,tableElement:l}=Jt(e);void 0===t?o(r,e,l):l!==t[1]&&(t[0].removeListeners(),n.observers.delete(e),o(r,e,l))}else"destroyed"===r&&void 0!==t&&(t[0].removeListeners(),n.observers.delete(e))}},{editor:e})},{skipInitialization:!1}),()=>{for(const[,[e]]of n.observers)e.removeListeners()})}function qn(e,t){e.hasNodes([Wn])||Ze(255);const{hasNestedTables:o=ke(!1)}=t??{};return i(e.registerCommand(Qe,e=>function({rows:e,columns:t,includeHeaders:n},o){const r=b()||ne();if(!r||!w(r))return!1;if(!o&&Nn(r.anchor.getNode()))return!1;const l=rt(Number(e),Number(t),n);c(l);const s=l.getFirstDescendant();return g(s)&&s.select(),!0}(e,o.peek()),_e),e.registerCommand(Se,(t,r)=>e===r&&function(e,t){const{nodes:o,selection:r}=e;if(!o.some(e=>Bn(e)||a(e).some(e=>Bn(e.node))))return!1;const l=Pt(r),s=w(r);if(!(s&&null!==n(r.anchor.getNode(),e=>Ge(e))&&null!==n(r.focus.getNode(),e=>Ge(e))||l))return!1;if(1===o.length&&Bn(o[0]))return function(e,t){const o=t.getStartEndPoints(),r=Pt(t);if(null===o)return!1;const[l,s]=o,[i,c,a]=Mt(l),u=n(s.getNode(),e=>Ge(e));if(!(Ge(i)&&Ge(u)&&ot(c)&&Bn(a)))return!1;const[h,d,f]=Et(a,i,u),[m]=kt(e,null,null),C=h.length,_=C>0?h[0].length:0;let S=d.startRow,b=d.startColumn,w=m.length,y=w>0?m[0].length:0;if(r){const e=$t(h,d,f),t=e.maxRow-e.minRow+1,n=e.maxColumn-e.minColumn+1;S=e.minRow,b=e.minColumn,w=Math.min(w,t),y=Math.min(y,n)}let N=!1;const v=Math.min(C,S+w)-1,x=Math.min(_,b+y)-1,T=new Set;for(let e=S;e<=v;e++)for(let t=b;t<=x;t++){const n=h[e][t];T.has(n.cell.getKey())||(1===n.cell.__rowSpan&&1===n.cell.__colSpan||(Kt(n.cell),T.add(n.cell.getKey()),N=!0))}let[F]=kt(a.getWritable(),null,null);const R=w-C+S;for(let e=0;e<R;e++){pt(F[C-1][0].cell)}const O=y-_+b;for(let e=0;e<O;e++){bt(F[0][_-1].cell,!0,!1)}[F]=kt(a.getWritable(),null,null);for(let e=S;e<S+w;e++)for(let t=b;t<b+y;t++){const n=e-S,o=t-b,r=m[n][o];if(r.startRow!==n||r.startColumn!==o)continue;const l=r.cell;if(1!==l.__rowSpan||1!==l.__colSpan){const n=[],o=Math.min(e+l.__rowSpan,S+w)-1,r=Math.min(t+l.__colSpan,b+y)-1;for(let l=e;l<=o;l++)for(let e=t;e<=r;e++){const t=F[l][e];n.push(t.cell)}Rt(n),N=!0}const{cell:s}=F[e][t],i=l.getBackgroundColor();null!=i&&s.setBackgroundColor(i);const c=s.getChildren();l.getChildren().forEach(e=>{if(g(e)){p().append(e),s.append(e)}else s.append(e)}),c.forEach(e=>e.remove())}if(r&&N){const[e]=kt(a.getWritable(),null,null);e[d.startRow][d.startColumn].cell.selectEnd()}return!0}(o[0],r);if(s&&t.peek()&&!function(e){if(Pt(e)&&!e.focus.getNode().is(e.anchor.getNode()))return!0;if(w(e)&&Ge(e.anchor.getNode())&&!e.anchor.getNode().is(e.focus.getNode()))return!0;return!1}(r))return!1;return!0}(t,o),_e),e.registerCommand(be,Jn,we),e.registerCommand(ye,Un,_e),e.registerNodeTransform(Wn,In),e.registerNodeTransform(et,Dn),e.registerNodeTransform(Ye,Pn))}const jn=ve({build:(e,t,n)=>$e(t),config:Te({hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasTabHandler:!0}),name:"@lexical/table/Table",nodes:()=>[Wn,et,Ye],register(e,t,n){const o=n.getOutput();return i(Me(()=>{const t=o.hasHorizontalScroll.value;Mn(e)!==t&&($n(e,t),e.update(xe))}),qn(e,o),Me(()=>Yn(e,o.hasTabHandler.value)),Me(()=>o.hasCellMerge.value?void 0:Xn(e)),Me(()=>o.hasCellBackgroundColor.value?void 0:e.registerNodeTransform(Ye,e=>{null!==e.getBackgroundColor()&&e.setBackgroundColor(null)})))}});function Vn(e){const t=[];let n=null;const o=()=>{if(null!==n){const e=n.getFirstChild();m(e)&&1===n.getChildrenSize()&&e.remove()}};for(const r of e)f(r)||g(r)||m(r)?null!==n?n.append(r):(n=p().append(r),t.push(n)):(o(),t.push(r),n=null);return o(),0===t.length&&t.push(p()),t}const Gn={$accepts:ot,$packageRun:e=>e.every(Ge)?[nt().splice(0,0,e)]:[],name:"TableSchema"},Qn={$accepts:Ge,name:"TableRowSchema"},Zn=[Be({$import:(e,n)=>{const o=Hn();n.hasAttribute("data-lexical-row-striping")&&o.setRowStriping(!0),n.hasAttribute("data-lexical-frozen-column")&&o.setFrozenColumns(1),n.hasAttribute("data-lexical-frozen-row")&&o.setFrozenRows(1);const r=n.querySelector(":scope > colgroup");if(r){let e=[];for(const t of r.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!Je.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&o.setColWidths(e)}return[o.splice(0,0,t(e.$importChildren(n),ot))]},match:Pe.tag("table"),name:"@lexical/table/table"}),Be({$import:(e,n)=>[nt(Je.test(n.style.height)?parseFloat(n.style.height):void 0).splice(0,0,t(e.$importChildren(n),Ge))],match:Pe.tag("tr"),name:"@lexical/table/tr"}),Be({$import:(e,t)=>{const n="TH"===t.nodeName,o=Je.test(t.style.width)?parseFloat(t.style.width):void 0;let r=Xe.NO_STATUS;if(n){const e=t.getAttribute("scope");if("col"===e)r=Xe.COLUMN;else if("row"===e)r=Xe.ROW;else{const e=t.parentElement,n=Re(e)&&(e.parentElement&&"THEAD"===e.parentElement.nodeName||0===e.rowIndex),o=0===t.cellIndex;n&&(r|=Xe.ROW),o&&(r|=Xe.COLUMN),r===Xe.NO_STATUS&&(r=Xe.ROW)}}const l=Ve(r,t.colSpan,o);l.__rowSpan=t.rowSpan;const s=t.style.backgroundColor;""!==s&&(l.__backgroundColor=s);const i=t.style.verticalAlign;(function(e){return"middle"===e||"bottom"===e})(i)&&(l.__verticalAlign=i);const c=e.get(De),a=c|function(e){let t=0;const n=e.fontWeight;"700"!==n&&"bold"!==n||(t|=Oe),"italic"===e.fontStyle&&(t|=Ae);const o=(e.textDecoration||"").split(" ");return o.includes("underline")&&(t|=Ke),o.includes("line-through")&&(t|=Ee),t}(t.style),u=e.get(Ie),h=t.style.color,d=h?{...u,color:h}:u,f=[];return a!==c&&f.push(Ue(De,a)),d!==u&&f.push(Ue(Ie,d)),[l.splice(0,0,Vn(e.$importChildren(t,{context:f})))]},match:Pe.tag("td","th"),name:"@lexical/table/cell"})],eo=ve({dependencies:[Le,jn,Fe(He,{rules:Zn})],name:"@lexical/table/Import"});export{Et as $computeTableMap,kt as $computeTableMapSkipCellCheck,Ve as $createTableCellNode,Hn as $createTableNode,rt as $createTableNodeWithDimensions,nt as $createTableRowNode,Dt as $createTableSelection,It as $createTableSelectionFrom,wt as $deleteTableColumn,vt as $deleteTableColumnAtSelection,xt as $deleteTableColumn__EXPERIMENTAL,yt as $deleteTableRowAtSelection,Nt as $deleteTableRow__EXPERIMENTAL,yn as $findCellNode,Nn as $findTableNode,zn as $getElementForTableNode,Mt as $getNodeTriplet,Jt as $getTableAndElementByKey,lt as $getTableCellNodeFromLexicalNode,Lt as $getTableCellNodeRect,at as $getTableColumnIndexFromTableCellNode,it as $getTableNodeFromLexicalNodeOrThrow,ct as $getTableRowIndexFromTableCellNode,st as $getTableRowNodeFromTableCellNodeOrThrow,Ct as $insertTableColumn,_t as $insertTableColumnAtSelection,St as $insertTableColumn__EXPERIMENTAL,dt as $insertTableRow,gt as $insertTableRowAtSelection,mt as $insertTableRow__EXPERIMENTAL,Mn as $isScrollableTablesActive,Wt as $isSimpleTable,Ge as $isTableCellNode,Bn as $isTableNode,ot as $isTableRowNode,Pt as $isTableSelection,Rt as $mergeCells,zt as $moveTableColumn,ht as $removeTableRowAtIndex,At as $unmergeCell,Qe as INSERT_TABLE_COMMAND,Xe as TableCellHeaderStates,Ye as TableCellNode,jn as TableExtension,eo as TableImportExtension,Zn as TableImportRules,Wn as TableNode,Yt as TableObserver,et as TableRowNode,Qn as TableRowSchema,Gn as TableSchema,on as applyTableHandlers,cn as getDOMCellFromTarget,Vt as getTableElement,sn as getTableObserverFromTableElement,Xn as registerTableCellUnmergeTransform,qn as registerTablePlugin,Yn as registerTableSelectionObserver,$n as setScrollableTablesActive};
++import{addClassNamesToElement as e,$descendantsMatching as t,$findMatchingParent as n,removeClassNamesFromElement as o,objectKlassEquals as r,isHTMLElement as l,$insertFirst as s,mergeRegister as i,$insertNodeToNearestRoot as c,$dfs as a,$unwrapAndFilterDescendants as u}from"@lexical/utils";import{ElementNode as h,isHTMLElement as d,$isInlineElementOrDecoratorNode as f,$isTextNode as g,$isLineBreakNode as m,$createParagraphNode as p,$applyNodeReplacement as C,createCommand as _,$createTextNode as S,$getSelection as b,$isRangeSelection as w,$isParagraphNode as y,$createPoint as N,$getNodeByKey as v,$isElementNode as x,$normalizeSelection__EXPERIMENTAL as T,isCurrentlyReadOnlyMode as F,TEXT_TYPE_TO_FORMAT as R,$getEditor as O,$setSelection as A,SELECTION_CHANGE_COMMAND as K,getDOMSelection as E,$createRangeSelection as k,$isRootNode as M,INSERT_PARAGRAPH_COMMAND as $,KEY_ARROW_DOWN_COMMAND as W,KEY_ARROW_UP_COMMAND as z,KEY_ARROW_LEFT_COMMAND as L,KEY_ARROW_RIGHT_COMMAND as H,COMMAND_PRIORITY_HIGH as B,KEY_ESCAPE_COMMAND as P,DELETE_WORD_COMMAND as D,DELETE_LINE_COMMAND as I,DELETE_CHARACTER_COMMAND as U,KEY_BACKSPACE_COMMAND as J,KEY_DELETE_COMMAND as X,CUT_COMMAND as Y,FORMAT_TEXT_COMMAND as q,FORMAT_ELEMENT_COMMAND as j,CONTROLLED_TEXT_INSERTION_COMMAND as V,KEY_TAB_COMMAND as G,FOCUS_COMMAND as Q,$getNearestNodeFromDOMNode as Z,isDOMNode as ee,$isRootOrShadowRoot as te,$getPreviousSelection as ne,$getNodeByKeyOrThrow as oe,$caretFromPoint as re,$isExtendableTextPointCaret as le,$extendCaretToRange as se,$isSiblingCaret as ie,$getSiblingCaret as ce,$setPointFromCaret as ae,$normalizeCaret as ue,$createRangeSelectionFromDom as he,$isChildCaret as de,$getChildCaret as fe,$getAdjacentChildCaret as ge,IS_FIREFOX as me,setDOMStyleFromCSS as pe,setDOMUnmanaged as Ce,COMMAND_PRIORITY_EDITOR as _e,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND as Se,SELECT_ALL_COMMAND as be,COMMAND_PRIORITY_LOW as we,CLICK_COMMAND as ye,$getRoot as Ne,defineExtension as ve,$fullReconcile as xe,safeCast as Te,configExtension as Fe,isHTMLTableRowElement as Re,IS_BOLD as Oe,IS_ITALIC as Ae,IS_UNDERLINE as Ke,IS_STRIKETHROUGH as Ee}from"lexical";import{signal as ke,effect as Me,namedSignals as $e}from"@lexical/extension";import{copyToClipboard as We,$getClipboardDataFromSelection as ze}from"@lexical/clipboard";import{CoreImportExtension as Le,DOMImportExtension as He,defineImportRule as Be,sel as Pe,ImportTextFormat as De,ImportTextStyle as Ie,contextValue as Ue}from"@lexical/html";const Je=/^(\d+(?:\.\d+)?)px$/,Xe={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1};class Ye extends h{__colSpan;__rowSpan;__headerState;__width;__backgroundColor;__verticalAlign;static getType(){return"tablecell"}static clone(e){return new Ye(e.__headerState,e.__colSpan,e.__width,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__rowSpan=e.__rowSpan,this.__backgroundColor=e.__backgroundColor,this.__verticalAlign=e.__verticalAlign,this.__colSpan=e.__colSpan,this.__headerState=e.__headerState,this.__width=e.__width}static importDOM(){return{td:e=>({conversion:je,priority:0}),th:e=>({conversion:je,priority:0})}}static importJSON(e){return Ve().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeaderStyles(e.headerState).setColSpan(e.colSpan||1).setRowSpan(e.rowSpan||1).setWidth(e.width||void 0).setBackgroundColor(e.backgroundColor||null).setVerticalAlign(e.verticalAlign||void 0)}constructor(e=Xe.NO_STATUS,t=1,n,o){super(o),this.__colSpan=t,this.__rowSpan=1,this.__headerState=e,this.__width=n,this.__backgroundColor=null,this.__verticalAlign=void 0}createDOM(t){const n=document.createElement(this.getTag());return this.__width&&(n.style.width=`${this.__width}px`),this.__colSpan>1&&(n.colSpan=this.__colSpan),this.__rowSpan>1&&(n.rowSpan=this.__rowSpan),null!==this.__backgroundColor&&(n.style.backgroundColor=this.__backgroundColor),qe(this.__verticalAlign)&&(n.style.verticalAlign=this.__verticalAlign),e(n,t.theme.tableCell,this.hasHeader()&&t.theme.tableCellHeader),n}exportDOM(e){const t=super.exportDOM(e);if(d(t.element)){const e=t.element;e.setAttribute("data-temporary-table-cell-lexical-key",this.getKey()),e.style.border="1px solid black",this.__colSpan>1&&(e.colSpan=this.__colSpan),this.__rowSpan>1&&(e.rowSpan=this.__rowSpan),e.style.width=`${this.getWidth()||75}px`,e.style.verticalAlign=this.getVerticalAlign()||"top",e.style.textAlign="start",null===this.__backgroundColor&&this.hasHeader()&&(e.style.backgroundColor="#f2f3f5")}return t}exportJSON(){return{...super.exportJSON(),...qe(this.__verticalAlign)&&{verticalAlign:this.__verticalAlign},backgroundColor:this.getBackgroundColor(),colSpan:this.__colSpan,headerState:this.__headerState,rowSpan:this.__rowSpan,width:this.getWidth()}}getColSpan(){return this.getLatest().__colSpan}setColSpan(e){const t=this.getWritable();return t.__colSpan=e,t}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(e){const t=this.getWritable();return t.__rowSpan=e,t}getTag(){return this.hasHeader()?"th":"td"}setHeaderStyles(e,t=Xe.BOTH){const n=this.getWritable();return n.__headerState=e&t|n.__headerState&~t,n}getHeaderStyles(){return this.getLatest().__headerState}setWidth(e){const t=this.getWritable();return t.__width=e,t}getWidth(){return this.getLatest().__width}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(e){const t=this.getWritable();return t.__backgroundColor=e,t}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(e){const t=this.getWritable();return t.__verticalAlign=e||void 0,t}toggleHeaderStyle(e){const t=this.getWritable();return(t.__headerState&e)===e?t.__headerState-=e:t.__headerState+=e,t}hasHeaderState(e){return(this.getHeaderStyles()&e)===e}hasHeader(){return this.getLatest().__headerState!==Xe.NO_STATUS}updateDOM(e){return e.__headerState!==this.__headerState||e.__width!==this.__width||e.__colSpan!==this.__colSpan||e.__rowSpan!==this.__rowSpan||e.__backgroundColor!==this.__backgroundColor||e.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}}function qe(e){return"middle"===e||"bottom"===e}function je(e){const t=e,n=e.nodeName.toLowerCase();let o;Je.test(t.style.width)&&(o=parseFloat(t.style.width));let r=Xe.NO_STATUS;if("th"===n){const e=t.getAttribute("scope");if("col"===e)r=Xe.COLUMN;else if("row"===e)r=Xe.ROW;else{const e=t.parentElement,n=d(e)&&"tr"===e.nodeName.toLowerCase()&&d(e.parentElement)&&("thead"===e.parentElement.nodeName.toLowerCase()||0===e.rowIndex),o=0===t.cellIndex;n&&(r|=Xe.ROW),o&&(r|=Xe.COLUMN),r===Xe.NO_STATUS&&(r=Xe.ROW)}}const l=Ve(r,t.colSpan,o);l.__rowSpan=t.rowSpan;const s=t.style.backgroundColor;""!==s&&(l.__backgroundColor=s);const i=t.style.verticalAlign;qe(i)&&(l.__verticalAlign=i);const c=t.style,a=(c&&c.textDecoration||"").split(" "),u="700"===c.fontWeight||"bold"===c.fontWeight,h=a.includes("line-through"),C="italic"===c.fontStyle,_=a.includes("underline"),S=c.color;return{after:e=>{const t=[];let n=null;const o=()=>{if(n){const e=n.getFirstChild();m(e)&&1===n.getChildrenSize()&&e.remove()}};for(const r of e)if(f(r)||g(r)||m(r)){if(g(r)&&(u&&r.toggleFormat("bold"),h&&r.toggleFormat("strikethrough"),C&&r.toggleFormat("italic"),_&&r.toggleFormat("underline"),S)){const e=r.getStyle();e.includes("color:")||r.setStyle(e+`color: ${S};`)}n?n.append(r):(n=p().append(r),t.push(n))}else t.push(r),o(),n=null;return o(),0===t.length&&t.push(p()),t},node:l}}function Ve(e=Xe.NO_STATUS,t=1,n){return C(new Ye(e,t,n))}function Ge(e){return e instanceof Ye}const Qe=_("INSERT_TABLE_COMMAND");function Ze(e,...t){const n=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(const e of t)o.append("v",e);throw n.search=o.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}class et extends h{__height;static getType(){return"tablerow"}static clone(e){return new et(e.__height,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__height=e.__height}static importDOM(){return{tr:e=>({conversion:tt,priority:0})}}static importJSON(e){return nt().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setHeight(e.height)}constructor(e,t){super(t),this.__height=e}exportJSON(){const e=this.getHeight();return{...super.exportJSON(),...void 0===e?void 0:{height:e}}}createDOM(t){const n=document.createElement("tr");return this.__height&&(n.style.height=`${this.__height}px`),e(n,t.theme.tableRow),n}extractWithChild(e,t,n){return"html"===n}isShadowRoot(){return!0}setHeight(e){const t=this.getWritable();return t.__height=e,t}getHeight(){return this.getLatest().__height}updateDOM(e){return e.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}}function tt(e){const n=e;let o;return Je.test(n.style.height)&&(o=parseFloat(n.style.height)),{after:e=>t(e,Ge),node:nt(o)}}function nt(e){return C(new et(e))}function ot(e){return e instanceof et}function rt(e,t,n=!0){const o=Hn();for(let r=0;r<e;r++){const e=nt();for(let o=0;o<t;o++){let t=Xe.NO_STATUS;"object"==typeof n?(0===r&&n.rows&&(t|=Xe.ROW),0===o&&n.columns&&(t|=Xe.COLUMN)):n&&(0===r&&(t|=Xe.ROW),0===o&&(t|=Xe.COLUMN));const l=Ve(t),s=p();s.append(S()),l.append(s),e.append(l)}o.append(e)}return o}function lt(e){const t=n(e,e=>Ge(e));return Ge(t)?t:null}function st(e){const t=n(e,e=>ot(e));if(ot(t))return t;throw new Error("Expected table cell to be inside of table row.")}function it(e){const t=n(e,e=>Bn(e));if(Bn(t))return t;throw new Error("Expected table cell to be inside of table.")}function ct(e){const t=st(e);return it(t).getChildren().findIndex(e=>e.is(t))}function at(e){return st(e).getChildren().findIndex(t=>t.is(e))}function ut(e,t){const n=it(e),{x:o,y:r}=n.getCordsFromCellNode(e,t);return{above:n.getCellNodeFromCords(o,r-1,t),below:n.getCellNodeFromCords(o,r+1,t),left:n.getCellNodeFromCords(o-1,r,t),right:n.getCellNodeFromCords(o+1,r,t)}}function ht(e,t){const n=e.getChildren();if(t>=n.length||t<0)throw new Error("Expected table cell to be inside of table row.");return n[t].remove(),e}function dt(e,t,n=!0,o,r){const l=e.getChildren();if(t>=l.length||t<0)throw new Error("Table row target index out of range");const s=l[t];if(!ot(s))throw new Error("Row before insertion index does not exist.");for(let e=0;e<o;e++){const e=s.getChildren(),t=e.length,o=nt();for(let n=0;n<t;n++){const t=e[n];Ge(t)||Ze(12);const{above:l,below:s}=ut(t,r);let i=Xe.NO_STATUS;const c=l&&l.getWidth()||s&&s.getWidth()||void 0;(l&&l.hasHeaderState(Xe.COLUMN)||s&&s.hasHeaderState(Xe.COLUMN))&&(i|=Xe.COLUMN);const a=Ve(i,1,c);a.append(p()),o.append(a)}n?s.insertAfter(o):s.insertBefore(o)}return e}const ft=(e,t)=>e===Xe.BOTH||e===t?t:Xe.NO_STATUS;function gt(e=!0){const t=b();w(t)||Pt(t)||Ze(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[r]=Mt(n),[l,,s]=Mt(o),[,i,c]=Et(s,l,r),{startRow:a}=c,{startRow:u}=i;return e?pt(a+r.__rowSpan>u+l.__rowSpan?r:l,!0):pt(u<a?l:r,!1)}const mt=gt;function pt(e,t=!0){const[,,n]=Mt(e),[o,r]=Et(n,e,e),l=o[0].length,{startRow:s}=r;let i=null;if(t){const t=s+e.__rowSpan-1,r=o[t],c=nt();for(let e=0;e<l;e++){const{cell:n,startRow:o}=r[e];if(o+n.__rowSpan-1<=t){const t=r[e].cell.__headerState,n=ft(t,Xe.COLUMN);c.append(Ve(n).append(p()))}else n.setRowSpan(n.__rowSpan+1)}const a=n.getChildAtIndex(t);ot(a)||Ze(256),a.insertAfter(c),i=c}else{const e=s,t=o[e],r=nt();for(let n=0;n<l;n++){const{cell:o,startRow:l}=t[n];if(l===e){const e=t[n].cell.__headerState,o=ft(e,Xe.COLUMN);r.append(Ve(o).append(p()))}else o.setRowSpan(o.__rowSpan+1)}const c=n.getChildAtIndex(e);ot(c)||Ze(257),c.insertBefore(r),i=r}return i}function Ct(e,t,n=!0,o,r){const l=e.getChildren(),s=[];for(let e=0;e<l.length;e++){const n=l[e];if(ot(n))for(let e=0;e<o;e++){const e=n.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");const o=e[t];Ge(o)||Ze(12);const{left:l,right:i}=ut(o,r);let c=Xe.NO_STATUS;(l&&l.hasHeaderState(Xe.ROW)||i&&i.hasHeaderState(Xe.ROW))&&(c|=Xe.ROW);const a=Ve(c);a.append(p()),s.push({newTableCell:a,targetCell:o})}}return s.forEach(({newTableCell:e,targetCell:t})=>{n?t.insertAfter(e):t.insertBefore(e)}),e}function _t(e=!0){const t=b();w(t)||Pt(t)||Ze(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[r]=Mt(n),[l,,s]=Mt(o),[,i,c]=Et(s,l,r),{startColumn:a}=c,{startColumn:u}=i;return e?bt(a+r.__colSpan>u+l.__colSpan?r:l,!0):bt(u<a?l:r,!1)}const St=_t;function bt(e,t=!0,n=!0){const[,,o]=Mt(e),[r,l]=Et(o,e,e),s=r.length,{startColumn:i}=l,c=t?i+e.__colSpan-1:i-1,a=o.getFirstChild();ot(a)||Ze(120);let u=null;function h(e=Xe.NO_STATUS){const t=Ve(e).append(p());return null===u&&(u=t),t}let d=a;e:for(let e=0;e<s;e++){if(0!==e){const e=d.getNextSibling();ot(e)||Ze(121),d=e}const t=r[e],n=t[c<0?0:c].cell.__headerState,o=ft(n,Xe.ROW);if(c<0){Ft(d,h(o));continue}const{cell:l,startColumn:s,startRow:i}=t[c];if(s+l.__colSpan-1<=c){let n=l,r=i,s=c;for(;r!==e&&n.__rowSpan>1;){if(s-=l.__colSpan,!(s>=0)){d.append(h(o));continue e}{const{cell:e,startRow:o}=t[s];n=e,r=o}}n.insertAfter(h(o))}else l.setColSpan(l.__colSpan+1)}null!==u&&n&&Tt(u);const f=o.getColWidths();if(f){const e=[...f],t=c<0?0:c,n=e[t];e.splice(t,0,n),o.setColWidths(e)}return u}function wt(e,t){const n=e.getChildren();for(let e=0;e<n.length;e++){const o=n[e];if(ot(o)){const e=o.getChildren();if(t>=e.length||t<0)throw new Error("Table column target index out of range");e[t].remove()}}return e}function yt(){const e=b();w(e)||Pt(e)||Ze(188);const[t,n]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[o,,r]=Mt(t),[l]=Mt(n),[s,i,c]=Et(r,o,l),{startRow:a}=i,{startRow:u}=c,h=u+l.__rowSpan-1;if(s.length===h-a+1)return void r.remove();const d=s[0].length,f=s[h+1],g=r.getChildAtIndex(h+1);for(let e=h;e>=a;e--){for(let t=d-1;t>=0;t--){const{cell:n,startRow:o,startColumn:r}=s[e][t];if(r===t){if(o<a||o+n.__rowSpan-1>h){const e=Math.max(o,a),t=Math.min(n.__rowSpan+o-1,h),r=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-r)}if(o>=a&&o+n.__rowSpan-1>h&&e===h){null===g&&Ze(122);let o=null;for(let n=0;n<t;n++){const t=f[n],r=t.cell;t.startRow===e+1&&(o=r),r.__colSpan>1&&(n+=r.__colSpan-1)}null===o?Ft(g,n):o.insertAfter(n)}}}const t=r.getChildAtIndex(e);ot(t)||Ze(206,String(e)),t.remove()}if(void 0!==f){const{cell:e}=f[0];Tt(e)}else{const e=s[a-1],{cell:t}=e[0];Tt(t)}}const Nt=yt;function vt(){const e=b();w(e)||Pt(e)||Ze(188);const t=e.anchor.getNode(),n=e.focus.getNode(),[o,,r]=Mt(t),[l]=Mt(n),[s,i,c]=Et(r,o,l),{startColumn:a}=i,{startRow:u,startColumn:h}=c,d=Math.min(a,h),f=Math.max(a+o.__colSpan-1,h+l.__colSpan-1),g=f-d+1;if(s[0].length===f-d+1)return r.selectPrevious(),void r.remove();const m=s.length;for(let e=0;e<m;e++)for(let t=d;t<=f;t++){const{cell:n,startColumn:o}=s[e][t];if(o<d){if(t===d){const e=d-o;n.setColSpan(n.__colSpan-Math.min(g,n.__colSpan-e))}}else if(o+n.__colSpan-1>f){if(t===f){const e=f-o+1;n.setColSpan(n.__colSpan-e)}}else n.remove()}const p=s[u],C=a>h?p[a+o.__colSpan]:p[h+l.__colSpan];if(void 0!==C){const{cell:e}=C;Tt(e)}else{const e=h<a?p[h-1]:p[a-1],{cell:t}=e;Tt(t)}const _=r.getColWidths();if(_){const e=[..._];e.splice(d,g),r.setColWidths(e)}}const xt=vt;function Tt(e){const t=e.getFirstDescendant();null==t?e.selectStart():t.getParentOrThrow().selectStart()}function Ft(e,t){const n=e.getFirstChild();null!==n?n.insertBefore(t):e.append(t)}function Rt(e){if(0===e.length)return null;const t=it(e[0]),[n]=kt(t,null,null);let o=1/0,r=-1/0,l=1/0,s=-1/0;const i=new Set;for(const t of n)for(const n of t){if(!n||!n.cell)continue;const t=n.cell.getKey();if(!i.has(t)&&e.some(e=>e.is(n.cell))){i.add(t);const e=n.startRow,c=n.startColumn,a=n.cell.__rowSpan||1,u=n.cell.__colSpan||1;o=Math.min(o,e),r=Math.max(r,e+a-1),l=Math.min(l,c),s=Math.max(s,c+u-1)}}if(o===1/0||l===1/0)return null;const c=r-o+1,a=s-l+1,u=n[o][l];if(!u.cell)return null;const h=u.cell;h.setColSpan(a),h.setRowSpan(c);const d=new Set([h.getKey()]);for(let e=o;e<=r;e++)for(let t=l;t<=s;t++){const o=n[e][t];if(!o.cell)continue;const r=o.cell,l=r.getKey();if(!d.has(l)){d.add(l);Ot(r)||h.append(...r.getChildren()),r.remove()}}return 0===h.getChildrenSize()&&h.append(p()),h}function Ot(e){if(1!==e.getChildrenSize())return!1;const t=e.getFirstChildOrThrow();return!(!y(t)||!t.isEmpty())}function At(){const e=b();w(e)||Pt(e)||Ze(188);const t=e.anchor.getNode(),o=n(t,Ge);return Ge(o)||Ze(148),Kt(o)}function Kt(e){const[t,n,o]=Mt(e),r=t.__colSpan,l=t.__rowSpan;if(1===r&&1===l)return;const[s,i]=Et(o,t,t),{startColumn:c,startRow:a}=i,u=t.__headerState&Xe.COLUMN,h=Array.from({length:r},(e,t)=>{let n=u;for(let e=0;0!==n&&e<s.length;e++)n&=s[e][t+c].cell.__headerState;return n}),d=t.__headerState&Xe.ROW,f=Array.from({length:l},(e,t)=>{let n=d;for(let e=0;0!==n&&e<s[0].length;e++)n&=s[t+a][e].cell.__headerState;return n});if(r>1){for(let e=1;e<r;e++)t.insertAfter(Ve(h[e]|f[0]).append(p()));t.setColSpan(1)}if(l>1){let e;for(let t=1;t<l;t++){const o=a+t,l=s[o];e=(e||n).getNextSibling(),ot(e)||Ze(125);let i=null;for(let e=0;e<c;e++){const t=l[e],n=t.cell;t.startRow===o&&(i=n),n.__colSpan>1&&(e+=n.__colSpan-1)}if(null===i)for(let n=r-1;n>=0;n--)Ft(e,Ve(h[n]|f[t]).append(p()));else for(let e=r-1;e>=0;e--)i.insertAfter(Ve(h[e]|f[t]).append(p()))}t.setRowSpan(1)}}function Et(e,t,n){const[o,r,l]=kt(e,t,n);return null===r&&Ze(207),null===l&&Ze(208),[o,r,l]}function kt(e,t,n){const o=[];let r=null,l=null;function s(e){let t=o[e];return void 0===t&&(o[e]=t=[]),t}const i=e.getChildren();for(let e=0;e<i.length;e++){const o=i[e];ot(o)||Ze(209);const c=s(e);for(let a=o.getFirstChild(),u=0;null!=a;a=a.getNextSibling()){for(Ge(a)||Ze(147);void 0!==c[u];)u++;const o={cell:a,startColumn:u,startRow:e},{__rowSpan:h,__colSpan:d}=a;for(let t=0;t<h&&!(e+t>=i.length);t++){const n=s(e+t);for(let e=0;e<d;e++)n[u+e]=o}null!==t&&null===r&&t.is(a)&&(r=o),null!==n&&null===l&&n.is(a)&&(l=o)}}return[o,r,l]}function Mt(e){let t;if(e instanceof Ye)t=e;else if("__type"in e){const o=n(e,Ge);Ge(o)||Ze(148),t=o}else{const o=n(e.getNode(),Ge);Ge(o)||Ze(148),t=o}const o=t.getParent();ot(o)||Ze(149);const r=o.getParent();return Bn(r)||Ze(210),[t,o,r]}function $t(e,t,n){let o,r=Math.min(t.startColumn,n.startColumn),l=Math.min(t.startRow,n.startRow),s=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),i=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{o=!1;for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const c=e[t][n];if(!c)continue;const a=c.startColumn+c.cell.__colSpan-1,u=c.startRow+c.cell.__rowSpan-1,h=c.startColumn<=s&&a>=r,d=c.startRow<=i&&u>=l;if(h&&d){const e=Math.min(r,c.startColumn),t=Math.max(s,a),n=Math.min(l,c.startRow),h=Math.max(i,u);e===r&&t===s&&n===l&&h===i||(r=e,s=t,l=n,i=h,o=!0)}}}while(o);return{maxColumn:s,maxRow:i,minColumn:r,minRow:l}}function Wt(e){const t=e.getChildren();let n=null;for(const e of t){if(!ot(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!Ge(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function zt(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!Wt(e))return;e.getChildren().filter(ot).forEach(e=>{const o=e.getChildren(),[r]=o.splice(t,1);o.splice(n,0,r),e.splice(0,o.length,o)});const r=e.getColWidths();if(r&&r.length===o){const o=[...r],[l]=o.splice(t,1);o.splice(n,0,l),e.setColWidths(o)}}function Lt(e){const[t,,n]=Mt(e),o=n.getChildren(),r=o.length,l=o[0].getChildren().length,s=new Array(r);for(let e=0;e<r;e++)s[e]=new Array(l);for(let e=0;e<r;e++){const n=o[e].getChildren();let r=0;for(let o=0;o<n.length;o++){for(;s[e][r];)r++;const l=n[o],i=l.__rowSpan||1,c=l.__colSpan||1;for(let t=0;t<i;t++)for(let n=0;n<c;n++)s[e+t][r+n]=l;if(t===l)return{colSpan:c,columnIndex:r,rowIndex:e,rowSpan:i};r+=c}}return null}function Ht(e){const[[t,o,r,l],[s,i,c,a]]=["anchor","focus"].map(t=>{const o=e[t].getNode(),r=n(o,Ge);Ge(r)||Ze(238,t,o.getKey(),o.getType());const l=r.getParent();ot(l)||Ze(239,t);const s=l.getParent();return Bn(s)||Ze(240,t),[o,r,l,s]});return l.is(a)||Ze(241),{anchorCell:o,anchorNode:t,anchorRow:r,anchorTable:l,focusCell:i,focusNode:s,focusRow:c,focusTable:a}}class Bt{tableKey;anchor;focus;_cachedNodes;dirty;constructor(e,t,n){this.anchor=t,this.focus=n,t._selection=this,n._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=e}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if("root"===this.tableKey||"root"===this.anchor.key||"element"!==this.anchor.type||"root"===this.focus.key||"element"!==this.focus.type)return!1;const e=v(this.tableKey),t=v(this.anchor.key),n=v(this.focus.key);return null!==e&&null!==t&&null!==n}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return Pt(e)&&this.tableKey===e.tableKey&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)}set(e,t,n){this.dirty=this.dirty||e!==this.tableKey||t!==this.anchor.key||n!==this.focus.key,this.tableKey=e,this.anchor.key=t,this.focus.key=n,this._cachedNodes=null}clone(){return new Bt(this.tableKey,N(this.anchor.key,this.anchor.offset,this.anchor.type),N(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(e){}insertText(){}hasFormat(e){let t=0;this.getNodes().filter(Ge).forEach(e=>{const n=e.getFirstChild();y(n)&&(t|=n.getTextFormat())});const n=R[e];return 0!==(t&n)}insertNodes(e){const t=this.focus.getNode();x(t)||Ze(151);T(t.select(0,t.getChildrenSize())).insertNodes(e)}getShape(){const{anchorCell:e,focusCell:t}=Ht(this),n=Lt(e);null===n&&Ze(153);const o=Lt(t);null===o&&Ze(155);const r=Math.min(n.columnIndex,o.columnIndex),l=Math.max(n.columnIndex+n.colSpan-1,o.columnIndex+o.colSpan-1),s=Math.min(n.rowIndex,o.rowIndex),i=Math.max(n.rowIndex+n.rowSpan-1,o.rowIndex+o.rowSpan-1);return{fromX:Math.min(r,l),fromY:Math.min(s,i),toX:Math.max(r,l),toY:Math.max(s,i)}}getNodes(){if(!this.isValid())return[];const e=this._cachedNodes;if(null!==e)return e;const{anchorTable:t,anchorCell:n,focusCell:o}=Ht(this),r=o.getParents()[1];if(r!==t){if(t.isParentOf(o)){const e=r.getParent();null==e&&Ze(159),this.set(this.tableKey,o.getKey(),e.getKey())}else{const e=t.getParent();null==e&&Ze(158),this.set(this.tableKey,e.getKey(),o.getKey())}return this.getNodes()}const[l,s,i]=Et(t,n,o),{minColumn:c,maxColumn:a,minRow:u,maxRow:h}=$t(l,s,i),d=new Map([[t.getKey(),t]]);let f=null;for(let e=u;e<=h;e++)for(let t=c;t<=a;t++){const{cell:n}=l[e][t],o=n.getParent();ot(o)||Ze(160),o!==f&&(d.set(o.getKey(),o),f=o),d.has(n.getKey())||Ut(n,e=>{d.set(e.getKey(),e)})}const g=Array.from(d.values());return F()||(this._cachedNodes=g),g}getTextContent(){const e=this.getNodes().filter(e=>Ge(e));let t="";for(let n=0;n<e.length;n++){const o=e[n],r=o.__parent,l=(e[n+1]||{}).__parent;t+=o.getTextContent()+(l!==r?"\n":"\t")}return t}}function Pt(e){return e instanceof Bt}function Dt(){const e=N("root",0,"element"),t=N("root",0,"element");return new Bt("root",e,t)}function It(e,t,n){e.getKey(),t.getKey(),n.getKey();const o=b(),r=Pt(o)?o.clone():Dt();return r.set(e.getKey(),t.getKey(),n.getKey()),r}function Ut(e,t){const n=[[e]];for(let e=n.at(-1);void 0!==e&&n.length>0;e=n.at(-1)){const o=e.pop();void 0===o?n.pop():!1!==t(o)&&x(o)&&n.push(o.getChildren())}}function Jt(e,t=O()){const n=v(e);Bn(n)||Ze(231,e);const o=Vt(n,t.getElementByKey(e));return null===o&&Ze(232,e),{tableElement:o,tableNode:n}}class Xt{observers;nextFocus;shouldCheckSelectionForTable;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null}setNextFocus(e){this.nextFocus=e}getAndClearNextFocus(){const{nextFocus:e}=this;return null!==e&&(this.nextFocus=null),e}setShouldCheckSelectionForTable(e){this.shouldCheckSelectionForTable=e}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:e}=this;return e?(this.shouldCheckSelectionForTable=null,e):null}}class Yt{focusX;focusY;listenersToRemove;table;isHighlightingCells;anchorX;anchorY;tableNodeKey;anchorCell;focusCell;anchorCellNodeKey;focusCellNodeKey;editor;tableSelection;hasHijackedSelectionStyles;isSelecting;pointerType;abortController;listenerOptions;constructor(e,t){this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=t,this.editor=e,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort("removeListeners"),Array.from(this.listenersToRemove).forEach(e=>e()),this.listenersToRemove.clear()}$lookup(){return Jt(this.tableNodeKey,this.editor)}trackTable(){const e=new MutationObserver(e=>{this.editor.getEditorState().read(()=>{let t=!1;for(let n=0;n<e.length;n++){const o=e[n].target.nodeName;if("TABLE"===o||"TBODY"===o||"THEAD"===o||"TR"===o){t=!0;break}}if(!t)return;const{tableNode:n,tableElement:o}=this.$lookup();this.table=un(n,o)},{editor:this.editor})});this.editor.getEditorState().read(()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=un(t,n),e.observe(n,{attributes:!0,childList:!0,subtree:!0})},{editor:this.editor})}$clearHighlight(e=!0){const t=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:n,tableElement:o}=this.$lookup();hn(t,un(n,o),null),e&&null!==b()&&(A(null),t.dispatchCommand(K,void 0))}$enableHighlightStyle(){const e=this.editor,{tableElement:t}=this.$lookup();o(t,e._config.theme.tableSelection),t.classList.remove("disable-selection"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:t}=this.$lookup();e(t,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(e){if(null!==e){e.tableKey!==this.tableNodeKey&&Ze(233,e.tableKey,this.tableNodeKey);const t=this.editor;this.tableSelection=e,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),hn(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=E(this.editor._window);e&&e.rangeCount>0&&e.removeAllRanges()}}$setFocusCellForSelection(e,t=!1){const n=this.editor,{tableNode:o}=this.$lookup(),r=e.x,l=e.y;if(this.focusCell=e,!this.isHighlightingCells){(t||this.anchorX!==r||this.anchorY!==l||null!=this.tableSelection&&null!=this.anchorCellNodeKey)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle())}if(-1!==this.focusX&&-1!==this.focusY&&r===this.focusX&&l===this.focusY)return!1;if(this.focusX=r,this.focusY=l,this.isHighlightingCells){const s=An(o,e.elem);if(null!=this.tableSelection&&null!=this.anchorCellNodeKey){let e=s;if(null===e&&t&&(e=o.getCellNodeFromCords(r,l,this.table)),null!==e){const t=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=e.getKey(),this.tableSelection=It(o,t,e),A(this.tableSelection),n.dispatchCommand(K,void 0),hn(n,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){return this.anchorCellNodeKey?v(this.anchorCellNodeKey):null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&Ze(234),e}$getFocusTableCell(){return this.focusCellNodeKey?v(this.focusCellNodeKey):null}$getFocusTableCellOrThrow(){const e=this.$getFocusTableCell();return null===e&&Ze(235),e}$setAnchorCellForSelection(e){this.isHighlightingCells=!1,this.anchorCell=e,this.anchorX=e.x,this.anchorY=e.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:t}=this.$lookup(),n=An(t,e.elem);if(null!==n){const e=n.getKey();null!=this.tableSelection?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(t.getKey(),e,e)):this.tableSelection=It(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const t=b();Pt(t)||Ze(236);const n=k(),o=n.anchor,r=n.focus,l=t.getNodes().filter(Ge);l.length>0||Ze(237);const s=l[0].getFirstChild(),i=y(s)?s.getFormatFlags(e,null):null;l.forEach(t=>{o.set(t.getKey(),0,"element"),r.set(t.getKey(),t.getChildrenSize(),"element"),n.formatText(e,i)}),A(t),this.editor.dispatchCommand(K,void 0)}$clearText(){const{editor:e}=this,t=v(this.tableNodeKey);if(!Bn(t))throw new Error("Expected TableNode.");const n=b();Pt(n)||Ze(253);const o=n.getNodes().filter(Ge),r=t.getFirstChild(),l=t.getLastChild();if(o.length>0&&null!==r&&null!==l&&ot(r)&&ot(l)&&o[0]===r.getFirstChild()&&o[o.length-1]===l.getLastChild()){t.selectPrevious();const n=t.getParent();return t.remove(),void(M(n)&&n.isEmpty()&&e.dispatchCommand($,void 0))}o.forEach(e=>{if(x(e)){const t=p();e.append(t),e.getChildren().forEach(e=>{e!==t&&e.remove()})}}),hn(e,this.table,null),A(null),e.dispatchCommand(K,void 0)}}const qt="__lexicalTableSelection";function jt(e){return d(e)&&"TABLE"===e.nodeName}function Vt(e,t){if(!t)return t;const n=jt(t)?t:t.querySelector("table");return jt(n)||Ze(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function Gt(e){return e._window}function Qt(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;Ge(n)&&(o=n)}return null}const Zt=[[W,"down"],[z,"up"],[L,"backward"],[H,"forward"]],en=[D,I,U],tn=[J,X];function nn(e,t){return e.registerRootListener(n=>{if(null===n)return;const o=e._window;if(null===o)return;const r=o=>{const r=o.target;if(0!==o.button||!ee(r)||!n.contains(r))return;const l=function(e){const t=cn(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if("TABLE"===n.nodeName&&qt in n&&n[qt])return{cellElement:t,tableElement:n,tableObserver:n[qt]};n=n.parentNode}return null}(r);e.update(()=>{if(Pt(b())){for(const[e]of t.observers.values())e.$clearHighlight(!1);A(null),e.dispatchCommand(K,void 0)}if(!l)return;const{tableObserver:n,tableElement:r,cellElement:s}=l;!function(e,t,n,o,r,l){const s=e._window;if(!s)return;const i=t=>{if(r.isSelecting)return;r.isSelecting=!0,null!==t&&null===r.anchorCell&&e.update(()=>{r.$setAnchorCellForSelection(t)});const n=()=>{r.isSelecting=!1,s.removeEventListener("pointerup",n),s.removeEventListener("pointermove",i)},i=t=>{if(!(e=>!(1&~e.buttons))(t)&&r.isSelecting)return r.isSelecting=!1,s.removeEventListener("pointerup",n),void s.removeEventListener("pointermove",i);if(!ee(t.target))return;let c=null;const a=!(me||o.contains(t.target));if(a)c=an(o,t.target);else for(const e of document.elementsFromPoint(t.clientX,t.clientY))if(c=an(o,e),c)break;if(c){const t=c;null===r.anchorCell&&e.update(()=>{r.$setAnchorCellForSelection(t)}),null!==r.focusCell&&c.elem===r.focusCell.elem||(l.setNextFocus({focusCell:c,override:a,tableKey:r.tableNodeKey}),e.dispatchCommand(K,void 0))}};s.addEventListener("pointerup",n,r.listenerOptions),s.addEventListener("pointermove",i,r.listenerOptions)};r.pointerType=t.pointerType;const c=oe(r.tableNodeKey),a=ne();if(me&&t.shiftKey&&_n(a,c)&&(w(a)||Pt(a))){const e=a.anchor.getNode(),o=Qt(c,a.anchor.getNode());if(o)r.$setAnchorCellForSelection(On(r,o)),r.$setFocusCellForSelection(n),Tn(t);else{(c.isBefore(e)?c.selectStart():c.selectEnd()).anchor.set(a.anchor.key,a.anchor.offset,a.anchor.type)}}else"touch"!==t.pointerType&&r.$setAnchorCellForSelection(n);i(n)}(e,o,s,r,n,t)})};return o.addEventListener("pointerdown",r),()=>{o.removeEventListener("pointerdown",r)}})}function on(e,t,o,l,s){const i=o.getRootElement(),c=Gt(o);null!==i&&null!==c||Ze(246);const a=new Yt(o,e.getKey()),u=Vt(e,t);!function(e,t){null!==sn(e)&&Ze(205);e[qt]=t}(u,a),a.listenersToRemove.add(()=>function(e,t){sn(e)===t&&delete e[qt]}(u,a));const h=e=>{if(e.detail>=3&&ee(e.target)){null!==cn(e.target)&&e.preventDefault()}};u.addEventListener("mousedown",h,a.listenerOptions),a.listenersToRemove.add(()=>{u.removeEventListener("mousedown",h)});for(const[t,n]of Zt)a.listenersToRemove.add(o.registerCommand(t,t=>xn(o,t,n,e,a,s),B));a.listenersToRemove.add(o.registerCommand(P,t=>{const n=b();if(Pt(n)){const o=Qt(e,n.focus.getNode());if(null!==o)return Tn(t),o.selectEnd(),!0}return!1},B));const d=t=>()=>{const o=b();if(!_n(o,e))return!1;if(Pt(o))return a.$clearText(),!0;if(w(o)){if(!Ge(Qt(e,o.anchor.getNode())))return!1;const r=o.anchor.getNode(),l=o.focus.getNode(),s=e.isParentOf(r),i=e.isParentOf(l);if(s&&!i||i&&!s)return a.$clearText(),!0;const c=n(o.anchor.getNode(),e=>x(e)),u=c&&n(c,e=>x(e)&&Ge(e.getParent()));if(!x(u)||!x(c))return!1;if(t===I&&null===u.getPreviousSibling())return!0}return!1};for(const e of en)a.listenersToRemove.add(o.registerCommand(e,d(e),B));const f=t=>{const n=b();if(!Pt(n)&&!w(n))return!1;const o=e.isParentOf(n.anchor.getNode());if(o!==e.isParentOf(n.focus.getNode())){const t=o?"anchor":"focus",r=o?"focus":"anchor",{key:l,offset:s,type:i}=n[r];return e[n[t].isBefore(n[r])?"selectPrevious":"selectNext"]()[r].set(l,s,i),!1}return!!_n(n,e)&&(!!Pt(n)&&(t&&(t.preventDefault(),t.stopPropagation()),a.$clearText(),!0))};for(const e of tn)a.listenersToRemove.add(o.registerCommand(e,f,B));return a.listenersToRemove.add(o.registerCommand(Y,e=>{const t=b();if(t){if(!Pt(t)&&!w(t))return!1;We(o,r(e,ClipboardEvent)?e:null,ze(t));const n=f(e);return w(t)?(t.removeText(),!0):n}return!1},B)),a.listenersToRemove.add(o.registerCommand(q,t=>{const o=b();if(!_n(o,e))return!1;if(Pt(o))return a.$formatCells(t),!0;if(w(o)){const e=n(o.anchor.getNode(),e=>Ge(e));if(!Ge(e))return!1}return!1},B)),a.listenersToRemove.add(o.registerCommand(j,t=>{const n=b();if(!Pt(n)||!_n(n,e))return!1;const o=n.anchor.getNode(),r=n.focus.getNode();if(!Ge(o)||!Ge(r))return!1;if(function(e,t){if(Pt(e)){const n=e.anchor.getNode(),o=e.focus.getNode();if(t&&n&&o){const[e]=Et(t,n,o);return n.getKey()===e[0][0].cell.getKey()&&o.getKey()===e[e.length-1].at(-1).cell.getKey()}}return!1}(n,e))return e.setFormat(t),!0;const[l,s,i]=Et(e,o,r),c=Math.max(s.startRow+s.cell.__rowSpan-1,i.startRow+i.cell.__rowSpan-1),a=Math.max(s.startColumn+s.cell.__colSpan-1,i.startColumn+i.cell.__colSpan-1),u=Math.min(s.startRow,i.startRow),h=Math.min(s.startColumn,i.startColumn),d=new Set;for(let e=u;e<=c;e++)for(let n=h;n<=a;n++){const o=l[e][n].cell;if(d.has(o))continue;d.add(o),o.setFormat(t);const r=o.getChildren();for(let e=0;e<r.length;e++){const n=r[e];x(n)&&!n.isInline()&&n.setFormat(t)}}return!0},B)),a.listenersToRemove.add(o.registerCommand(V,t=>{const r=b();if(!_n(r,e))return!1;if(Pt(r))return a.$clearHighlight(),!1;if(w(r)){const l=n(r.anchor.getNode(),e=>Ge(e));if(!Ge(l))return!1;if("string"==typeof t){const n=Rn(o,r,e);if(n)return Fn(n,e,[S(t)]),!0}}return!1},B)),l&&a.listenersToRemove.add(o.registerCommand(G,t=>{const o=b();if(!w(o)||!o.isCollapsed()||!_n(o,e))return!1;const r=yn(o.anchor.getNode());return!(null===r||!e.is(Nn(r)))&&(Tn(t),function(e,t){const o="next"===t?"getNextSibling":"getPreviousSibling",r="next"===t?"getFirstChild":"getLastChild",l=e[o]();if(x(l))return l.selectEnd();const s=n(e,ot);null===s&&Ze(247);for(let e=s[o]();ot(e);e=e[o]()){const t=e[r]();if(x(t))return t.selectEnd()}const i=n(s,Bn);null===i&&Ze(248);"next"===t?i.selectNext():i.selectPrevious()}(r,t.shiftKey?"previous":"next"),!0)},B)),a.listenersToRemove.add(o.registerCommand(Q,t=>e.isSelected(),B)),a.listenersToRemove.add(o.registerCommand($,()=>{const t=b();if(!w(t)||!t.isCollapsed()||!_n(t,e))return!1;const n=Rn(o,t,e);return!!n&&(Fn(n,e),!0)},B)),a}function rn(e,t){const o=b(),r=ne(),l=e.getAndClearNextFocus();if(null!==l){const{tableKey:t,focusCell:n}=l,r=e.observers.get(t);r||Ze(335,t);const[s]=r;if(Pt(o)&&o.tableKey===s.tableNodeKey)return(n.x!==s.focusX||n.y!==s.focusY)&&(s.$setFocusCellForSelection(n),!0);if(null!==s.anchorCell&&null!==s.anchorCellNodeKey&&n.elem!==s.anchorCell.elem&&null!==s.tableSelection)return s.$setFocusCellForSelection(n,!0),!0}const s=e.getAndClearShouldCheckSelectionForTable();if(s&&w(r)&&w(o)&&o.isCollapsed()){const e=oe(s),t=o.anchor.getNode(),r=e.getFirstChild(),l=yn(t);if(null!==l&&ot(r)){const t=r.getFirstChild();if(Ge(t)&&e.is(n(l,n=>n.is(e)||n.is(t))))return t.selectStart(),!0}}Pt(o)&&function(e,t){const n=Gt(e),o=ne();if(!t.is(o))return;const r=oe(t.tableKey),l=E(n);if(l&&l.anchorNode&&l.focusNode){const n=Z(l.focusNode),o=n&&!r.isParentOf(n),s=Z(l.anchorNode),i=s&&r.isParentOf(s);if(o&&i&&l.rangeCount>0){const n=he(l,e);n&&(n.anchor.set(r.getKey(),t.isBackward()?r.getChildrenSize():0,"element"),l.removeAllRanges(),A(n))}}}(t,o),w(o)&&function(e,t){const n=ne(),{anchor:o,focus:r}=e,l=o.getNode(),s=r.getNode(),i=yn(l),c=yn(s),a=i?Nn(i):null,u=c?Nn(c):null,h=e.isBackward(),d=i&&c&&a&&u&&a.is(u),f=u&&(!a||a.isParentOf(u)),g=a&&(!u||u.isParentOf(a));if(f){const t=e.clone(),[n]=Et(u,c,c),o=n[0][0].cell,r=n[n.length-1].at(-1).cell;t.focus.set(h?o.getKey():r.getKey(),h?0:r.getChildrenSize(),"element"),A(t)}else if(g){const t=e.clone(),[n]=Et(a,i,i),o=n[0][0].cell,r=n[n.length-1].at(-1).cell;t.anchor.set(h?r.getKey():o.getKey(),h?r.getChildrenSize():0,"element"),A(t)}else if(d){const o=t.observers.get(a.getKey());o||Ze(335,a.getKey());const[r]=o;if(i.is(c)||(r.$setAnchorCellForSelection(On(r,i)),r.$setFocusCellForSelection(On(r,c),!0)),"touch"===r.pointerType&&r.isSelecting&&e.isCollapsed()&&w(n)&&n.isCollapsed()){const e=yn(n.anchor.getNode());e&&!e.is(c)&&(r.$setAnchorCellForSelection(On(r,e)),r.$setFocusCellForSelection(On(r,c),!0),r.pointerType=null)}}}(o,e);const i=Array.from(e.observers.entries()).map(([e,[t]])=>({tableNode:oe(e),tableObserver:t}));for(const{tableNode:e,tableObserver:n}of i)ln(t,e,n);return!1}function ln(e,t,n){const o=b(),r=ne();o&&!o.is(r)&&(Pt(o)||Pt(r))&&n.tableSelection&&!n.tableSelection.is(r)&&(Pt(o)&&o.tableKey===n.tableNodeKey?n.$updateTableTableSelection(o):!Pt(o)&&Pt(r)&&r.tableKey===n.tableNodeKey&&n.$updateTableTableSelection(null)),n.hasHijackedSelectionStyles&&!t.isSelected()?function(e,t){t.$enableHighlightStyle(),dn(t.table,t=>{const n=t.elem;t.highlighted=!1,wn(e,t),n.getAttribute("style")||n.removeAttribute("style")})}(e,n):!n.hasHijackedSelectionStyles&&t.isSelected()&&function(e,t){t.$disableHighlightStyle(),dn(t.table,t=>{t.highlighted=!0,bn(e,t)})}(e,n)}function sn(e){return e[qt]||null}function cn(e){let t=e;for(;null!=t;){const e=t.nodeName;if("TD"===e||"TH"===e){const e=t._cell;return void 0===e?null:e}t=t.parentNode}return null}function an(e,t){if(!e.contains(t))return null;let n=null;for(let o=t;null!=o;o=o.parentNode){if(o===e)return n;const t=o.nodeName;"TD"!==t&&"TH"!==t||(n=o._cell||null)}return null}function un(e,t){const n=[],o={columns:0,domRows:n,rows:0};let r=Vt(e,t).querySelector("tr"),l=0,s=0;for(n.length=0;null!=r;){const e=r.nodeName;if("TD"===e||"TH"===e){const e={elem:r,hasBackgroundColor:""!==r.style.backgroundColor,highlighted:!1,x:l,y:s};r._cell=e;let t=n[s];void 0===t&&(t=n[s]=[]),t[l]=e}else{const e=r.firstChild;if(null!=e){r=e;continue}}const t=r.nextSibling;if(null!=t){l++,r=t;continue}const o=r.parentNode;if(null!=o){const e=o.nextSibling;if(null==e)break;s++,l=0,r=e}}return o.columns=l+1,o.rows=s+1,o}function hn(e,t,n){const o=new Set(n?n.getNodes():[]);dn(t,(t,n)=>{const r=t.elem;o.has(n)?(t.highlighted=!0,bn(e,t)):(t.highlighted=!1,wn(e,t),r.getAttribute("style")||r.removeAttribute("style"))})}function dn(e,t){const{domRows:n}=e;for(let e=0;e<n.length;e++){const o=n[e];if(o)for(let n=0;n<o.length;n++){const r=o[n];if(!r)continue;const l=Z(r.elem);null!==l&&t(r,l,{x:n,y:e})}}}const fn=(e,t,n,o,r)=>{const l="forward"===r;switch(r){case"backward":case"forward":return n!==(l?e.table.columns-1:0)?Sn(t.getCellNodeFromCordsOrThrow(n+(l?1:-1),o,e.table),l):o!==(l?e.table.rows-1:0)?Sn(t.getCellNodeFromCordsOrThrow(l?0:e.table.columns-1,o+(l?1:-1),e.table),l):l?t.selectNext():t.selectPrevious(),!0;case"up":return 0!==o?Sn(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case"down":return o!==e.table.rows-1?Sn(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function gn(e,t){let n,o;if(t.startColumn===e.minColumn)n="minColumn";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n="maxColumn"}if(t.startRow===e.minRow)o="minRow";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;o="maxRow"}return[n,o]}function mn([e,t]){return["minColumn"===e?"maxColumn":"minColumn","minRow"===t?"maxRow":"minRow"]}function pn(e,t,[n,o]){const r=t[o],l=e[r];void 0===l&&Ze(250,o,String(r));const s=t[n],i=l[s];return void 0===i&&Ze(250,n,String(s)),i}function Cn(e,t,n,o,r){const l=$t(t,n,o),s=function(e,t){const{minColumn:n,maxColumn:o,minRow:r,maxRow:l}=t;let s=1,i=1,c=1,a=1;const u=e[r],h=e[l];for(let e=n;e<=o;e++)s=Math.max(s,u[e].cell.__rowSpan),a=Math.max(a,h[e].cell.__rowSpan);for(let t=r;t<=l;t++)i=Math.max(i,e[t][n].cell.__colSpan),c=Math.max(c,e[t][o].cell.__colSpan);return{bottomSpan:a,leftSpan:i,rightSpan:c,topSpan:s}}(t,l),{topSpan:i,leftSpan:c,bottomSpan:a,rightSpan:u}=s,h=function(e,t){const n=gn(e,t);return null===n&&Ze(249,t.cell.getKey()),n}(l,n),[d,f]=mn(h);let g=l[d],m=l[f];"forward"===r?g+="maxColumn"===d?1:c:"backward"===r?g-="minColumn"===d?1:u:"down"===r?m+="maxRow"===f?1:i:"up"===r&&(m-="minRow"===f?1:a);const p=t[m];if(void 0===p)return!1;const C=p[g];if(void 0===C)return!1;const[_,S]=function(e,t,n){const o=$t(e,t,n),r=gn(o,t);if(r)return[pn(e,o,r),pn(e,o,mn(r))];const l=gn(o,n);if(l)return[pn(e,o,mn(l)),pn(e,o,l)];const s=["minColumn","minRow"];return[pn(e,o,s),pn(e,o,mn(s))]}(t,n,C),b=On(e,_.cell),w=On(e,S.cell);return e.$setAnchorCellForSelection(b),e.$setFocusCellForSelection(w,!0),!0}function _n(e,t){if(w(e)||Pt(e)){const n=t.isParentOf(e.anchor.getNode()),o=t.isParentOf(e.focus.getNode());return n&&o}return!1}function Sn(e,t){t?e.selectStart():e.selectEnd()}function bn(t,n){const o=n.elem,r=t._config.theme;Ge(Z(o))||Ze(131),e(o,r.tableCellSelected)}function wn(e,t){const n=t.elem;Ge(Z(n))||Ze(131);const r=e._config.theme;o(n,r.tableCellSelected)}function yn(e){const t=n(e,Ge);return Ge(t)?t:null}function Nn(e){const t=n(e,Bn);return Bn(t)?t:null}function vn(e,t,o,r,l,s,i){const c=re(o.focus,l?"previous":"next");if(le(c))return!1;let a=c;for(const e of se(c).iterNodeCarets("shadowRoot")){if(!ie(e)||!x(e.origin))return!1;a=e}const u=a.getParentAtCaret();if(!Ge(u))return!1;const h=u,d=function(e){for(const t of se(e).iterNodeCarets("root")){const{origin:n}=t;if(Ge(n)){if(de(t))return fe(n,e.direction)}else if(!ot(n))break}return null}(ce(h,a.direction)),f=n(h,Bn);if(!f||!f.is(s))return!1;const g=e.getElementByKey(h.getKey()),m=cn(g);if(!g||!m)return!1;const p=zn(e,f);if(i.table=p,d)if("extend"===r){const t=cn(e.getElementByKey(d.origin.getKey()));if(!t)return!1;i.$setAnchorCellForSelection(m),i.$setFocusCellForSelection(t,!0)}else{const e=ue(d);ae(o.anchor,e),ae(o.focus,e)}else if("extend"===r)i.$setAnchorCellForSelection(m),i.$setFocusCellForSelection(m,!0);else{const e=function(e){const t=ge(e);return de(t)?ue(t):e}(ce(f,c.direction));ae(o.anchor,e),ae(o.focus,e)}return Tn(t),!0}function xn(e,t,o,r,l,s){if(("up"===o||"down"===o)&&function(e){const t=e.getRootElement();if(!t)return!1;return t.hasAttribute("aria-controls")&&"typeahead-menu"===t.getAttribute("aria-controls")}(e))return!1;const i=b();if(!_n(i,r)){if(w(i)){if("backward"===o){if(i.focus.offset>0)return!1;const e=function(e){for(let t=e,n=e;null!==n;t=n,n=n.getParent())if(x(n)){if(n!==t&&n.getFirstChild()!==t)return null;if(!n.isInline())return n}return null}(i.focus.getNode());if(!e)return!1;const n=e.getPreviousSibling();return!!Bn(n)&&(Tn(t),t.shiftKey?i.focus.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent(),"element"):n.selectEnd(),!0)}if(t.shiftKey&&("up"===o||"down"===o)){const e=i.focus.getNode();if(!i.isCollapsed()&&("up"===o&&!i.isBackward()||"down"===o&&i.isBackward())){let l=n(e,e=>Bn(e));if(Ge(l)&&(l=n(l,Bn)),l!==r)return!1;if(!l)return!1;const s="down"===o?l.getNextSibling():l.getPreviousSibling();if(!s)return!1;let c=0;"up"===o&&x(s)&&(c=s.getChildrenSize());let a=s;if("up"===o&&x(s)){const e=s.getLastChild();a=e||s,c=g(a)?a.getTextContentSize():0}const u=i.clone();return u.focus.set(a.getKey(),c,g(a)?"text":"element"),A(u),Tn(t),!0}if(te(e)){const e="up"===o?i.getNodes()[i.getNodes().length-1]:i.getNodes()[0];if(e){if(null!==Qt(r,e)){const e=r.getFirstDescendant(),t=r.getLastDescendant();if(!e||!t)return!1;const[n]=Mt(e),[o]=Mt(t),s=r.getCordsFromCellNode(n,l.table),i=r.getCordsFromCellNode(o,l.table),c=r.getDOMCellFromCordsOrThrow(s.x,s.y,l.table),a=r.getDOMCellFromCordsOrThrow(i.x,i.y,l.table);return l.$setAnchorCellForSelection(c),l.$setFocusCellForSelection(a,!0),!0}}return!1}{let r=n(e,e=>x(e)&&!e.isInline());if(Ge(r)&&(r=n(r,Bn)),!r)return!1;const s="down"===o?r.getNextSibling():r.getPreviousSibling();if(Bn(s)&&l.tableNodeKey===s.getKey()){const e=s.getFirstDescendant(),n=s.getLastDescendant();if(!e||!n)return!1;const[r]=Mt(e),[l]=Mt(n),c=i.clone();return c.focus.set(("up"===o?r:l).getKey(),"up"===o?0:l.getChildrenSize(),"element"),Tn(t),A(c),!0}}}}return"down"===o&&Mn(e)&&s.setShouldCheckSelectionForTable(r.getKey()),!1}if(w(i)){if("backward"===o||"forward"===o){return vn(e,t,i,t.shiftKey?"extend":"move","backward"===o,r,l)}if(i.isCollapsed()){const{anchor:c,focus:a}=i,u=n(c.getNode(),Ge),h=n(a.getNode(),Ge);if(!Ge(u)||!u.is(h))return!1;const d=Nn(u);if(d!==r&&null!=d){const n=Vt(d,e.getElementByKey(d.getKey()));if(null!=n)return l.table=un(d,n),xn(e,t,o,d,l,s)}const f=e.getElementByKey(u.__key),g=e.getElementByKey(c.key);if(null==g||null==f)return!1;let m;if("element"===c.type)m=g.getBoundingClientRect();else{const t=E(Gt(e));if(null===t||0===t.rangeCount)return!1;m=t.getRangeAt(0).getBoundingClientRect()}const p="up"===o?u.getFirstChild():u.getLastChild();if(null==p)return!1;const C=e.getElementByKey(p.__key);if(null==C)return!1;const _=C.getBoundingClientRect();if("up"===o?_.top>m.top-m.height:m.bottom+m.height>_.bottom){Tn(t);const e=r.getCordsFromCellNode(u,l.table);if(!t.shiftKey)return fn(l,r,e.x,e.y,o);{const t=r.getDOMCellFromCordsOrThrow(e.x,e.y,l.table);l.$setAnchorCellForSelection(t),l.$setFocusCellForSelection(t,!0)}return!0}}}else if(Pt(i)){const{anchor:s,focus:c,tableKey:a}=i;if(a!==r.getKey())return!1;const u=n(s.getNode(),Ge),h=n(c.getNode(),Ge),[d]=i.getNodes();Bn(d)||Ze(251);const f=Vt(d,e.getElementByKey(d.getKey()));if(!Ge(u)||!Ge(h)||!Bn(d)||null==f)return!1;l.$updateTableTableSelection(i);const g=un(d,f),m=r.getCordsFromCellNode(u,g),p=r.getDOMCellFromCordsOrThrow(m.x,m.y,g);if(l.$setAnchorCellForSelection(p),Tn(t),t.shiftKey){const[e,t,n]=Et(r,u,h);return Cn(l,e,t,n,o)}return h.selectEnd(),!0}return!1}function Tn(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function Fn(e,t,n){const o=p();"first"===e?t.insertBefore(o):t.insertAfter(o),o.append(...n||[]),o.selectEnd()}function Rn(e,t,o){const r=o.getParent();if(!r)return;const l=E(Gt(e));if(!l)return;const s=l.anchorNode,i=e.getElementByKey(r.getKey()),c=Vt(o,e.getElementByKey(o.getKey()));if(!s||!i||!c||!i.contains(s)||c.contains(s))return;const a=n(t.anchor.getNode(),e=>Ge(e));if(!a)return;const u=n(a,e=>Bn(e));if(!Bn(u)||!u.is(o))return;const[h,d]=Et(o,a,a),f=h[0][0],g=h[h.length-1][h[0].length-1],{startRow:m,startColumn:p}=d,C=m===f.startRow&&p===f.startColumn,_=m===g.startRow&&p===g.startColumn;return C?"first":_?"last":void 0}function On(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function An(e,t,n){return Qt(e,Z(t,n))}function Kn(e,t,n){const o=e.querySelector("colgroup");if(!o)return;const r=[];for(let e=0;e<t;e++){const t=document.createElement("col"),o=n&&n[e];o&&(t.style.width=`${o}px`),r.push(t)}o.replaceChildren(...r)}function En(t,n,r){if(!n.theme.tableAlignment)return;const l=[],s=[];for(const e of["center","right"]){const t=n.theme.tableAlignment[e];t&&(e===r?s:l).push(t)}o(t,...l),e(t,...s)}const kn=new WeakSet;function Mn(e=O()){return kn.has(e)}function $n(e,t){t?kn.add(e):kn.delete(e)}class Wn extends h{__rowStriping;__frozenColumnCount;__frozenRowCount;__colWidths;static getType(){return"table"}getColWidths(){return this.getLatest().__colWidths}setColWidths(e){const t=this.getWritable();return t.__colWidths=e,t}static clone(e){return new Wn(e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__colWidths=e.__colWidths,this.__rowStriping=e.__rowStriping,this.__frozenColumnCount=e.__frozenColumnCount,this.__frozenRowCount=e.__frozenRowCount}static importDOM(){return{table:e=>({conversion:Ln,priority:1})}}static importJSON(e){return Hn().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setRowStriping(e.rowStriping||!1).setFrozenColumns(e.frozenColumnCount||0).setFrozenRows(e.frozenRowCount||0).setColWidths(e.colWidths)}constructor(e){super(e),this.__rowStriping=!1,this.__frozenColumnCount=0,this.__frozenRowCount=0,this.__colWidths=void 0}exportJSON(){return{...super.exportJSON(),colWidths:this.getColWidths(),frozenColumnCount:this.__frozenColumnCount?this.__frozenColumnCount:void 0,frozenRowCount:this.__frozenRowCount?this.__frozenRowCount:void 0,rowStriping:this.__rowStriping?this.__rowStriping:void 0}}extractWithChild(e,t,n){return"html"===n}getDOMSlot(e){const t=jt(e)?e:e.querySelector("table");return jt(t)||Ze(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector("colgroup"))}createDOM(t,n){const o=document.createElement("table");this.__style&&pe(o.style,this.__style);const r=document.createElement("colgroup");if(o.appendChild(r),Ce(r),e(o,t.theme.table),this.updateTableElement(null,o,t),Mn(n)){const n=document.createElement("div"),r=t.theme.tableScrollableWrapper;return r?e(n,r):n.style.overflowX="auto",n.appendChild(o),this.updateTableWrapper(null,n,o,t),n}return o}updateTableWrapper(t,n,r,l){this.__frozenColumnCount!==(t?t.__frozenColumnCount:0)&&function(t,n,r,l){l>0?(e(t,r.theme.tableFrozenColumn),n.setAttribute("data-lexical-frozen-column","true")):(o(t,r.theme.tableFrozenColumn),n.removeAttribute("data-lexical-frozen-column"))}(n,r,l,this.__frozenColumnCount),this.__frozenRowCount!==(t?t.__frozenRowCount:0)&&function(t,n,r,l){l>0?(e(t,r.theme.tableFrozenRow),n.setAttribute("data-lexical-frozen-row","true")):(o(t,r.theme.tableFrozenRow),n.removeAttribute("data-lexical-frozen-row"))}(n,r,l,this.__frozenRowCount)}updateTableElement(t,n,r){this.__style!==(t?t.__style:"")&&pe(n.style,this.__style,t?t.__style:""),this.__rowStriping!==(!!t&&t.__rowStriping)&&function(t,n,r){r?(e(t,n.theme.tableRowStriping),t.setAttribute("data-lexical-row-striping","true")):(o(t,n.theme.tableRowStriping),t.removeAttribute("data-lexical-row-striping"))}(n,r,this.__rowStriping);const l=t?t.getColumnCount():0,s=t?t.__colWidths:void 0;this.getColumnCount()===l&&this.getColWidths()===s||Kn(n,this.getColumnCount(),this.getColWidths()),En(n,r,this.getFormatType())}updateDOM(e,t,n){const o=Vt(this,t);return t===o===Mn()||(l(r=t)&&"DIV"===r.nodeName&&this.updateTableWrapper(e,t,o,n),this.updateTableElement(e,o,n),!1);var r}scaleDOMColWidths(e,t){const n=this.getColWidths();if(!n)return;Kn(Vt(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(e){const t=super.exportDOM(e),{element:n}=t;return{after:n=>{if(t.after&&(n=t.after(n)),!jt(n)&&l(n)&&(n=n.querySelector("table")),!jt(n))return null;En(n,e._config,this.getFormatType());const[o]=kt(this,null,null),r=new Map;for(const e of o)for(const t of e){const e=t.cell.getKey();r.has(e)||r.set(e,{colSpan:t.cell.getColSpan(),startColumn:t.startColumn})}const s=new Set;for(const e of n.querySelectorAll(":scope > tr > [data-temporary-table-cell-lexical-key]")){const t=e.getAttribute("data-temporary-table-cell-lexical-key");if(t){const n=r.get(t);if(e.removeAttribute("data-temporary-table-cell-lexical-key"),n){r.delete(t);for(let e=0;e<n.colSpan;e++)s.add(e+n.startColumn)}}}const i=n.querySelector(":scope > colgroup");if(i){const e=Array.from(n.querySelectorAll(":scope > colgroup > col")).filter((e,t)=>s.has(t));i.replaceChildren(...e)}const c=n.querySelectorAll(":scope > tr");if(c.length>0){const e=document.createElement("tbody");for(const t of c)e.appendChild(t);n.append(e)}return n},element:!jt(n)&&l(n)?n.querySelector("table"):n}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(e,t){const{rows:n,domRows:o}=t;for(let t=0;t<n;t++){const n=o[t];if(null!=n)for(let o=0;o<n.length;o++){const r=n[o];if(null==r)continue;const{elem:l}=r,s=An(this,l);if(null!==s&&e.is(s))return{x:o,y:t}}}throw new Error("Cell not found in table.")}getDOMCellFromCords(e,t,n){const{domRows:o}=n,r=o[t];if(null==r)return null;const l=r[e<r.length?e:r.length-1];return null==l?null:l}getDOMCellFromCordsOrThrow(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(!o)throw new Error("Cell not found at cords.");return o}getCellNodeFromCords(e,t,n){const o=this.getDOMCellFromCords(e,t,n);if(null==o)return null;const r=Z(o.elem);return Ge(r)?r:null}getCellNodeFromCordsOrThrow(e,t,n){const o=this.getCellNodeFromCords(e,t,n);if(!o)throw new Error("Node at cords not TableCellNode.");return o}getRowStriping(){return Boolean(this.getLatest().__rowStriping)}setRowStriping(e){const t=this.getWritable();return t.__rowStriping=e,t}setFrozenColumns(e){const t=this.getWritable();return t.__frozenColumnCount=e,t}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(e){const t=this.getWritable();return t.__frozenRowCount=e,t}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const e=this.getFirstChild();if(!e)return 0;let t=0;return e.getChildren().forEach(e=>{Ge(e)&&(t+=e.getColSpan())}),t}}function zn(e,t){const n=e.getElementByKey(t.getKey());return null===n&&Ze(230),un(t,n)}function Ln(e){const n=Hn();e.hasAttribute("data-lexical-row-striping")&&n.setRowStriping(!0),e.hasAttribute("data-lexical-frozen-column")&&n.setFrozenColumns(1),e.hasAttribute("data-lexical-frozen-row")&&n.setFrozenRows(1);const o=e.querySelector(":scope > colgroup");if(o){let e=[];for(const t of o.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!Je.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&n.setColWidths(e)}return{after:e=>t(e,ot),node:n}}function Hn(){return C(new Wn)}function Bn(e){return e instanceof Wn}function Pn(e){ot(e.getParent())?e.isEmpty()&&e.append(p()):e.remove()}function Dn(e){Bn(e.getParent())?u(e,Ge):e.remove()}function In(e){u(e,ot);const[t]=kt(e,null,null),n=t.reduce((e,t)=>Math.max(e,t.length),0),o=e.getChildren();for(let e=0;e<t.length;++e){const r=o[e];if(!r)continue;ot(r)||Ze(254,r.constructor.name,r.getType());const l=t[e].reduce((e,t)=>t?1+e:e,0);if(l!==n)for(let e=l;e<n;++e){const e=Ve();e.append(p()),r.append(e)}}const r=e.getColWidths(),l=e.getColumnCount();if(r&&r.length!==l){let t;if(l<r.length)t=r.slice(0,l);else if(r.length>0){const e=r[r.length-1];t=[...r,...Array(l-r.length).fill(e)]}e.setColWidths(t)}}function Un(e){if(e.detail<3||!ee(e.target))return!1;const t=Z(e.target);if(null===t)return!1;const o=n(t,e=>x(e)&&!e.isInline());if(null===o)return!1;return!!Ge(o.getParent())&&(o.select(0),!0)}function Jn(){const e=b();if(!w(e))return!1;const t=Nn(e.anchor.getNode());if(null===t)return!1;const n=Ne();if(!n.is(t.getParent())||1!==n.getChildrenSize())return!1;const[o]=kt(t,null,null);if(0===o.length||0===o[0].length)return!1;const r=o[0][0];if(!r||!r.cell)return!1;const l=o[o.length-1],s=l[l.length-1];if(!s||!s.cell)return!1;const i=It(t,r.cell,s.cell);return A(i),!0}function Xn(e){return e.registerNodeTransform(Ye,e=>{if(e.getColSpan()>1||e.getRowSpan()>1){const[,,t]=Mt(e),[n]=Et(t,e,e),o=n.length,r=n[0].length;let l=t.getFirstChild();ot(l)||Ze(175);const i=[];for(let e=0;e<o;e++){0!==e&&(l=l.getNextSibling(),ot(l)||Ze(175));let t=null;for(let o=0;o<r;o++){const r=n[e][o],c=r.cell;if(r.startRow===e&&r.startColumn===o)t=c,i.push(c);else if(c.getColSpan()>1||c.getRowSpan()>1){Ge(c)||Ze(176);const e=Ve(c.__headerState);null!==t?t.insertAfter(e):s(l,e)}}}for(const e of i)e.setColSpan(1),e.setRowSpan(1)}})}function Yn(e,t=!0){const n=new Xt,o=(o,r,l)=>{const s=Vt(o,l),i=on(o,s,e,t,n);n.observers.set(r,[i,s])};return i(nn(e,n),e.registerCommand(K,()=>rn(n,e),B),e.registerMutationListener(Wn,t=>{e.getEditorState().read(()=>{for(const[e,r]of t){const t=n.observers.get(e);if("created"===r||"updated"===r){const{tableNode:r,tableElement:l}=Jt(e);void 0===t?o(r,e,l):l!==t[1]&&(t[0].removeListeners(),n.observers.delete(e),o(r,e,l))}else"destroyed"===r&&void 0!==t&&(t[0].removeListeners(),n.observers.delete(e))}},{editor:e})},{skipInitialization:!1}),()=>{for(const[,[e]]of n.observers)e.removeListeners()})}function qn(e,t){e.hasNodes([Wn])||Ze(255);const{hasNestedTables:o=ke(!1)}=t??{};return i(e.registerCommand(Qe,e=>function({rows:e,columns:t,includeHeaders:n},o){const r=b()||ne();if(!r||!w(r))return!1;if(!o&&Nn(r.anchor.getNode()))return!1;const l=rt(Number(e),Number(t),n);c(l);const s=l.getFirstDescendant();return g(s)&&s.select(),!0}(e,o.peek()),_e),e.registerCommand(Se,(t,r)=>e===r&&function(e,t){const{nodes:o,selection:r}=e;if(!o.some(e=>Bn(e)||a(e).some(e=>Bn(e.node))))return!1;const l=Pt(r),s=w(r);if(!(s&&null!==n(r.anchor.getNode(),e=>Ge(e))&&null!==n(r.focus.getNode(),e=>Ge(e))||l))return!1;if(1===o.length&&Bn(o[0]))return function(e,t){const o=t.getStartEndPoints(),r=Pt(t);if(null===o)return!1;const[l,s]=o,[i,c,a]=Mt(l),u=n(s.getNode(),e=>Ge(e));if(!(Ge(i)&&Ge(u)&&ot(c)&&Bn(a)))return!1;const[h,d,f]=Et(a,i,u),[m]=kt(e,null,null),C=h.length,_=C>0?h[0].length:0;let S=d.startRow,b=d.startColumn,w=m.length,y=w>0?m[0].length:0;if(r){const e=$t(h,d,f),t=e.maxRow-e.minRow+1,n=e.maxColumn-e.minColumn+1;S=e.minRow,b=e.minColumn,w=Math.min(w,t),y=Math.min(y,n)}let N=!1;const v=Math.min(C,S+w)-1,x=Math.min(_,b+y)-1,T=new Set;for(let e=S;e<=v;e++)for(let t=b;t<=x;t++){const n=h[e][t];T.has(n.cell.getKey())||(1===n.cell.__rowSpan&&1===n.cell.__colSpan||(Kt(n.cell),T.add(n.cell.getKey()),N=!0))}let[F]=kt(a.getWritable(),null,null);const R=w-C+S;for(let e=0;e<R;e++){pt(F[C-1][0].cell)}const O=y-_+b;for(let e=0;e<O;e++){bt(F[0][_-1].cell,!0,!1)}[F]=kt(a.getWritable(),null,null);for(let e=S;e<S+w;e++)for(let t=b;t<b+y;t++){const n=e-S,o=t-b,r=m[n][o];if(r.startRow!==n||r.startColumn!==o)continue;const l=r.cell;if(1!==l.__rowSpan||1!==l.__colSpan){const n=[],o=Math.min(e+l.__rowSpan,S+w)-1,r=Math.min(t+l.__colSpan,b+y)-1;for(let l=e;l<=o;l++)for(let e=t;e<=r;e++){const t=F[l][e];n.push(t.cell)}Rt(n),N=!0}const{cell:s}=F[e][t],i=l.getBackgroundColor();null!=i&&s.setBackgroundColor(i);const c=s.getChildren();l.getChildren().forEach(e=>{if(g(e)){p().append(e),s.append(e)}else s.append(e)}),c.forEach(e=>e.remove())}if(r&&N){const[e]=kt(a.getWritable(),null,null);e[d.startRow][d.startColumn].cell.selectEnd()}return!0}(o[0],r);if(s&&t.peek()&&!function(e){if(Pt(e)&&!e.focus.getNode().is(e.anchor.getNode()))return!0;if(w(e)&&Ge(e.anchor.getNode())&&!e.anchor.getNode().is(e.focus.getNode()))return!0;return!1}(r))return!1;return!0}(t,o),_e),e.registerCommand(be,Jn,we),e.registerCommand(ye,Un,_e),e.registerNodeTransform(Wn,In),e.registerNodeTransform(et,Dn),e.registerNodeTransform(Ye,Pn))}const jn=ve({build:(e,t,n)=>$e(t),config:Te({hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasTabHandler:!0}),name:"@lexical/table/Table",nodes:()=>[Wn,et,Ye],register(e,t,n){const o=n.getOutput();return i(Me(()=>{const t=o.hasHorizontalScroll.value;Mn(e)!==t&&($n(e,t),e.update(xe))}),qn(e,o),Me(()=>Yn(e,o.hasTabHandler.value)),Me(()=>o.hasCellMerge.value?void 0:Xn(e)),Me(()=>o.hasCellBackgroundColor.value?void 0:e.registerNodeTransform(Ye,e=>{null!==e.getBackgroundColor()&&e.setBackgroundColor(null)})))}});function Vn(e){const t=[];let n=null;const o=()=>{if(null!==n){const e=n.getFirstChild();m(e)&&1===n.getChildrenSize()&&e.remove()}};for(const r of e)f(r)||g(r)||m(r)?null!==n?n.append(r):(n=p().append(r),t.push(n)):(o(),t.push(r),n=null);return o(),0===t.length&&t.push(p()),t}const Gn={$accepts:ot,$packageRun:e=>e.every(Ge)?[nt().splice(0,0,e)]:[],name:"TableSchema"},Qn={$accepts:Ge,name:"TableRowSchema"},Zn=[Be({$import:(e,n)=>{const o=Hn();n.hasAttribute("data-lexical-row-striping")&&o.setRowStriping(!0),n.hasAttribute("data-lexical-frozen-column")&&o.setFrozenColumns(1),n.hasAttribute("data-lexical-frozen-row")&&o.setFrozenRows(1);const r=n.querySelector(":scope > colgroup");if(r){let e=[];for(const t of r.querySelectorAll(":scope > col")){let n=t.style.width||"";if(!Je.test(n)&&(n=t.getAttribute("width")||"",!/^\d+$/.test(n))){e=void 0;break}e.push(parseFloat(n))}e&&o.setColWidths(e)}return[o.splice(0,0,t(e.$importChildren(n),ot))]},match:Pe.tag("table"),name:"@lexical/table/table"}),Be({$import:(e,n)=>[nt(Je.test(n.style.height)?parseFloat(n.style.height):void 0).splice(0,0,t(e.$importChildren(n),Ge))],match:Pe.tag("tr"),name:"@lexical/table/tr"}),Be({$import:(e,t)=>{const n="TH"===t.nodeName,o=Je.test(t.style.width)?parseFloat(t.style.width):void 0;let r=Xe.NO_STATUS;if(n){const e=t.getAttribute("scope");if("col"===e)r=Xe.COLUMN;else if("row"===e)r=Xe.ROW;else{const e=t.parentElement,n=Re(e)&&(e.parentElement&&"THEAD"===e.parentElement.nodeName||0===e.rowIndex),o=0===t.cellIndex;n&&(r|=Xe.ROW),o&&(r|=Xe.COLUMN),r===Xe.NO_STATUS&&(r=Xe.ROW)}}const l=Ve(r,t.colSpan,o);l.__rowSpan=t.rowSpan;const s=t.style.backgroundColor;""!==s&&(l.__backgroundColor=s);const i=t.style.verticalAlign;(function(e){return"middle"===e||"bottom"===e})(i)&&(l.__verticalAlign=i);const c=e.get(De),a=c|function(e){let t=0;const n=e.fontWeight;"700"!==n&&"bold"!==n||(t|=Oe),"italic"===e.fontStyle&&(t|=Ae);const o=(e.textDecoration||"").split(" ");return o.includes("underline")&&(t|=Ke),o.includes("line-through")&&(t|=Ee),t}(t.style),u=e.get(Ie),h=t.style.color,d=h?{...u,color:h}:u,f=[];return a!==c&&f.push(Ue(De,a)),d!==u&&f.push(Ue(Ie,d)),[l.splice(0,0,Vn(e.$importChildren(t,{context:f})))]},match:Pe.tag("td","th"),name:"@lexical/table/cell"})],eo=ve({dependencies:[Le,jn,Fe(He,{rules:Zn})],name:"@lexical/table/Import"});export{Et as $computeTableMap,kt as $computeTableMapSkipCellCheck,Ve as $createTableCellNode,Hn as $createTableNode,rt as $createTableNodeWithDimensions,nt as $createTableRowNode,Dt as $createTableSelection,It as $createTableSelectionFrom,wt as $deleteTableColumn,vt as $deleteTableColumnAtSelection,xt as $deleteTableColumn__EXPERIMENTAL,yt as $deleteTableRowAtSelection,Nt as $deleteTableRow__EXPERIMENTAL,yn as $findCellNode,Nn as $findTableNode,zn as $getElementForTableNode,Mt as $getNodeTriplet,Jt as $getTableAndElementByKey,lt as $getTableCellNodeFromLexicalNode,Lt as $getTableCellNodeRect,at as $getTableColumnIndexFromTableCellNode,it as $getTableNodeFromLexicalNodeOrThrow,ct as $getTableRowIndexFromTableCellNode,st as $getTableRowNodeFromTableCellNodeOrThrow,Ct as $insertTableColumn,_t as $insertTableColumnAtSelection,St as $insertTableColumn__EXPERIMENTAL,dt as $insertTableRow,gt as $insertTableRowAtSelection,mt as $insertTableRow__EXPERIMENTAL,Mn as $isScrollableTablesActive,Wt as $isSimpleTable,Ge as $isTableCellNode,Bn as $isTableNode,ot as $isTableRowNode,Pt as $isTableSelection,Rt as $mergeCells,zt as $moveTableColumn,ht as $removeTableRowAtIndex,At as $unmergeCell,Qe as INSERT_TABLE_COMMAND,Xe as TableCellHeaderStates,Ye as TableCellNode,jn as TableExtension,eo as TableImportExtension,Zn as TableImportRules,Wn as TableNode,Yt as TableObserver,et as TableRowNode,Qn as TableRowSchema,Gn as TableSchema,on as applyTableHandlers,cn as getDOMCellFromTarget,Vt as getTableElement,sn as getTableObserverFromTableElement,Xn as registerTableCellUnmergeTransform,qn as registerTablePlugin,Yn as registerTableSelectionObserver,$n as setScrollableTablesActive};
+diff --git a/src/LexicalTableObserver.ts b/src/LexicalTableObserver.ts
+index eb24a778294e05cf2e4fee396cd3c952b40ee7b2..80e32a2b8bdaca5a49983590258819c4b1f17c56 100644
+--- a/src/LexicalTableObserver.ts
++++ b/src/LexicalTableObserver.ts
+@@ -555,8 +555,6 @@ export class TableObserver {
+ selectedNodes.forEach(cellNode => {
+ if ($isElementNode(cellNode)) {
+ const paragraphNode = $createParagraphNode();
+- const textNode = $createTextNode();
+- paragraphNode.append(textNode);
+ cellNode.append(paragraphNode);
+ cellNode.getChildren().forEach(child => {
+ if (child !== paragraphNode) {
diff --git a/apps/web/src/features/block-md/component/FormatTools.tsx b/apps/web/src/features/block-md/component/FormatTools.tsx
index f348eaa72f..d8629c5e16 100644
--- a/apps/web/src/features/block-md/component/FormatTools.tsx
+++ b/apps/web/src/features/block-md/component/FormatTools.tsx
@@ -14,12 +14,20 @@ import { toast } from '@core/component/Toast/Toast';
import { ENABLE_MARKDOWN_COMMENTS } from '@core/constant/featureFlags';
import type { ValidHotkey } from '@core/hotkey/types';
import { useCanComment, useCanEdit } from '@core/signal/permissions';
+import {
+ $isTableCellNode,
+ $isTableSelection,
+ $mergeCells,
+ $unmergeCell,
+} from '@lexical/table';
import type { ElementName } from '@macro-inc/lexical-core';
import CaretRight from '@phosphor/caret-right.svg';
import ChatTeardrop from '@phosphor/chat-teardrop.svg';
import Check from '@phosphor/check-square.svg';
import TextCode from '@phosphor/code.svg';
import CodeBlock from '@phosphor/code-block.svg';
+import CornersIn from '@phosphor/corners-in.svg';
+import CornersOut from '@phosphor/corners-out.svg';
import ThreeDots from '@phosphor/dots-three.svg';
import MathIcon from '@phosphor/function.svg';
import Grid from '@phosphor/grid-four.svg';
@@ -47,6 +55,7 @@ import TextT from '@phosphor/text-t.svg';
import TextUnderline from '@phosphor/text-underline.svg';
import { Button, Dropdown, Hotkey, SingleSelectCheck } from '@ui';
import {
+ $getSelection,
COMMAND_PRIORITY_LOW,
FOCUS_COMMAND,
FORMAT_TEXT_COMMAND,
@@ -395,6 +404,18 @@ export function FormatTools(props: { withinPopup?: boolean }) {
currentEditor.dispatchCommand(TRY_INSERT_EQUATION_COMMAND, undefined);
}
+ function handleMergeCells() {
+ editor()?.update(() => {
+ const lexicalSelection = $getSelection();
+ if (!$isTableSelection(lexicalSelection)) return;
+ $mergeCells(lexicalSelection.getNodes().filter($isTableCellNode));
+ });
+ }
+
+ function handleSplitCell() {
+ editor()?.update(() => $unmergeCell());
+ }
+
createEffect(() => {
const editor_ = editor();
if (editor_ !== undefined) {
@@ -781,6 +802,32 @@ export function FormatTools(props: { withinPopup?: boolean }) {
component={selection()?.hasLinks ? BrokenLinkIcon : LinkIcon}
/>
</Button>
+ <Show when={selection()?.onMergableCells}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ tooltip="Merge cells"
+ onClick={handleMergeCells}
+ disabled={buttonIsDisabled()}
+ >
+ <CornersIn />
+ </Button>
+ </Show>
+ <Show when={selection()?.onSplittableCells}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ tooltip="Split cell"
+ onClick={handleSplitCell}
+ disabled={buttonIsDisabled()}
+ >
+ <CornersOut />
+ </Button>
+ </Show>
</Show>
<Show when={ENABLE_MARKDOWN_COMMENTS && canComment()}>
<Button
diff --git a/apps/web/src/features/block-md/component/MarkdownEditor.tsx b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
index 49322cf41e..c5fa91a98c 100644
--- a/apps/web/src/features/block-md/component/MarkdownEditor.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownEditor.tsx
@@ -23,18 +23,18 @@ import { ActionMenu } from '@core/component/LexicalMarkdown/component/menu/Actio
import { EmojiMenu } from '@core/component/LexicalMarkdown/component/menu/EmojiMenu';
import { FloatingEquationMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingEquationMenu';
import { FloatingLinkMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingLinkMenu';
+import { FloatingTableMenu } from '@core/component/LexicalMarkdown/component/menu/FloatingTableMenu';
import { GenerateMenu } from '@core/component/LexicalMarkdown/component/menu/GenerateMenu';
import { MentionsMenu } from '@core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu';
import { SnippetsMenu } from '@core/component/LexicalMarkdown/component/menu/SnippetsMenu';
-import TableActionMenu, {
- anchorElemRefSignal,
- menuButtonRefSignal,
- tableCellNodeKeySignal,
-} from '@core/component/LexicalMarkdown/component/menu/TableActionMenu';
import { TagsMenu } from '@core/component/LexicalMarkdown/component/menu/TagsMenu';
import { DraggableBlockMenu } from '@core/component/LexicalMarkdown/component/misc/DraggableBlockMenu';
import { DragInsertIndicator } from '@core/component/LexicalMarkdown/component/misc/DragInsertIndicator';
import { TableCellResizer } from '@core/component/LexicalMarkdown/component/misc/TableCellResizer';
+import { TableDeleteButtons } from '@core/component/LexicalMarkdown/component/misc/TableDeleteButtons';
+import { TableInsertButton } from '@core/component/LexicalMarkdown/component/misc/TableInsertButton';
+import { TableMoveHandle } from '@core/component/LexicalMarkdown/component/misc/TableMoveHandle';
+import { TableSelectionActionBar } from '@core/component/LexicalMarkdown/component/misc/TableSelectionActionBar';
import {
getErrorDescription,
MarkdownEditorErrors,
@@ -59,14 +59,15 @@ import {
generatePlugin,
horizontalRulePlugin,
keyboardShortcutsPlugin,
+ listToTablePlugin,
markdownPastePlugin,
mentionsPlugin,
pinnedPropertiesPlugin,
selectionDataPlugin,
tabIndentationPlugin,
- tableActionMenuPlugin,
tableCellResizerPlugin,
tablePlugin,
+ tableTouchSelectionPlugin,
tagsPlugin,
textPastePlugin,
wordcountPlugin,
@@ -143,6 +144,7 @@ import { IS_MAC } from '@core/constant/isMac';
import { useUserId } from '@core/context/user';
import { fileFolderDrop } from '@core/directive/fileFolderDrop';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { createMethodRegistration } from '@core/orchestrator';
import {
blockFileSignal,
@@ -508,16 +510,6 @@ export function MarkdownEditor(props: {
}
});
- const tableActionsMenuPluginProps = {
- menuButtonRef: menuButtonRefSignal.get,
- anchorElem: anchorElemRefSignal.get,
-
- tableCellNodeKey: tableCellNodeKeySignal.get,
- setTableCellNodeKey: (cellNodeKey: string | null) => {
- tableCellNodeKeySignal.set(cellNodeKey ?? undefined);
- },
- };
-
const peerIdValidator: Accessor<PeerIdValidator> = () => {
if (!IS_SYNC()) {
return createPeerIdValidator(() => undefined, false);
@@ -582,7 +574,7 @@ export function MarkdownEditor(props: {
})
)
.use(tableCellResizerPlugin())
- .use(tableActionMenuPlugin(tableActionsMenuPluginProps))
+ .use(tableTouchSelectionPlugin())
.use(
filePastePlugin({
onPasteFilesAndDirs: (fileEntries, directories) =>
@@ -688,6 +680,7 @@ export function MarkdownEditor(props: {
setAccessories: setAccessoryStore,
})
);
+ plugins.use(listToTablePlugin());
const [editorHasNoContent, setEditorHasNoContent] = createSignal(false);
@@ -1112,6 +1105,7 @@ export function MarkdownEditor(props: {
<FloatingMenuGroup>
<FloatingLinkMenu autoLinkMatchMode="common-tlds" />
<FloatingEquationMenu />
+ <FloatingTableMenu />
<MarkdownPopup
highlightLayerRef={highlightLayerRef() ?? editorContainerRef}
lexicalMapping={lexicalWrapper.mapping}
@@ -1135,8 +1129,17 @@ export function MarkdownEditor(props: {
</Show>
<Show when={canEdit()}>
+ {/* On touch devices the hover-driven controls are unusable */}
+ {isTouchDevice() ? (
+ <TableSelectionActionBar />
+ ) : (
+ <>
+ <TableInsertButton />
+ <TableDeleteButtons />
+ </>
+ )}
<TableCellResizer />
- <TableActionMenu anchorElem={editorContainerRef} cellMerge={true} />
+ <TableMoveHandle />
</Show>
<Show when={ENABLE_MARKDOWN_AI_GENERATE}>
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index 461a2c0998..e58eb2cfbe 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -12,8 +12,10 @@ import {
} from '@core/component/LexicalMarkdown/context/FloatingMenuContext';
import { LexicalWrapperContext } from '@core/component/LexicalMarkdown/context/LexicalWrapperContext';
import {
+ $getConvertibleListFromSelection,
autoRegister,
type EnhancedSelection,
+ LIST_TO_TABLE_COMMAND,
NODE_TRANSFORM,
registerRootEventListener,
} from '@core/component/LexicalMarkdown/plugins';
@@ -46,6 +48,7 @@ import { debouncedDependent } from '@core/util/debounce';
import { getScrollParentElement } from '@core/util/scrollParent';
import MacroGridLoader from '@icon/macro-grid-noise-loader-4.svg';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
+import GridIcon from '@phosphor/grid-four.svg';
import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
@@ -123,6 +126,9 @@ export function MarkdownPopup(props: {
const [isLoading, setIsLoading] = createSignal<boolean>(false);
const [isConverting, setIsConverting] = createSignal(false);
const [hasCheckboxes, setHasCheckboxes] = createSignal(false);
+ const [convertibleListKey, setConvertibleListKey] = createSignal<
+ string | null
+ >(null);
const { replaceOrInsertSplit } = useSplitLayout();
let markdownRootRef!: HTMLDivElement;
@@ -149,6 +155,9 @@ export function MarkdownPopup(props: {
setLocationCopied(false);
editor.read(() => {
setHasCheckboxes($canConvertCheckboxesToTasks());
+ setConvertibleListKey(
+ $getConvertibleListFromSelection()?.getKey() ?? null
+ );
});
})
);
@@ -422,6 +431,27 @@ export function MarkdownPopup(props: {
{isConverting() ? 'Converting...' : 'Tasks'}
</Button>
</Show>
+ <Show when={canEdit() && convertibleListKey()}>
+ {(listKey) => (
+ <Button
+ size="sm"
+ class="rounded-md"
+ depth={3}
+ variant="ghost"
+ tooltip="Convert list to table"
+ onClick={() => {
+ const converted = editor.dispatchCommand(
+ LIST_TO_TABLE_COMMAND,
+ listKey()
+ );
+ if (converted) setPopupVisible(false);
+ }}
+ >
+ <GridIcon class="size-4" />
+ Table
+ </Button>
+ )}
+ </Show>
<Button
size="sm"
class="px-2 text-xs rounded-md py-1.25"
@@ -636,7 +666,7 @@ export function MarkdownPopup(props: {
<ScopedPortal scope="local">
<div
ref={setAnchorRef}
- class="absolute pointer-events-none z-highlight-menu"
+ class="absolute pointer-events-none z-50"
style={{
left: `${anchorRefPosition().left}px`,
top: `${anchorRefPosition().top}px`,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx
new file mode 100644
index 0000000000..93ab65d2a5
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingTableMenu.tsx
@@ -0,0 +1,168 @@
+import clickOutside from '@core/directive/clickOutside';
+import { useCanEdit } from '@core/signal/permissions';
+import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
+import { INSERT_TABLE_COMMAND } from '@lexical/table';
+import { createCallback } from '@solid-primitives/rootless';
+import { Layer } from '@ui';
+import {
+ createEffect,
+ createSignal,
+ Index,
+ Show,
+ untrack,
+ useContext,
+} from 'solid-js';
+import {
+ createMenuOpenSignal,
+ MenuPriority,
+} from '../../context/FloatingMenuContext';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
+import { floatWithSelection } from '../../directive/floatWithSelection';
+import { tablePickerPlugin } from '../../plugins';
+import { useMenuKeyboardNavigation } from './useMenuKeyboardNavigation';
+
+false && floatWithSelection;
+false && clickOutside;
+
+const DEFAULT_ROWS = 3;
+const DEFAULT_COLS = 3;
+// The grid starts MIN_GRID_SIZE cells square and grows a cell past the
+// selection (Google Docs style) up to MAX_GRID_SIZE.
+const MIN_GRID_SIZE = 6;
+const MAX_GRID_SIZE = 12;
+
+/**
+ * Floating table size picker, opened via TRY_INSERT_TABLE_PICKER_COMMAND.
+ * Arrow keys resize the selection, Enter inserts, Escape cancels. The mouse
+ * can hover/click the grid as well. The editor keeps focus throughout.
+ */
+export function FloatingTableMenu() {
+ const canEdit = useCanEdit();
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const plugins = () => lexicalWrapper?.plugins;
+ const editor = () => lexicalWrapper?.editor;
+
+ const [menuOpen, setMenuOpen] = createMenuOpenSignal(
+ 'table-picker-menu',
+ MenuPriority.Low,
+ false
+ );
+ const [rows, setRows] = createSignal(DEFAULT_ROWS);
+ const [cols, setCols] = createSignal(DEFAULT_COLS);
+
+ const { isKeypressActive } = useIsKeyPressActive();
+
+ const resetMenu = () => {
+ setMenuOpen(false);
+ setRows(DEFAULT_ROWS);
+ setCols(DEFAULT_COLS);
+ };
+
+ const handleCreateTable = createCallback(() => {
+ if (menuOpen()) {
+ resetMenu();
+ return;
+ }
+ // Defer past the current event: the keystroke that triggered the picker
+ // is still mid-dispatch (microtask checkpoints run between document
+ // listeners), and opening synchronously would let the picker's own
+ // keydown listener treat that same Enter as a confirm.
+ setTimeout(() => setMenuOpen(true), 0);
+ });
+
+ const insertTable = (rows: number, cols: number) => {
+ editor()?.dispatchCommand(INSERT_TABLE_COMMAND, {
+ columns: `${cols}`,
+ rows: `${rows}`,
+ includeHeaders: false,
+ });
+ resetMenu();
+ };
+
+ createEffect(() => {
+ const currentPlugins = plugins();
+ if (!currentPlugins) return;
+
+ currentPlugins.useReactive(canEdit, () => {
+ if (!canEdit()) return;
+ return tablePickerPlugin({ onCreateTable: handleCreateTable });
+ });
+ });
+
+ const visibleRows = () =>
+ Math.max(MIN_GRID_SIZE, Math.min(MAX_GRID_SIZE, rows() + 1));
+ const visibleCols = () =>
+ Math.max(MIN_GRID_SIZE, Math.min(MAX_GRID_SIZE, cols() + 1));
+
+ useMenuKeyboardNavigation({
+ isActive: menuOpen,
+ onUp: () => setRows((r) => Math.max(1, r - 1)),
+ onDown: () => setRows((r) => Math.min(MAX_GRID_SIZE, r + 1)),
+ onLeft: () => setCols((c) => Math.max(1, c - 1)),
+ onRight: () => setCols((c) => Math.min(MAX_GRID_SIZE, c + 1)),
+ onSelect: () => insertTable(rows(), cols()),
+ onClose: () => {
+ resetMenu();
+ editor()?.focus();
+ },
+ onOtherKey: (e) => {
+ // Typing dismisses the picker and the key goes to the editor.
+ if (e.key.length === 1 || e.key === 'Backspace') {
+ resetMenu();
+ }
+ },
+ });
+
+ const handleCellHover = (rowIndex: number, colIndex: number) => {
+ if (isKeypressActive()) return;
+ setRows(rowIndex + 1);
+ setCols(colIndex + 1);
+ };
+
+ return (
+ <Show when={menuOpen()}>
+ {/* Same elevated surface as the other floating bars. */}
+ <Layer depth={2}>
+ <div
+ class="p-2 fixed bg-surface top-0 left-0 z-action-menu rounded-lg shadow-lg ring-1 ring-edge cursor-default select-none"
+ use:floatWithSelection={{
+ selection: untrack(() => window.getSelection()),
+ reactiveOnContainer: editor()?.getRootElement(),
+ }}
+ use:clickOutside={() => resetMenu()}
+ on:mousedown={(e) => e.preventDefault()}
+ >
+ <div class="flex flex-col items-center gap-1.5">
+ <div
+ class="grid gap-1"
+ style={{
+ 'grid-template-columns': `repeat(${visibleCols()}, 1fr)`,
+ }}
+ >
+ <Index each={Array.from({ length: visibleRows() })}>
+ {(_, rowIndex) => (
+ <Index each={Array.from({ length: visibleCols() })}>
+ {(_, colIndex) => (
+ <div
+ class="size-4 border border-edge rounded-xs transition-colors duration-100"
+ classList={{
+ 'bg-accent/20 border-accent/50':
+ rowIndex < rows() && colIndex < cols(),
+ }}
+ onMouseOver={() => handleCellHover(rowIndex, colIndex)}
+ onClick={() => insertTable(rowIndex + 1, colIndex + 1)}
+ />
+ )}
+ </Index>
+ )}
+ </Index>
+ </div>
+ <p class="text-xs text-ink-muted">
+ {rows()} &times; {cols()}
+ </p>
+ </div>
+ </div>
+ </Layer>
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TableActionMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TableActionMenu.tsx
deleted file mode 100644
index 4b2ffbcca4..0000000000
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/TableActionMenu.tsx
+++ /dev/null
@@ -1,463 +0,0 @@
-/**
- * Copyright (c) Meta Platforms, Inc. and affiliates.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- */
-
-import { mdStore } from '@block-md/signal/markdownBlockData';
-import { createBlockSignal } from '@core/block';
-import {
- $computeTableMapSkipCellCheck,
- $deleteTableColumnAtSelection,
- $deleteTableRowAtSelection,
- $getNodeTriplet,
- $getTableNodeFromLexicalNodeOrThrow,
- $insertTableColumnAtSelection,
- $insertTableRowAtSelection,
- $isTableCellNode,
- $isTableSelection,
- $unmergeCell,
- getTableElement,
- getTableObserverFromTableElement,
- type TableCellNode,
- type TableSelection,
-} from '@lexical/table';
-import ArrowLineDown from '@phosphor/arrow-line-down.svg';
-import ArrowLineLeft from '@phosphor/arrow-line-left.svg';
-import ArrowLineRight from '@phosphor/arrow-line-right.svg';
-import ArrowLineUp from '@phosphor/arrow-line-up.svg';
-import ArrowsIn from '@phosphor/arrows-in-line-horizontal.svg';
-import ArrowsOut from '@phosphor/arrows-out-line-horizontal.svg';
-import CaretDown from '@phosphor/caret-down.svg';
-import TrashCan from '@phosphor/trash-simple.svg';
-import X from '@phosphor/x.svg';
-import { createCallback } from '@solid-primitives/rootless';
-import { Dropdown, Tooltip } from '@ui';
-import type { ElementNode, LexicalEditor } from 'lexical';
-import {
- $createParagraphNode,
- $getSelection,
- $isElementNode,
- $isParagraphNode,
- $isRangeSelection,
- $isTextNode,
- $setSelection,
-} from 'lexical';
-import { type JSX, Show } from 'solid-js';
-import { Portal } from 'solid-js/web';
-import { nodeByKey } from '../../utils';
-
-// Helper Functions
-function computeSelectionCount(selection: TableSelection): {
- columns: number;
- rows: number;
-} {
- const selectionShape = selection.getShape();
- return {
- columns: selectionShape.toX - selectionShape.fromX + 1,
- rows: selectionShape.toY - selectionShape.fromY + 1,
- };
-}
-
-function $canUnmerge(): boolean {
- const selection = $getSelection();
-
- if (
- ($isRangeSelection(selection) && !selection.isCollapsed()) ||
- ($isTableSelection(selection) && !selection.anchor.is(selection.focus)) ||
- (!$isRangeSelection(selection) && !$isTableSelection(selection))
- ) {
- return false;
- }
-
- const [cell] = $getNodeTriplet(selection.anchor);
- return cell.__colSpan > 1 || cell.__rowSpan > 1;
-}
-
-function $cellContainsEmptyParagraph(cell: TableCellNode): boolean {
- if (cell.getChildrenSize() !== 1) {
- return false;
- }
-
- const firstChild = cell.getFirstChildOrThrow();
- return $isParagraphNode(firstChild) && firstChild.isEmpty();
-}
-
-function $selectLastDescendant(node: ElementNode): void {
- const lastDescendant = node.getLastDescendant();
-
- if ($isTextNode(lastDescendant)) {
- lastDescendant.select();
- } else if ($isElementNode(lastDescendant)) {
- lastDescendant.selectEnd();
- } else if (lastDescendant !== null) {
- lastDescendant.selectNext();
- }
-}
-
-function currentCellBackgroundColor(editor: LexicalEditor): null | string {
- return editor.read(() => {
- const selection = $getSelection();
-
- if ($isRangeSelection(selection) || $isTableSelection(selection)) {
- const [cell] = $getNodeTriplet(selection.anchor);
- if ($isTableCellNode(cell)) {
- return cell.getBackgroundColor();
- }
- }
-
- return null;
- });
-}
-
-// Signal Definitions
-export const menuButtonRefSignal = createBlockSignal<
- HTMLDivElement | undefined
->(undefined);
-export const anchorElemRefSignal = createBlockSignal<HTMLElement | undefined>(
- undefined
-);
-export const tableCellNodeKeySignal = createBlockSignal<string | undefined>(
- undefined
-);
-
-// Component Types
-type ActionMenuProps = Readonly<{
- tableCellNodeKey: string;
- cellMerge: boolean;
-}>;
-
-// Component Definitions
-function ActionMenu({
- tableCellNodeKey: initialTableCellNodeKey,
- cellMerge,
-}: ActionMenuProps) {
- const mdData = mdStore.get;
- const editor = () => mdData.editor;
-
- const [tableCellNodeKey, setTableCellNodeKey] = createBlockSignal<string>(
- initialTableCellNodeKey
- );
- const [selectionCounts, setSelectionCounts] = createBlockSignal<{
- rows: number;
- columns: number;
- }>({
- columns: 1,
- rows: 1,
- });
-
- const initialBackgroundColor = () => {
- const currentEditor = editor();
- return !currentEditor
- ? ''
- : currentCellBackgroundColor(currentEditor) || '';
- };
-
- const [_backgroundColor, _setBackgroundColor] = createBlockSignal<string>(
- initialBackgroundColor()
- );
-
- // State Helpers
- const canMergeCells = () => {
- return editor()?.read(() => {
- const selection = $getSelection();
- if ($isTableSelection(selection)) {
- const currentSelectionCounts = computeSelectionCount(selection);
- setSelectionCounts(currentSelectionCounts);
- return (
- currentSelectionCounts.columns > 1 || currentSelectionCounts.rows > 1
- );
- }
- return false;
- });
- };
-
- const canUnmergeCell = () => {
- return editor()?.read(() => $canUnmerge());
- };
-
- // Action Functions
- const clearTableSelection = createCallback(() => {
- const currentEditor = editor();
- if (!currentEditor) return;
-
- const tableCellNode = nodeByKey(currentEditor, tableCellNodeKey());
- if (!tableCellNode || !$isTableCellNode(tableCellNode)) return;
-
- currentEditor.update(() => {
- if (tableCellNode.isAttached()) {
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
- const tableElement = getTableElement(
- tableNode,
- currentEditor.getElementByKey(tableNode.getKey())
- );
-
- if (!tableElement) return;
-
- const tableObserver = getTableObserverFromTableElement(tableElement);
- if (tableObserver !== null) {
- tableObserver.$clearHighlight();
- }
-
- tableNode.markDirty();
- setTableCellNodeKey(tableCellNode.getLatest().getKey());
- }
-
- $setSelection(null);
- });
- });
-
- const mergeTableCellsAtSelection = () => {
- editor()?.update(() => {
- const selection = $getSelection();
-
- if ($isTableSelection(selection)) {
- const nodes = selection.getNodes();
- const tableCells = nodes.filter($isTableCellNode);
- if (tableCells.length === 0) return;
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCells[0]);
- const [gridMap] = $computeTableMapSkipCellCheck(tableNode, null, null);
-
- let minRow = Infinity;
- let maxRow = -Infinity;
- let minCol = Infinity;
- let maxCol = -Infinity;
- const processedCells = new Set();
-
- for (const row of gridMap) {
- for (const mapCell of row) {
- if (!mapCell || !mapCell.cell) continue;
-
- const cellKey = mapCell.cell.getKey();
- if (processedCells.has(cellKey)) continue;
-
- if (tableCells.some((cell) => cell.is(mapCell.cell))) {
- processedCells.add(cellKey);
-
- const cellStartRow = mapCell.startRow;
- const cellStartCol = mapCell.startColumn;
- const cellRowSpan = mapCell.cell.__rowSpan || 1;
- const cellColSpan = mapCell.cell.__colSpan || 1;
-
- minRow = Math.min(minRow, cellStartRow);
- maxRow = Math.max(maxRow, cellStartRow + cellRowSpan - 1);
- minCol = Math.min(minCol, cellStartCol);
- maxCol = Math.max(maxCol, cellStartCol + cellColSpan - 1);
- }
- }
- }
-
- if (minRow === Infinity || minCol === Infinity) return;
-
- const totalRowSpan = maxRow - minRow + 1;
- const totalColSpan = maxCol - minCol + 1;
- const targetCellMap = gridMap[minRow][minCol];
-
- if (!targetCellMap?.cell) return;
-
- const targetCell = targetCellMap.cell;
- targetCell.setColSpan(totalColSpan);
- targetCell.setRowSpan(totalRowSpan);
-
- const seenCells = new Set([targetCell.getKey()]);
-
- for (let row = minRow; row <= maxRow; row++) {
- for (let col = minCol; col <= maxCol; col++) {
- const mapCell = gridMap[row][col];
- if (!mapCell?.cell) continue;
-
- const currentCell = mapCell.cell;
- const key = currentCell.getKey();
-
- if (!seenCells.has(key)) {
- seenCells.add(key);
- const isEmpty = $cellContainsEmptyParagraph(currentCell);
-
- if (!isEmpty) {
- targetCell.append(...currentCell.getChildren());
- }
-
- currentCell.remove();
- }
- }
- }
-
- if (targetCell.getChildrenSize() === 0) {
- targetCell.append($createParagraphNode());
- }
-
- $selectLastDescendant(targetCell);
- }
- });
- };
-
- const unmergeTableCellsAtSelection = () => {
- editor()?.update(() => {
- $unmergeCell();
- });
- };
-
- const insertTableRowAtSelection = createCallback(
- (shouldInsertAfter: boolean) => {
- editor()?.update(() => {
- for (let i = 0; i < selectionCounts().rows; i++) {
- $insertTableRowAtSelection(shouldInsertAfter);
- }
- });
- }
- );
-
- const insertTableColumnAtSelection = createCallback(
- (shouldInsertAfter: boolean) => {
- editor()?.update(() => {
- for (let i = 0; i < selectionCounts().columns; i++) {
- $insertTableColumnAtSelection(shouldInsertAfter);
- }
- });
- }
- );
-
- const deleteTableRowAtSelection = createCallback(() => {
- editor()?.update(() => {
- $deleteTableRowAtSelection();
- });
- });
-
- const deleteTableAtSelection = createCallback(() => {
- const currentEditor = editor();
- if (!currentEditor) return;
-
- const tableCellNode = nodeByKey(currentEditor, tableCellNodeKey());
- if (!tableCellNode) return;
-
- currentEditor.update(() => {
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
- tableNode.remove();
- clearTableSelection();
- });
- });
-
- const deleteTableColumnAtSelection = createCallback(() => {
- editor()?.update(() => {
- $deleteTableColumnAtSelection();
- });
- });
-
- // Component Render
- return (
- <Dropdown placement="right-start">
- <Dropdown.Trigger class="dropdown-menu__trigger">
- <Tooltip label="Table Options">
- <div class="size-6 rounded-md p-0 bg-surface hover:bg-hover hover-transition-bg flex items-center justify-center">
- <CaretDown class="size-4" />
- </div>
- </Tooltip>
- </Dropdown.Trigger>
- <Dropdown.Content>
- <Show when={cellMerge && canMergeCells()}>
- <Dropdown.Group>
- <Dropdown.Item onSelect={() => mergeTableCellsAtSelection()}>
- <ArrowsIn class="size-4 shrink-0" />
- <span class="flex-1 truncate">Merge cells</span>
- </Dropdown.Item>
- </Dropdown.Group>
- </Show>
- <Show when={cellMerge && canUnmergeCell()}>
- <Dropdown.Group>
- <Dropdown.Item onSelect={() => unmergeTableCellsAtSelection()}>
- <ArrowsOut class="size-4 shrink-0" />
- <span class="flex-1 truncate">Unmerge cells</span>
- </Dropdown.Item>
- </Dropdown.Group>
- </Show>
-
- <Dropdown.Group>
- <Dropdown.Item onSelect={() => insertTableRowAtSelection(false)}>
- <ArrowLineUp class="size-4 shrink-0" />
- <span class="flex-1 truncate">
- {`Insert ${selectionCounts().rows === 1 ? 'row' : `${selectionCounts().rows} rows`} above`}
- </span>
- </Dropdown.Item>
- <Dropdown.Item onSelect={() => insertTableRowAtSelection(true)}>
- <ArrowLineDown class="size-4 shrink-0" />
- <span class="flex-1 truncate">
- {`Insert ${selectionCounts().rows === 1 ? 'row' : `${selectionCounts().rows} rows`} below`}
- </span>
- </Dropdown.Item>
- </Dropdown.Group>
-
- <Dropdown.Group>
- <Dropdown.Item onSelect={() => insertTableColumnAtSelection(false)}>
- <ArrowLineLeft class="size-4 shrink-0" />
- <span class="flex-1 truncate">
- {`Insert ${selectionCounts().columns === 1 ? 'column' : `${selectionCounts().columns} columns`} left`}
- </span>
- </Dropdown.Item>
- <Dropdown.Item onSelect={() => insertTableColumnAtSelection(true)}>
- <ArrowLineRight class="size-4 shrink-0" />
- <span class="flex-1 truncate">
- {`Insert ${selectionCounts().columns === 1 ? 'column' : `${selectionCounts().columns} columns`} right`}
- </span>
- </Dropdown.Item>
- </Dropdown.Group>
-
- <Dropdown.Group>
- <Dropdown.Item onSelect={() => deleteTableColumnAtSelection()}>
- <X class="size-4 shrink-0" />
- <span class="flex-1 truncate">Delete column</span>
- </Dropdown.Item>
- <Dropdown.Item onSelect={() => deleteTableRowAtSelection()}>
- <X class="size-4 shrink-0" />
- <span class="flex-1 truncate">Delete row</span>
- </Dropdown.Item>
- <Dropdown.Item onSelect={() => deleteTableAtSelection()}>
- <TrashCan class="size-4 shrink-0 text-failure" />
- <span class="flex-1 truncate">Delete table</span>
- </Dropdown.Item>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
-
-function ActionMenuContainer({
- cellMerge,
-}: {
- cellMerge: boolean;
-}): JSX.Element {
- const tableCellNodeKey = tableCellNodeKeySignal.get;
-
- return (
- <div
- ref={menuButtonRefSignal.set}
- class="table-cell-action-button-container--inactive"
- >
- <Show when={tableCellNodeKey()}>
- <div class="size-4 rounded-md p-0">
- <ActionMenu
- tableCellNodeKey={tableCellNodeKey()!}
- cellMerge={cellMerge}
- />
- </div>
- </Show>
- </div>
- );
-}
-
-export default function TableActionMenu({
- anchorElem = document.body,
- cellMerge = false,
-}: {
- anchorElem?: HTMLElement;
- cellMerge?: boolean;
-}) {
- anchorElemRefSignal.set(anchorElem);
-
- return (
- <Portal mount={anchorElem}>
- <ActionMenuContainer cellMerge={cellMerge} />
- </Portal>
- );
-}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
index a27716e566..b16aebbb9c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableCellResizer.tsx
@@ -1,426 +1,297 @@
+/**
+ * @file Column resize handles for tables. On pointer devices an invisible
+ * strip along the hovered cell's right edge shows a line on hover and drags
+ * that column border. Touch has no handle at all: a horizontal swipe that
+ * starts near a column border resizes it. The first touchmove decides the
+ * gesture — mostly-vertical movement is left to the browser as a scroll,
+ * and a still finger disarms before the long-press cell selection fires.
+ * The new width applies live while dragging, with the pointer captured so
+ * the drag survives leaving the editor; Escape/pointercancel restores the
+ * pre-drag width.
+ */
import { mdStore } from '@block-md/signal/markdownBlockData';
-import { createBlockSignal } from '@core/block';
import { ScopedPortal } from '@core/component/ScopedPortal';
-import type { TableCellNode, TableDOMCell, TableMapType } from '@lexical/table';
-import {
- $computeTableMapSkipCellCheck,
- $getTableNodeFromLexicalNodeOrThrow,
- $getTableRowIndexFromTableCellNode,
- $isTableCellNode,
- $isTableRowNode,
- getDOMCellFromTarget,
- getTableElement,
-} from '@lexical/table';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { getDOMCellFromTarget } from '@lexical/table';
import { calculateZoomLevel } from '@lexical/utils';
-import { createCallback } from '@solid-primitives/rootless';
-import { $getNearestNodeFromDOMNode, isHTMLElement } from 'lexical';
-import { createMemo, createSignal, type JSX, onCleanup, Show } from 'solid-js';
+import { createMemo, createSignal, onCleanup, Show } from 'solid-js';
import { registerEditorWidthObserver } from '../../plugins/shared/utils';
-
-// Constants
-const MIN_ROW_HEIGHT = 35;
-export const MIN_COLUMN_WIDTH = 120;
-
-// Types
-type PointerPosition = {
- x: number;
- y: number;
-};
-
-type PointerDraggingDirection = 'right' | 'bottom';
+import {
+ $applyResizeDrag,
+ $captureResizeDrag,
+ $revertResizeDrag,
+ type ResizeEdge,
+} from '../../plugins/tables/tableCellResize';
+import { createLayoutTick } from './createLayoutTick';
+
+// Width of the pointer-device hit strip along a cell edge.
+const HIT_ZONE_PX = 9;
+// Touch counts as starting on a border within this distance of it.
+const TOUCH_EDGE_PX = 12;
+// A still finger is a long-press (cell selection), not a resize; disarm
+// before tableTouchSelection's 400ms long-press fires.
+const TOUCH_ARM_TIMEOUT_MS = 350;
+
+// Set while dragging; names the border of the active cell being dragged.
+// Module scope: at most one drag runs across all editors, and the other
+// floating table controls (insert/delete buttons) hide themselves on it —
+// their hover tracking freezes while the resize captures the pointer.
+const [dragEdge, setDragEdge] = createSignal<ResizeEdge>();
+export const tableColumnResizeEdge = dragEdge;
export function TableCellResizer() {
- // State and references
const mdData = mdStore.get;
const editor = () => mdData.editor;
- let targetRef: HTMLElement | undefined;
- let resizerRef: HTMLDivElement | undefined;
- let tableRectRef: DOMRect | undefined;
- let pointerStartPosRef: PointerPosition | undefined;
-
- const [pointerCurrentPos, setPointerCurrentPos] = createBlockSignal<
- PointerPosition | undefined
- >(undefined);
-
- const [activeCell, setActiveCell] = createBlockSignal<
- TableDOMCell | undefined
- >(undefined);
-
- const [draggingDirection, setDraggingDirection] = createBlockSignal<
- PointerDraggingDirection | undefined
- >(undefined);
-
- // Helper functions
- const resetState = createCallback(() => {
- setActiveCell(undefined);
- setDraggingDirection(undefined);
- targetRef = undefined;
- pointerStartPosRef = undefined;
- tableRectRef = undefined;
- });
-
- const isHeightChanging = (direction: PointerDraggingDirection) => {
- return direction === 'bottom';
- };
-
- const getCellNodeHeight = (cell: TableCellNode): number | undefined => {
- const domCellNode = editor()?.getElementByKey(cell.getKey());
- return domCellNode?.clientHeight;
- };
+ // Cell whose border carries the handle: the hovered cell on pointer
+ // devices, the touched cell during a touch drag.
+ const [activeCellElem, setActiveCellElem] = createSignal<HTMLElement>();
+ const { layoutTick, bumpLayout } = createLayoutTick();
- const getCellColumnIndex = (
- tableCellNode: TableCellNode,
- tableMap: TableMapType
+ const startResize = (
+ cellElem: HTMLElement,
+ edge: ResizeEdge,
+ down: { pointerId: number; clientX: number; pointerType: string },
+ captureTarget: HTMLElement
) => {
- for (let row = 0; row < tableMap.length; row++) {
- for (let column = 0; column < tableMap[row].length; column++) {
- if (tableMap[row][column].cell === tableCellNode) {
- return column;
- }
- }
- }
- };
-
- // Update handlers
- const updateRowHeight = createCallback((heightChange: number) => {
- const currentActiveCell = activeCell();
- if (!currentActiveCell) {
- throw new Error('TableCellResizer: Expected active cell.');
- }
-
- editor()?.update(
- () => {
- const tableCellNode = $getNearestNodeFromDOMNode(
- currentActiveCell.elem
- );
- if (!$isTableCellNode(tableCellNode)) {
- throw new Error('TableCellResizer: Table cell node not found.');
- }
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
- const baseRowIndex = $getTableRowIndexFromTableCellNode(tableCellNode);
- const tableRows = tableNode.getChildren();
-
- // Determine if this is a full row merge by checking colspan
- const isFullRowMerge =
- tableCellNode.getColSpan() === tableNode.getColumnCount();
-
- // For full row merges, apply to first row. For partial merges, apply to last row
- const tableRowIndex = isFullRowMerge
- ? baseRowIndex
- : baseRowIndex + tableCellNode.getRowSpan() - 1;
-
- if (tableRowIndex >= tableRows.length || tableRowIndex < 0) {
- throw new Error('Expected table cell to be inside of table row.');
- }
-
- const tableRow = tableRows[tableRowIndex];
- if (!$isTableRowNode(tableRow)) {
- throw new Error('Expected table row');
- }
-
- let height = tableRow.getHeight();
- if (height === undefined) {
- const rowCells = tableRow.getChildren<TableCellNode>();
- height = Math.min(
- ...rowCells.map((cell) => getCellNodeHeight(cell) ?? Infinity)
- );
- }
-
- const newHeight = Math.max(height + heightChange, MIN_ROW_HEIGHT);
- tableRow.setHeight(newHeight);
- },
- { tag: 'skip-scroll-into-view' }
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ const zoom = calculateZoomLevel(cellElem);
+ const drag = currentEditor.read(() =>
+ $captureResizeDrag(currentEditor, cellElem, edge, zoom)
);
- });
-
- const updateColumnWidth = createCallback((widthChange: number) => {
- const currentActiveCell = activeCell();
- if (!currentActiveCell) {
- throw new Error('TableCellResizer: Expected active cell.');
- }
+ if (!drag) return;
- editor()?.update(
- () => {
- const tableCellNode = $getNearestNodeFromDOMNode(
- currentActiveCell.elem
- );
- if (!$isTableCellNode(tableCellNode)) {
- throw new Error('TableCellResizer: Table cell node not found.');
- }
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
- const [tableMap] = $computeTableMapSkipCellCheck(tableNode, null, null);
- const columnIndex = getCellColumnIndex(tableCellNode, tableMap);
-
- if (columnIndex === undefined) {
- throw new Error('TableCellResizer: Table column not found.');
- }
-
- const colWidths = tableNode.getColWidths();
- if (!colWidths) {
- return;
- }
-
- const width = colWidths[columnIndex];
- if (width === undefined) {
- return;
- }
-
- const newColWidths = [...colWidths];
- const newWidth = Math.max(width + widthChange, MIN_COLUMN_WIDTH);
- newColWidths[columnIndex] = newWidth;
- tableNode.setColWidths(newColWidths);
- },
- { tag: 'skip-scroll-into-view' }
- );
- });
-
- // Event handlers
- const pointerUpHandler = createCallback(
- (direction: PointerDraggingDirection) => {
- const handler = (event: PointerEvent) => {
- event.preventDefault();
- event.stopPropagation();
-
- const currentActiveCell = activeCell();
- if (!currentActiveCell) {
- throw new Error('TableCellResizer: Expected active cell.');
- }
-
- if (pointerStartPosRef) {
- const { x, y } = pointerStartPosRef;
- if (!currentActiveCell) {
- return;
- }
-
- const zoom = calculateZoomLevel(event.target as Element);
- if (isHeightChanging(direction)) {
- const heightChange = (event.clientY - y) / zoom;
- updateRowHeight(heightChange);
- } else {
- const widthChange = (event.clientX - x) / zoom;
- updateColumnWidth(widthChange);
- }
-
- resetState();
- document.removeEventListener('pointerup', handler);
- }
- };
- return handler;
+ const isTouch = down.pointerType === 'touch';
+ try {
+ captureTarget.setPointerCapture(down.pointerId);
+ } catch {
+ // The pointer ended between the down event and here.
+ return;
}
- );
-
- const toggleResize = createCallback(
- (direction: PointerDraggingDirection): ((event: PointerEvent) => void) =>
- (event) => {
- event.preventDefault();
- event.stopPropagation();
+ setActiveCellElem(cellElem);
+ setDragEdge(edge);
+
+ const previousCursor = document.body.style.cursor;
+ if (!isTouch) document.body.style.cursor = 'col-resize';
+
+ let frame = 0;
+ let delta = 0;
+ // The first live update pushes one history entry; the rest merge into
+ // it so the whole drag undoes in a single step.
+ let pushedHistory = false;
+
+ const applyDelta = () => {
+ frame = 0;
+ const tag = pushedHistory
+ ? ['skip-scroll-into-view', 'history-merge']
+ : ['skip-scroll-into-view'];
+ pushedHistory = true;
+ currentEditor.update(() => $applyResizeDrag(drag, delta), { tag });
+ };
- const currentActiveCell = activeCell();
- if (!currentActiveCell) {
- throw new Error('TableCellResizer: Expected active cell.');
- }
+ const onPointerMove = (move: PointerEvent) => {
+ if (move.pointerId !== down.pointerId) return;
+ move.preventDefault();
+ delta = (move.clientX - down.clientX) / zoom;
+ if (!frame) frame = requestAnimationFrame(applyDelta);
+ };
- pointerStartPosRef = {
- x: event.clientX,
- y: event.clientY,
- };
+ // pointermove can't stop the page from panning; only preventDefault
+ // from a non-passive touchmove listener can.
+ const blockScroll = (event: TouchEvent) => event.preventDefault();
- setPointerCurrentPos(pointerStartPosRef);
- setDraggingDirection(direction);
- document.addEventListener('pointerup', pointerUpHandler(direction));
+ const onPointerUp = (up: PointerEvent) => {
+ if (up.pointerId !== down.pointerId) return;
+ if (frame) {
+ cancelAnimationFrame(frame);
+ applyDelta();
}
- );
-
- const onPointerMove = (event: PointerEvent) => {
- const target = event.target;
- if (!isHTMLElement(target)) {
- return;
- }
+ cleanup();
+ };
+ const cancelDrag = () => {
+ if (pushedHistory) {
+ currentEditor.update(() => $revertResizeDrag(drag), {
+ tag: ['skip-scroll-into-view', 'history-merge'],
+ });
+ }
+ cleanup();
+ };
+ const onPointerCancel = (event: PointerEvent) => {
+ if (event.pointerId !== down.pointerId) return;
+ cancelDrag();
+ };
+ const onKeyDown = (keyEvent: KeyboardEvent) => {
+ if (keyEvent.key === 'Escape') cancelDrag();
+ };
- if (draggingDirection()) {
- event.preventDefault();
- event.stopPropagation();
- setPointerCurrentPos({
- x: event.clientX,
- y: event.clientY,
- });
- return;
- }
+ const cleanup = () => {
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ if (captureTarget.hasPointerCapture(down.pointerId)) {
+ captureTarget.releasePointerCapture(down.pointerId);
+ }
+ document.removeEventListener('pointermove', onPointerMove);
+ document.removeEventListener('pointerup', onPointerUp);
+ document.removeEventListener('pointercancel', onPointerCancel);
+ document.removeEventListener('touchmove', blockScroll);
+ document.removeEventListener('keydown', onKeyDown);
+ document.body.style.cursor = previousCursor;
+ setDragEdge(undefined);
+ if (isTouch) setActiveCellElem(undefined);
+ };
- if (resizerRef && resizerRef.contains(target)) {
- return;
+ // Document-level listeners see the captured events by bubbling, so one
+ // set serves both the desktop strip and the touch gesture.
+ document.addEventListener('pointermove', onPointerMove);
+ document.addEventListener('pointerup', onPointerUp);
+ document.addEventListener('pointercancel', onPointerCancel);
+ if (isTouch) {
+ document.addEventListener('touchmove', blockScroll, { passive: false });
}
+ document.addEventListener('keydown', onKeyDown);
+ };
- if (targetRef !== target) {
- targetRef = target;
- const cell = getDOMCellFromTarget(target);
-
- if (cell && activeCell() !== cell) {
- editor()?.read(() => {
- const tableCellNode = $getNearestNodeFromDOMNode(cell.elem);
- if (!tableCellNode) {
- throw new Error('TableCellResizer: Table cell node not found.');
- }
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
- const tableElement = getTableElement(
- tableNode,
- editor()?.getElementByKey(tableNode.getKey()) ?? null
- );
-
- if (!tableElement) {
- throw new Error('TableCellResizer: Table element not found.');
- }
-
- targetRef = target as HTMLElement;
- tableRectRef = tableElement.getBoundingClientRect();
- setActiveCell(cell);
- });
- } else if (!cell) {
- resetState();
- }
- }
+ // Hover activation (mouse/pen). Touch never hovers; its activation is the
+ // swipe gesture below.
+ let lastHoverTarget: EventTarget | null = null;
+ const onRootPointerMove = (event: PointerEvent) => {
+ if (event.pointerType === 'touch' || dragEdge()) return;
+ if (event.target === lastHoverTarget) return;
+ lastHoverTarget = event.target;
+ const cell =
+ event.target instanceof Node ? getDOMCellFromTarget(event.target) : null;
+ setActiveCellElem(cell?.elem);
};
- const onPointerDown = (event: PointerEvent) => {
- const isTouchEvent = event.pointerType === 'touch';
- if (isTouchEvent) {
- onPointerMove(event);
- }
+ const onRootPointerDown = (down: PointerEvent) => {
+ if (down.pointerType !== 'touch' || !down.isPrimary) return;
+ if (!editor()?.isEditable() || dragEdge()) return;
+ const cell =
+ down.target instanceof Node ? getDOMCellFromTarget(down.target) : null;
+ if (!cell) return;
+ const rect = cell.elem.getBoundingClientRect();
+ const edge: ResizeEdge | undefined =
+ Math.abs(down.clientX - rect.right) <= TOUCH_EDGE_PX
+ ? 'right'
+ : Math.abs(down.clientX - rect.left) <= TOUCH_EDGE_PX
+ ? 'left'
+ : undefined;
+ if (!edge) return;
+
+ const { pointerId, clientX: startX, clientY: startY, pointerType } = down;
+ let timer = 0;
+ const cancelArmed = () => {
+ window.clearTimeout(timer);
+ document.removeEventListener('touchmove', onArmedTouchMove);
+ document.removeEventListener('pointerup', cancelArmed);
+ document.removeEventListener('pointercancel', cancelArmed);
+ };
+ // Deciding on the first touchmove (while it is still cancelable) is what
+ // lets a horizontal swipe beat the browser's pan gesture.
+ const onArmedTouchMove = (event: TouchEvent) => {
+ const touch = event.touches[0];
+ if (!touch) return;
+ cancelArmed();
+ const dx = touch.clientX - startX;
+ const dy = touch.clientY - startY;
+ // Mostly-vertical first movement is a scroll; leave it to the browser.
+ if (Math.abs(dx) <= Math.abs(dy)) return;
+ event.preventDefault();
+ startResize(
+ cell.elem,
+ edge,
+ { pointerId, clientX: startX, pointerType },
+ cell.elem
+ );
+ };
+ timer = window.setTimeout(cancelArmed, TOUCH_ARM_TIMEOUT_MS);
+ document.addEventListener('touchmove', onArmedTouchMove, {
+ passive: false,
+ });
+ document.addEventListener('pointerup', cancelArmed);
+ document.addEventListener('pointercancel', cancelArmed);
};
- // Event listeners setup
- const resizerContainer = resizerRef;
- resizerContainer?.addEventListener('pointermove', onPointerMove, {
- capture: true,
+ let cleanupRoot: (() => void) | null = null;
+ const removeRootListener = editor()?.registerRootListener((root) => {
+ cleanupRoot?.();
+ cleanupRoot = null;
+ if (!root) return;
+ root.addEventListener('pointermove', onRootPointerMove);
+ root.addEventListener('pointerdown', onRootPointerDown);
+ cleanupRoot = () => {
+ root.removeEventListener('pointermove', onRootPointerMove);
+ root.removeEventListener('pointerdown', onRootPointerDown);
+ };
});
- const removeRootListener = editor()?.registerRootListener(
- (rootElement, prevRootElement) => {
- prevRootElement?.removeEventListener('pointermove', onPointerMove);
- prevRootElement?.removeEventListener('pointerdown', onPointerDown);
- rootElement?.addEventListener('pointermove', onPointerMove);
- rootElement?.addEventListener('pointerdown', onPointerDown);
- }
- );
+ const removeUpdateListener = editor()?.registerUpdateListener(bumpLayout);
- const [editorWidth, setEditorWidth] = createSignal(Infinity);
- let cleanUpWidthObserver = () => {};
- if (editor()) {
- cleanUpWidthObserver = registerEditorWidthObserver(editor()!, (width) => {
- setEditorWidth(width);
- });
+ let cleanupWidthObserver = () => {};
+ const widthObserverEditor = editor();
+ if (widthObserverEditor) {
+ cleanupWidthObserver = registerEditorWidthObserver(
+ widthObserverEditor,
+ bumpLayout
+ );
}
onCleanup(() => {
removeRootListener?.();
- cleanUpWidthObserver();
- resizerContainer?.removeEventListener('pointermove', onPointerMove);
+ removeUpdateListener?.();
+ cleanupRoot?.();
+ cleanupWidthObserver();
});
- // UI related
- const getResizers = createMemo(() => {
- const currentActiveCell = activeCell();
- editorWidth(); // Make this memo reactive on editor width change.
- const rootEl = editor()?.getRootElement();
- // let rootRect = rootEl ? containedClientRect(rootEl!) : null;
- // let containerRect = rootEl ? getContainerRect(rootEl) : null;
- let rootRect = rootEl ? rootEl.getBoundingClientRect() : null;
- if (currentActiveCell) {
- // const cellRect = containedClientRect(currentActiveCell.elem);
- const cellRect = currentActiveCell.elem.getBoundingClientRect();
- const zoneWidth = 5; // Pixel width of the zone where you can drag the edge
-
- const styles: Record<string, JSX.CSSProperties> = {
- bottom: {
- 'background-color': 'transparent',
- cursor: 'row-resize',
- height: `${zoneWidth}px`,
- left: `${cellRect.left}px`,
- top: `${cellRect.top + cellRect.height - zoneWidth / 2}px`,
- width: `${cellRect.width}px`,
- position: 'fixed', // Use fixed positioning based on viewport coordinates
- },
- right: {
- 'background-color': 'transparent',
- cursor: 'col-resize',
- height: `${cellRect.height}px`,
- left: `${cellRect.left + cellRect.width - zoneWidth / 2}px`,
- top: `${cellRect.top}px`,
- width: `${zoneWidth}px`,
- position: 'fixed', // Use fixed positioning based on viewport coordinates
- },
- };
-
- const tableRect = tableRectRef;
- const currentDraggingDirection = draggingDirection();
- const currentPointerPos = pointerCurrentPos();
-
- if (currentDraggingDirection && currentPointerPos && tableRect) {
- const compensatedMousePos = {
- x: currentPointerPos.x,
- y: currentPointerPos.y,
- };
- if (isHeightChanging(currentDraggingDirection)) {
- styles[currentDraggingDirection].left = `${tableRect.left}px`;
- styles[currentDraggingDirection].top = `${compensatedMousePos.y}px`;
- styles[currentDraggingDirection].height = '3px';
- styles[currentDraggingDirection].width = `${tableRect.width}px`;
-
- // Do not let the resizer go outside of the root element;
- if (rootRect) {
- styles[currentDraggingDirection].left =
- `${Math.max(rootRect.left, tableRect.left)}px`;
- styles[currentDraggingDirection].width =
- `${Math.min(rootRect.width, tableRect.width)}px`;
- }
- } else {
- styles[currentDraggingDirection].top = `${tableRect.top}px`;
- styles[currentDraggingDirection].left = `${compensatedMousePos.x}px`;
- styles[currentDraggingDirection].width = '3px';
- styles[currentDraggingDirection].height = `${tableRect.height}px`;
- }
-
- styles[currentDraggingDirection]['background-color'] =
- 'var(--color-accent-bg)';
- }
+ const cellRect = createMemo(() => {
+ layoutTick();
+ const elem = activeCellElem();
+ if (!elem?.isConnected) return;
+ return elem.getBoundingClientRect();
+ });
- return styles;
- }
+ const onStripPointerDown = (down: PointerEvent) => {
+ if (down.pointerType === 'mouse' && down.button !== 0) return;
+ const cellElem = activeCellElem();
+ const strip = down.currentTarget;
+ if (!cellElem || !(strip instanceof HTMLElement)) return;
+ down.preventDefault();
+ down.stopPropagation();
+ startResize(cellElem, 'right', down, strip);
+ };
- return {
- bottom: undefined,
- left: undefined,
- right: undefined,
- top: undefined,
- };
- });
+ // The strip doubles as the drag indicator on touch, pinned to whichever
+ // border is being dragged.
+ const stripX = (rect: DOMRect) =>
+ dragEdge() === 'left' ? rect.left : rect.right;
return (
- <Show when={activeCell()}>
- <ScopedPortal scope="split">
- <div ref={resizerRef}>
- <Show when={getResizers().right}>
+ <Show when={cellRect()}>
+ {(rect) => (
+ <ScopedPortal scope="split">
+ <Show when={!isTouchDevice() || dragEdge()}>
<div
- class="touch-none pointer-course"
+ class="group fixed z-20 flex cursor-col-resize touch-none justify-center"
style={{
- ...(getResizers().right || {}),
+ left: `${stripX(rect()) - HIT_ZONE_PX / 2}px`,
+ top: `${rect().top}px`,
+ width: `${HIT_ZONE_PX}px`,
+ height: `${rect().height}px`,
}}
- onPointerDown={toggleResize('right')}
- />
- </Show>
- <Show when={getResizers().bottom}>
- <div
- class="touch-none pointer-course"
- style={getResizers().bottom || undefined}
- onPointerDown={toggleResize('bottom')}
- />
+ onPointerDown={onStripPointerDown}
+ >
+ <div
+ class="h-full w-[3px] bg-accent transition-opacity"
+ classList={{
+ 'opacity-100': !!dragEdge(),
+ 'opacity-0 group-hover:opacity-70': !dragEdge(),
+ }}
+ />
+ </div>
</Show>
- </div>
- </ScopedPortal>
+ </ScopedPortal>
+ )}
</Show>
);
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx
new file mode 100644
index 0000000000..653e827988
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableDeleteButtons.tsx
@@ -0,0 +1,236 @@
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import { ScopedPortal } from '@core/component/ScopedPortal';
+import {
+ $deleteTableColumnAtSelection,
+ $deleteTableRowAtSelection,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $isTableCellNode,
+ getDOMCellFromTarget,
+} from '@lexical/table';
+import TrashIcon from '@phosphor/trash-simple.svg';
+import { createCallback } from '@solid-primitives/rootless';
+import { Layer } from '@ui';
+import { $getNearestNodeFromDOMNode, isHTMLElement } from 'lexical';
+import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import { tableColumnResizeEdge } from './TableCellResizer';
+
+type DeleteTarget = {
+ cellElem: HTMLElement;
+ cellLeft: number;
+ cellRight: number;
+ cellTop: number;
+ cellBottom: number;
+ tableTop: number;
+ tableBottom: number;
+ // Clamped to the visible span of the scroll wrapper.
+ tableLeft: number;
+ tableRight: number;
+ // Pointer proximity to the border each button sits on.
+ nearTop: boolean;
+ nearLeft: boolean;
+};
+
+// How far (px) inside the table's top/left border the pointer still counts
+// as hovering that border.
+const EDGE_PROXIMITY_PX = 20;
+
+const BUTTON_CLASS =
+ 'fixed z-20 flex size-5 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border border-edge bg-surface text-ink-muted shadow-sm hover:border-failure hover:bg-failure hover:text-surface';
+
+export function TableDeleteButtons() {
+ const mdData = mdStore.get;
+ const editor = () => mdData.editor;
+
+ const [target, setTarget] = createSignal<DeleteTarget>();
+ const [hovered, setHovered] = createSignal<'row' | 'column' | 'table'>();
+
+ const clear = () => {
+ if (!hovered()) setTarget(undefined);
+ };
+
+ // A column resize captures the pointer, so no pointermove would ever
+ // clear stale buttons; hide them for the duration of the drag.
+ createEffect(() => {
+ if (tableColumnResizeEdge()) {
+ setHovered(undefined);
+ setTarget(undefined);
+ }
+ });
+
+ const onPointerMove = createCallback((event: PointerEvent) => {
+ if (tableColumnResizeEdge()) return;
+ const eventTarget = event.target;
+ if (!editor() || !isHTMLElement(eventTarget)) return;
+
+ const domCell = getDOMCellFromTarget(eventTarget);
+ if (!domCell) return clear();
+
+ const tableElem = domCell.elem.closest('table');
+ if (!tableElem) return clear();
+
+ const rect = domCell.elem.getBoundingClientRect();
+ const tableRect = tableElem.getBoundingClientRect();
+ const wrapperRect = tableElem
+ .closest('.md-table-scrollable-wrapper')
+ ?.getBoundingClientRect();
+
+ const tableLeft = Math.max(tableRect.left, wrapperRect?.left ?? -Infinity);
+ const nearTop = event.clientY - tableRect.top <= EDGE_PROXIMITY_PX;
+ const nearLeft = event.clientX - tableLeft <= EDGE_PROXIMITY_PX;
+ if (!nearTop && !nearLeft) return clear();
+
+ setTarget({
+ cellElem: domCell.elem,
+ cellLeft: rect.left,
+ cellRight: rect.right,
+ cellTop: rect.top,
+ cellBottom: rect.bottom,
+ tableTop: tableRect.top,
+ tableBottom: tableRect.bottom,
+ tableLeft,
+ tableRight: Math.min(tableRect.right, wrapperRect?.right ?? Infinity),
+ nearTop,
+ nearLeft,
+ });
+ });
+
+ const deleteAt = createCallback((type: 'row' | 'column' | 'table') => {
+ const currentTarget = target();
+ const currentEditor = editor();
+ if (!currentTarget || !currentEditor) return;
+
+ currentEditor.update(() => {
+ const cellNode = $getNearestNodeFromDOMNode(currentTarget.cellElem);
+ if (!$isTableCellNode(cellNode) || !cellNode.isAttached()) return;
+
+ if (type === 'table') {
+ const tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNode);
+ tableNode.remove();
+ return;
+ }
+
+ // The delete helpers operate on the selection, so anchor it in the
+ // hovered cell.
+ cellNode.selectStart();
+ if (type === 'row') $deleteTableRowAtSelection();
+ else $deleteTableColumnAtSelection();
+ });
+
+ setHovered(undefined);
+ setTarget(undefined);
+ });
+
+ const removeRootListener = editor()?.registerRootListener(
+ (rootElement, prevRootElement) => {
+ prevRootElement?.removeEventListener('pointermove', onPointerMove);
+ rootElement?.addEventListener('pointermove', onPointerMove);
+ }
+ );
+
+ // Positions go stale on any scroll; just hide.
+ const onScroll = () => {
+ setTarget(undefined);
+ setHovered(undefined);
+ };
+ document.addEventListener('scroll', onScroll, {
+ capture: true,
+ passive: true,
+ });
+
+ onCleanup(() => {
+ removeRootListener?.();
+ document.removeEventListener('scroll', onScroll, { capture: true });
+ });
+
+ const onButtonLeave = () => {
+ setHovered(undefined);
+ setTarget(undefined);
+ };
+
+ return (
+ <Show when={target()}>
+ {(t) => (
+ <ScopedPortal scope="split">
+ {/* Same elevated surface as the other floating bars. */}
+ <Layer depth={2}>
+ {/* Highlight of the row/column about to be deleted. */}
+ <Show when={hovered()}>
+ {(h) => (
+ <div
+ class="fixed z-10 pointer-events-none bg-failure/15"
+ style={{
+ left:
+ h() === 'column'
+ ? `${t().cellLeft}px`
+ : `${t().tableLeft}px`,
+ width:
+ h() === 'column'
+ ? `${t().cellRight - t().cellLeft}px`
+ : `${t().tableRight - t().tableLeft}px`,
+ top:
+ h() === 'row' ? `${t().cellTop}px` : `${t().tableTop}px`,
+ height:
+ h() === 'row'
+ ? `${t().cellBottom - t().cellTop}px`
+ : `${t().tableBottom - t().tableTop}px`,
+ }}
+ />
+ )}
+ </Show>
+ <Show when={t().nearTop}>
+ <button
+ type="button"
+ aria-label="Delete column"
+ class={BUTTON_CLASS}
+ style={{
+ left: `${(t().cellLeft + t().cellRight) / 2}px`,
+ top: `${Math.max(t().tableTop, 12)}px`,
+ }}
+ onPointerDown={(e) => e.preventDefault()}
+ onPointerEnter={() => setHovered('column')}
+ onPointerLeave={onButtonLeave}
+ onClick={() => deleteAt('column')}
+ >
+ <TrashIcon class="size-3" />
+ </button>
+ </Show>
+ <Show when={t().nearLeft}>
+ <button
+ type="button"
+ aria-label="Delete row"
+ class={BUTTON_CLASS}
+ style={{
+ left: `${t().tableLeft}px`,
+ top: `${(t().cellTop + t().cellBottom) / 2}px`,
+ }}
+ onPointerDown={(e) => e.preventDefault()}
+ onPointerEnter={() => setHovered('row')}
+ onPointerLeave={onButtonLeave}
+ onClick={() => deleteAt('row')}
+ >
+ <TrashIcon class="size-3" />
+ </button>
+ </Show>
+ <Show when={t().nearTop && t().nearLeft}>
+ <button
+ type="button"
+ aria-label="Delete table"
+ class={BUTTON_CLASS}
+ style={{
+ left: `${t().tableLeft}px`,
+ top: `${t().tableTop}px`,
+ }}
+ onPointerDown={(e) => e.preventDefault()}
+ onPointerEnter={() => setHovered('table')}
+ onPointerLeave={onButtonLeave}
+ onClick={() => deleteAt('table')}
+ >
+ <TrashIcon class="size-3" />
+ </button>
+ </Show>
+ </Layer>
+ </ScopedPortal>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx
new file mode 100644
index 0000000000..fc44129374
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableInsertButton.tsx
@@ -0,0 +1,263 @@
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import { ScopedPortal } from '@core/component/ScopedPortal';
+import {
+ $computeTableMapSkipCellCheck,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $insertTableColumnAtSelection,
+ $insertTableRowAtSelection,
+ $isTableCellNode,
+ getDOMCellFromTarget,
+ getTableElement,
+} from '@lexical/table';
+import PlusIcon from '@phosphor/plus.svg';
+import { createCallback } from '@solid-primitives/rootless';
+import { Layer } from '@ui';
+import {
+ $getNearestNodeFromDOMNode,
+ $getNodeByKey,
+ isHTMLElement,
+} from 'lexical';
+import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
+import { tableColumnResizeEdge } from './TableCellResizer';
+
+// How close (px) the pointer must be to a row/column border for the button to show.
+const BORDER_PROXIMITY = 6;
+
+type InsertTarget = {
+ type: 'row' | 'column';
+ // Cell whose trailing edge is the hovered border; insertion happens after it.
+ cellKey: string;
+ // Button center, viewport coordinates.
+ x: number;
+ y: number;
+ // Extent of the border line (x-range for rows, y-range for columns).
+ lineFrom: number;
+ lineTo: number;
+};
+
+export function TableInsertButton() {
+ const mdData = mdStore.get;
+ const editor = () => mdData.editor;
+
+ const [insertTarget, setInsertTarget] = createSignal<InsertTarget>();
+ const [buttonHovered, setButtonHovered] = createSignal(false);
+
+ const clear = () => {
+ if (!buttonHovered()) setInsertTarget(undefined);
+ };
+
+ // A column resize captures the pointer, so no pointermove would ever
+ // clear a stale button; hide it for the duration of the drag.
+ createEffect(() => {
+ if (tableColumnResizeEdge()) {
+ setButtonHovered(false);
+ setInsertTarget(undefined);
+ }
+ });
+
+ const onPointerMove = createCallback((event: PointerEvent) => {
+ if (tableColumnResizeEdge()) return;
+ const currentEditor = editor();
+ const target = event.target;
+ if (!currentEditor || !isHTMLElement(target)) return;
+
+ const domCell = getDOMCellFromTarget(target);
+ if (!domCell) return clear();
+
+ const rect = domCell.elem.getBoundingClientRect();
+ const edge = (
+ [
+ {
+ type: 'row',
+ side: 'end',
+ dist: Math.abs(event.clientY - rect.bottom),
+ pos: rect.bottom,
+ },
+ {
+ type: 'row',
+ side: 'start',
+ dist: Math.abs(event.clientY - rect.top),
+ pos: rect.top,
+ },
+ {
+ type: 'column',
+ side: 'end',
+ dist: Math.abs(event.clientX - rect.right),
+ pos: rect.right,
+ },
+ {
+ type: 'column',
+ side: 'start',
+ dist: Math.abs(event.clientX - rect.left),
+ pos: rect.left,
+ },
+ ] as const
+ )
+ .filter((e) => e.dist <= BORDER_PROXIMITY)
+ .sort((a, b) => a.dist - b.dist)[0];
+
+ if (!edge) return clear();
+
+ currentEditor.read(() => {
+ const cellNode = $getNearestNodeFromDOMNode(domCell.elem);
+ if (!$isTableCellNode(cellNode)) return clear();
+
+ const tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNode);
+
+ // The border is the trailing edge of some cell; for leading edges resolve
+ // the neighboring cell before it. The outer top/left edges have no
+ // neighbor and get no button (we only insert after).
+ let referenceCell = cellNode;
+ if (edge.side === 'start') {
+ const [gridMap, cellMap] = $computeTableMapSkipCellCheck(
+ tableNode,
+ cellNode,
+ null
+ );
+ if (!cellMap) return clear();
+ const { startRow, startColumn } = cellMap;
+ const neighbor =
+ edge.type === 'row'
+ ? startRow > 0
+ ? gridMap[startRow - 1][startColumn]
+ : undefined
+ : startColumn > 0
+ ? gridMap[startRow][startColumn - 1]
+ : undefined;
+ if (!neighbor) return clear();
+ referenceCell = neighbor.cell;
+ }
+
+ const tableElem = getTableElement(
+ tableNode,
+ currentEditor.getElementByKey(tableNode.getKey())
+ );
+ if (!tableElem) return clear();
+
+ const tableRect = tableElem.getBoundingClientRect();
+ const wrapperRect = tableElem
+ .closest('.md-table-scrollable-wrapper')
+ ?.getBoundingClientRect();
+
+ if (edge.type === 'row') {
+ const left = Math.max(tableRect.left, wrapperRect?.left ?? -Infinity);
+ const right = Math.min(tableRect.right, wrapperRect?.right ?? Infinity);
+ setInsertTarget({
+ type: 'row',
+ cellKey: referenceCell.getKey(),
+ x: (rect.left + rect.right) / 2,
+ y: edge.pos,
+ lineFrom: left,
+ lineTo: right,
+ });
+ } else {
+ const top = Math.max(tableRect.top, 0);
+ const bottom = Math.min(tableRect.bottom, window.innerHeight);
+ setInsertTarget({
+ type: 'column',
+ cellKey: referenceCell.getKey(),
+ x: edge.pos,
+ y: (rect.top + rect.bottom) / 2,
+ lineFrom: top,
+ lineTo: bottom,
+ });
+ }
+ });
+ });
+
+ const onInsert = createCallback(() => {
+ const target = insertTarget();
+ const currentEditor = editor();
+ if (!target || !currentEditor) return;
+
+ currentEditor.update(() => {
+ const cell = $getNodeByKey(target.cellKey);
+ if (!$isTableCellNode(cell) || !cell.isAttached()) return;
+
+ // The insert helpers operate on the selection, so anchor it in the
+ // cell whose trailing edge was hovered.
+ cell.selectStart();
+ if (target.type === 'row') {
+ const newRow = $insertTableRowAtSelection(true);
+ const firstCell = newRow?.getFirstChild();
+ if ($isTableCellNode(firstCell)) firstCell.selectStart();
+ } else {
+ $insertTableColumnAtSelection(true);
+ }
+ });
+
+ setButtonHovered(false);
+ setInsertTarget(undefined);
+ });
+
+ const removeRootListener = editor()?.registerRootListener(
+ (rootElement, prevRootElement) => {
+ prevRootElement?.removeEventListener('pointermove', onPointerMove);
+ rootElement?.addEventListener('pointermove', onPointerMove);
+ }
+ );
+
+ // Positions go stale on any scroll; just hide.
+ const onScroll = () => {
+ setInsertTarget(undefined);
+ setButtonHovered(false);
+ };
+ document.addEventListener('scroll', onScroll, {
+ capture: true,
+ passive: true,
+ });
+
+ onCleanup(() => {
+ removeRootListener?.();
+ document.removeEventListener('scroll', onScroll, { capture: true });
+ });
+
+ return (
+ <Show when={insertTarget()}>
+ {(target) => (
+ <ScopedPortal scope="split">
+ {/* Same elevated surface as the other floating bars. */}
+ <Layer depth={2}>
+ <Show when={buttonHovered()}>
+ <div
+ class="fixed z-10 pointer-events-none bg-accent"
+ style={
+ target().type === 'row'
+ ? {
+ left: `${target().lineFrom}px`,
+ width: `${target().lineTo - target().lineFrom}px`,
+ top: `${target().y - 1}px`,
+ height: '2px',
+ }
+ : {
+ top: `${target().lineFrom}px`,
+ height: `${target().lineTo - target().lineFrom}px`,
+ left: `${target().x - 1}px`,
+ width: '2px',
+ }
+ }
+ />
+ </Show>
+ <button
+ type="button"
+ class="fixed z-20 flex size-5 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border border-edge bg-surface text-ink-muted shadow-sm hover:border-accent hover:bg-accent hover:text-surface"
+ style={{ left: `${target().x}px`, top: `${target().y}px` }}
+ aria-label={
+ target().type === 'row' ? 'Insert row' : 'Insert column'
+ }
+ onPointerDown={(e) => e.preventDefault()}
+ onPointerEnter={() => setButtonHovered(true)}
+ onPointerLeave={() => {
+ setButtonHovered(false);
+ setInsertTarget(undefined);
+ }}
+ onClick={onInsert}
+ >
+ <PlusIcon class="size-3" />
+ </button>
+ </Layer>
+ </ScopedPortal>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx
new file mode 100644
index 0000000000..7e99631d1d
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableMoveHandle.tsx
@@ -0,0 +1,624 @@
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import { ScopedPortal } from '@core/component/ScopedPortal';
+import clickOutside from '@core/directive/clickOutside';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import {
+ $computeTableMap,
+ $createTableSelection,
+ $deleteTableColumnAtSelection,
+ $deleteTableRowAtSelection,
+ $getTableCellNodeFromLexicalNode,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $insertTableColumnAtSelection,
+ $insertTableRowAtSelection,
+ $isTableCellNode,
+ $isTableSelection,
+ $unmergeCell,
+ getDOMCellFromTarget,
+ type TableCellNode,
+} from '@lexical/table';
+import ColumnsIcon from '@phosphor/columns.svg';
+import ColumnsPlusLeftIcon from '@phosphor/columns-plus-left.svg';
+import ColumnsPlusRightIcon from '@phosphor/columns-plus-right.svg';
+import CornersOutIcon from '@phosphor/corners-out.svg';
+import DotsIcon from '@phosphor/dots-six-vertical.svg';
+import RowsIcon from '@phosphor/rows.svg';
+import RowsPlusBottomIcon from '@phosphor/rows-plus-bottom.svg';
+import RowsPlusTopIcon from '@phosphor/rows-plus-top.svg';
+import TrashIcon from '@phosphor/trash-simple.svg';
+import { createCallback } from '@solid-primitives/rootless';
+import { Layer } from '@ui';
+import {
+ $getNearestNodeFromDOMNode,
+ $getNodeByKey,
+ $getSelection,
+ $isRangeSelection,
+ $setSelection,
+ BLUR_COMMAND,
+ COMMAND_PRIORITY_LOW,
+ FOCUS_COMMAND,
+ SELECTION_CHANGE_COMMAND,
+} from 'lexical';
+import {
+ type Component,
+ type ComponentProps,
+ createMemo,
+ createSignal,
+ For,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { floatWithElement } from '../../directive/floatWithElement';
+import { $moveCellRange } from '../../plugins/tables/tableMove';
+import { createLayoutTick } from './createLayoutTick';
+
+false && clickOutside;
+false && floatWithElement;
+
+const DRAG_THRESHOLD_PX = 4;
+
+type MenuItem = {
+ label: string;
+ icon: Component<ComponentProps<'svg'>>;
+ action: (cell: TableCellNode) => void;
+};
+
+// 2×2 grid: column inserts side by side on top, row inserts below.
+const INSERT_ITEMS: MenuItem[] = [
+ {
+ label: 'Insert column left',
+ icon: ColumnsPlusLeftIcon,
+ action: () => $insertTableColumnAtSelection(false),
+ },
+ {
+ label: 'Insert column right',
+ icon: ColumnsPlusRightIcon,
+ action: () => $insertTableColumnAtSelection(true),
+ },
+ {
+ label: 'Insert row below',
+ icon: RowsPlusBottomIcon,
+ action: () => $insertTableRowAtSelection(true),
+ },
+ {
+ label: 'Insert row above',
+ icon: RowsPlusTopIcon,
+ action: () => $insertTableRowAtSelection(false),
+ },
+];
+
+// Bottom row: delete the row/column the selection is in.
+const DELETE_ITEMS: MenuItem[] = [
+ {
+ label: 'Delete row',
+ icon: RowsIcon,
+ action: () => $deleteTableRowAtSelection(),
+ },
+ {
+ label: 'Delete column',
+ icon: ColumnsIcon,
+ action: () => $deleteTableColumnAtSelection(),
+ },
+];
+
+const MENU_WIDTH_PX = 104;
+const MENU_MAX_HEIGHT_PX = 140;
+
+type DropTarget = {
+ cellElem: HTMLElement;
+ rect: Pick<DOMRect, 'left' | 'top' | 'width' | 'height'>;
+};
+
+type DragShape = {
+ rows: number;
+ columns: number;
+};
+
+/**
+ * Grab handle pinned to the top-right corner of the cell (or multi-cell
+ * selection) the cursor is in. Dragging it moves the selected cells'
+ * contents to the cell dropped on, via the same grid-overlay pipeline as
+ * pasting a copied range.
+ */
+export function TableMoveHandle() {
+ const mdData = mdStore.get;
+ const editor = () => mdData.editor;
+
+ const [anchorCellKey, setAnchorCellKey] = createSignal<string>();
+ const [focusCellKey, setFocusCellKey] = createSignal<string>();
+ const [anchorCellMerged, setAnchorCellMerged] = createSignal(false);
+ const { layoutTick, bumpLayout } = createLayoutTick();
+
+ const [dragging, setDragging] = createSignal(false);
+ const [dropTarget, setDropTarget] = createSignal<DropTarget>();
+ // Touch-only dropdown with insert/delete actions, opened by tapping the
+ // handle without dragging it.
+ const [menuOpen, setMenuOpen] = createSignal(false);
+ const [handleElem, setHandleElem] = createSignal<HTMLButtonElement>();
+
+ const initialRootElement = editor()?.getRootElement();
+ const [editorFocused, setEditorFocused] = createSignal(
+ !!initialRootElement && initialRootElement.contains(document.activeElement)
+ );
+
+ const trackSelection = createCallback(() => {
+ // Keep the handle (and the selection it represents) frozen mid-drag.
+ if (dragging()) return;
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ currentEditor.read(() => {
+ const selection = $getSelection();
+ if ($isTableSelection(selection)) {
+ const anchorNode = $getNodeByKey(selection.anchor.key);
+ const focusNode = $getNodeByKey(selection.focus.key);
+ if (!anchorNode || !focusNode) {
+ setAnchorCellKey(undefined);
+ setFocusCellKey(undefined);
+ setAnchorCellMerged(false);
+ return;
+ }
+ const anchorCell = $getTableCellNodeFromLexicalNode(anchorNode);
+ const focusCell = $getTableCellNodeFromLexicalNode(focusNode);
+ setAnchorCellKey(anchorCell?.getKey());
+ setFocusCellKey(focusCell?.getKey());
+ setAnchorCellMerged(
+ !!anchorCell &&
+ (anchorCell.getColSpan() > 1 || anchorCell.getRowSpan() > 1)
+ );
+ return;
+ }
+ if ($isRangeSelection(selection)) {
+ const anchorNode = $getNodeByKey(selection.anchor.key);
+ const cell = anchorNode
+ ? $getTableCellNodeFromLexicalNode(anchorNode)
+ : null;
+ setAnchorCellKey(cell?.getKey());
+ setFocusCellKey(cell?.getKey());
+ setAnchorCellMerged(
+ !!cell && (cell.getColSpan() > 1 || cell.getRowSpan() > 1)
+ );
+ return;
+ }
+ setAnchorCellKey(undefined);
+ setFocusCellKey(undefined);
+ setAnchorCellMerged(false);
+ });
+ });
+
+ const removeSelectionListener = editor()?.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ trackSelection();
+ return false;
+ },
+ COMMAND_PRIORITY_LOW
+ );
+ const removeUpdateListener = editor()?.registerUpdateListener(() => {
+ trackSelection();
+ bumpLayout();
+ });
+
+ // Escape (via @lexical/rich-text) and clicking elsewhere blur the editor
+ // without clearing its selection, which would otherwise leave the handle
+ // floating over a selection that is no longer visible.
+ const removeFocusListener = editor()?.registerCommand(
+ FOCUS_COMMAND,
+ () => {
+ setEditorFocused(true);
+ return false;
+ },
+ COMMAND_PRIORITY_LOW
+ );
+ const removeBlurListener = editor()?.registerCommand(
+ BLUR_COMMAND,
+ () => {
+ setEditorFocused(false);
+ return false;
+ },
+ COMMAND_PRIORITY_LOW
+ );
+
+ onCleanup(() => {
+ removeSelectionListener?.();
+ removeUpdateListener?.();
+ removeFocusListener?.();
+ removeBlurListener?.();
+ });
+
+ // Top-right corner of the union of the anchor and focus cells (opposite
+ // corners of a table selection; the same cell for a caret selection).
+ const handlePosition = createMemo(() => {
+ layoutTick();
+ if (!editorFocused() && !dragging() && !menuOpen()) return;
+ const currentEditor = editor();
+ const aKey = anchorCellKey();
+ const fKey = focusCellKey();
+ if (!currentEditor || !aKey || !fKey) return;
+
+ const anchorElem = currentEditor.getElementByKey(aKey);
+ const focusElem = currentEditor.getElementByKey(fKey);
+ if (!anchorElem || !focusElem) return;
+
+ const a = anchorElem.getBoundingClientRect();
+ const f = focusElem.getBoundingClientRect();
+
+ // Top-left corner of the table (clamped to the scroll wrapper's visible
+ // span) for the touch-only delete-table button.
+ const tableElem = anchorElem.closest('table');
+ const tableRect = tableElem?.getBoundingClientRect();
+ const wrapperRect = tableElem
+ ?.closest('.md-table-scrollable-wrapper')
+ ?.getBoundingClientRect();
+ // Vertical scroll viewport of the editor; its top is the highest the
+ // handle may sit before it would float over the gray area above.
+ const scrollTop = mdData.scrollContainer?.getBoundingClientRect().top;
+
+ return {
+ // Clamp to the scroll wrapper's visible right edge so a cell scrolled
+ // (or sized) past it doesn't leave the handle floating over the margin.
+ x: Math.min(
+ Math.max(a.right, f.right),
+ wrapperRect?.right ?? window.innerWidth,
+ window.innerWidth
+ ),
+ // Clamp to the scroll viewport's top so scrolling the cell above the
+ // content area doesn't leave the handle floating over the gray.
+ y: Math.max(Math.min(a.top, f.top), scrollTop ?? -Infinity),
+ tableCorner: tableRect
+ ? {
+ x: Math.max(tableRect.left, wrapperRect?.left ?? -Infinity),
+ y: Math.max(tableRect.top, 12),
+ }
+ : undefined,
+ };
+ });
+
+ // Row×column footprint of the dragged range, captured when the drag
+ // starts so the drop preview can mirror it.
+ const dragShape = createCallback((): DragShape => {
+ const fallback: DragShape = { rows: 1, columns: 1 };
+ const currentEditor = editor();
+ if (!currentEditor) return fallback;
+ return currentEditor.read(() => {
+ const aKey = anchorCellKey();
+ const fKey = focusCellKey();
+ const anchorCell = aKey ? $getNodeByKey(aKey) : null;
+ const focusCell = fKey ? $getNodeByKey(fKey) : null;
+ if (
+ !$isTableCellNode(anchorCell) ||
+ !$isTableCellNode(focusCell) ||
+ !anchorCell.isAttached() ||
+ !focusCell.isAttached()
+ ) {
+ return fallback;
+ }
+ const table = $getTableNodeFromLexicalNodeOrThrow(anchorCell);
+ const [, aPos, fPos] = $computeTableMap(table, anchorCell, focusCell);
+ const minRow = Math.min(aPos.startRow, fPos.startRow);
+ const maxRow = Math.max(
+ aPos.startRow + anchorCell.getRowSpan() - 1,
+ fPos.startRow + focusCell.getRowSpan() - 1
+ );
+ const minColumn = Math.min(aPos.startColumn, fPos.startColumn);
+ const maxColumn = Math.max(
+ aPos.startColumn + anchorCell.getColSpan() - 1,
+ fPos.startColumn + focusCell.getColSpan() - 1
+ );
+ return {
+ rows: maxRow - minRow + 1,
+ columns: maxColumn - minColumn + 1,
+ };
+ });
+ });
+
+ // Rect covering the cells the dragged range would land on, anchored at
+ // the hovered cell: clipped at the right edge (matching the drop
+ // behavior) and extended past the bottom for rows that would be created.
+ const previewRect = createCallback(
+ (cellElem: HTMLElement, shape: DragShape): DropTarget['rect'] => {
+ const cellRect = cellElem.getBoundingClientRect();
+ const currentEditor = editor();
+ if (!currentEditor) return cellRect;
+ return currentEditor.read(() => {
+ const targetCell = $getNearestNodeFromDOMNode(cellElem);
+ if (!$isTableCellNode(targetCell) || !targetCell.isAttached()) {
+ return cellRect;
+ }
+ const table = $getTableNodeFromLexicalNodeOrThrow(targetCell);
+ const [map, targetPos] = $computeTableMap(
+ table,
+ targetCell,
+ targetCell
+ );
+ const lastRow = map.length - 1;
+ const lastColumn = (map[0]?.length ?? 1) - 1;
+
+ const endColumn = Math.min(
+ targetPos.startColumn + shape.columns - 1,
+ lastColumn
+ );
+ const wantedEndRow = targetPos.startRow + shape.rows - 1;
+ const endRow = Math.min(wantedEndRow, lastRow);
+
+ const endCell = map[endRow]?.[endColumn]?.cell;
+ const endElem = endCell
+ ? currentEditor.getElementByKey(endCell.getKey())
+ : null;
+ const endRect = endElem?.getBoundingClientRect() ?? cellRect;
+
+ const left = Math.min(cellRect.left, endRect.left);
+ const top = Math.min(cellRect.top, endRect.top);
+ const right = Math.max(cellRect.right, endRect.right);
+ // Rows the move would append extend the preview past the table.
+ const bottom =
+ Math.max(cellRect.bottom, endRect.bottom) +
+ (wantedEndRow - endRow) * cellRect.height;
+
+ return { left, top, width: right - left, height: bottom - top };
+ });
+ }
+ );
+
+ const performMove = createCallback((targetElem: HTMLElement) => {
+ const currentEditor = editor();
+ if (!currentEditor) return;
+
+ currentEditor.update(() => {
+ const targetCell = $getNearestNodeFromDOMNode(targetElem);
+ if (!$isTableCellNode(targetCell) || !targetCell.isAttached()) return;
+
+ const aKey = anchorCellKey();
+ const fKey = focusCellKey();
+ const anchorCell = aKey ? $getNodeByKey(aKey) : null;
+ const focusCell = fKey ? $getNodeByKey(fKey) : null;
+ if (
+ !$isTableCellNode(anchorCell) ||
+ !$isTableCellNode(focusCell) ||
+ !anchorCell.isAttached() ||
+ !focusCell.isAttached()
+ ) {
+ return;
+ }
+
+ $moveCellRange(currentEditor, anchorCell, focusCell, targetCell);
+ });
+ });
+
+ const resetDrag = () => {
+ setDragging(false);
+ setDropTarget(undefined);
+ };
+
+ // Select the cells the handle represents as a table selection, so the
+ // cells highlight and the selection popup (with merge/split) opens.
+ const selectHandleCells = createCallback(() => {
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ currentEditor.update(() => {
+ const aKey = anchorCellKey();
+ const fKey = focusCellKey();
+ const anchorCell = aKey ? $getNodeByKey(aKey) : null;
+ const focusCell = fKey ? $getNodeByKey(fKey) : null;
+ if (
+ !$isTableCellNode(anchorCell) ||
+ !$isTableCellNode(focusCell) ||
+ !anchorCell.isAttached() ||
+ !focusCell.isAttached()
+ ) {
+ return;
+ }
+ const table = $getTableNodeFromLexicalNodeOrThrow(anchorCell);
+ const tableSelection = $createTableSelection();
+ tableSelection.set(
+ table.getKey(),
+ anchorCell.getKey(),
+ focusCell.getKey()
+ );
+ $setSelection(tableSelection);
+ });
+ // The popup listens for this; programmatic $setSelection doesn't fire it.
+ currentEditor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);
+ });
+
+ const runMenuAction = createCallback(
+ (action: (cell: TableCellNode) => void) => {
+ setMenuOpen(false);
+ editor()?.update(() => {
+ // Prefer the live selection; re-anchor in the tracked cell if the tap
+ // blurred the editor. The insert/delete helpers act on the selection.
+ const selection = $getSelection();
+ let cell =
+ $isRangeSelection(selection) || $isTableSelection(selection)
+ ? $getTableCellNodeFromLexicalNode(selection.anchor.getNode())
+ : null;
+ if (!cell) {
+ const key = anchorCellKey();
+ const tracked = key ? $getNodeByKey(key) : null;
+ if ($isTableCellNode(tracked) && tracked.isAttached()) {
+ tracked.selectStart();
+ cell = tracked;
+ }
+ }
+ if (cell) action(cell);
+ });
+ }
+ );
+
+ const menuItemButton = (item: MenuItem, danger?: boolean) => (
+ <button
+ type="button"
+ aria-label={item.label}
+ title={item.label}
+ class="flex items-center justify-center rounded-md py-2 ring-1 ring-edge active:bg-accent/10"
+ classList={{ 'text-failure': danger, 'text-ink-muted': !danger }}
+ onClick={() => runMenuAction(item.action)}
+ >
+ <span class="relative">
+ <item.icon class="size-5" />
+ <Show when={danger}>
+ <TrashIcon class="absolute -right-1 -bottom-1 size-3 rounded-full bg-surface" />
+ </Show>
+ </span>
+ </button>
+ );
+
+ const onHandlePointerDown = (downEvent: PointerEvent) => {
+ downEvent.preventDefault();
+ const handleElem = downEvent.currentTarget;
+ if (!(handleElem instanceof HTMLElement)) return;
+ handleElem.setPointerCapture(downEvent.pointerId);
+
+ const startX = downEvent.clientX;
+ const startY = downEvent.clientY;
+ const shape = dragShape();
+ let started = false;
+
+ const onPointerMove = (moveEvent: PointerEvent) => {
+ if (!started) {
+ const distance = Math.hypot(
+ moveEvent.clientX - startX,
+ moveEvent.clientY - startY
+ );
+ if (distance < DRAG_THRESHOLD_PX) return;
+ started = true;
+ setDragging(true);
+ setMenuOpen(false);
+ }
+ const under = document.elementFromPoint(
+ moveEvent.clientX,
+ moveEvent.clientY
+ );
+ const domCell = under ? getDOMCellFromTarget(under) : null;
+ setDropTarget(
+ domCell
+ ? {
+ cellElem: domCell.elem,
+ rect: previewRect(domCell.elem, shape),
+ }
+ : undefined
+ );
+ };
+
+ const onPointerUp = () => {
+ const target = dropTarget();
+ if (started && target) performMove(target.cellElem);
+ // A tap (no drag) opens the action menu on touch devices, where the
+ // hover-driven insert/delete buttons are unusable. On desktop it
+ // selects the handle's cells, surfacing the selection popup.
+ else if (!started && isTouchDevice()) setMenuOpen(true);
+ else if (!started) selectHandleCells();
+ cleanup();
+ };
+
+ const onKeyDown = (keyEvent: KeyboardEvent) => {
+ if (keyEvent.key === 'Escape') cleanup();
+ };
+
+ const cleanup = () => {
+ handleElem.releasePointerCapture(downEvent.pointerId);
+ handleElem.removeEventListener('pointermove', onPointerMove);
+ handleElem.removeEventListener('pointerup', onPointerUp);
+ handleElem.removeEventListener('pointercancel', cleanup);
+ document.removeEventListener('keydown', onKeyDown);
+ resetDrag();
+ };
+
+ handleElem.addEventListener('pointermove', onPointerMove);
+ handleElem.addEventListener('pointerup', onPointerUp);
+ handleElem.addEventListener('pointercancel', cleanup);
+ document.addEventListener('keydown', onKeyDown);
+ };
+
+ return (
+ <Show when={handlePosition()}>
+ {(pos) => (
+ <ScopedPortal scope="split">
+ {/* Same elevated surface as the other floating bars. */}
+ <Layer depth={2}>
+ <Show when={dragging() && dropTarget()}>
+ {(t) => (
+ <div
+ class="fixed z-10 pointer-events-none bg-accent/15 ring-1 ring-accent/60"
+ style={{
+ left: `${t().rect.left}px`,
+ top: `${t().rect.top}px`,
+ width: `${t().rect.width}px`,
+ height: `${t().rect.height}px`,
+ }}
+ />
+ )}
+ </Show>
+ <button
+ ref={setHandleElem}
+ type="button"
+ aria-label="Move cells"
+ class="fixed z-20 flex size-6 -translate-x-[calc(100%-3px)] -translate-y-[3px] items-center justify-center rounded-full border border-edge bg-surface text-ink-muted shadow-sm touch-none"
+ classList={{
+ 'cursor-grab': !dragging(),
+ 'cursor-grabbing': dragging(),
+ }}
+ style={{ left: `${pos().x}px`, top: `${pos().y}px` }}
+ onPointerDown={onHandlePointerDown}
+ >
+ <DotsIcon class="size-3.5" />
+ </button>
+ {/* Touch devices get a persistent delete-table button on the
+ table's top-left corner while the selection is in the table. */}
+ <Show when={isTouchDevice() && pos().tableCorner}>
+ {(corner) => (
+ <button
+ type="button"
+ aria-label="Delete table"
+ title="Delete table"
+ class="fixed z-20 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border border-edge bg-surface text-failure shadow-sm active:border-failure active:bg-failure active:text-surface"
+ style={{ left: `${corner().x}px`, top: `${corner().y}px` }}
+ onPointerDown={(e) => e.preventDefault()}
+ onClick={() =>
+ runMenuAction((cell) =>
+ $getTableNodeFromLexicalNodeOrThrow(cell).remove()
+ )
+ }
+ >
+ <TrashIcon class="size-3.5" />
+ </button>
+ )}
+ </Show>
+ <Show when={menuOpen()}>
+ <div
+ class="z-30 grid grid-cols-2 gap-1 overflow-y-auto rounded-lg bg-surface p-1.5 shadow-lg ring-1 ring-edge"
+ style={{
+ width: `${MENU_WIDTH_PX}px`,
+ 'max-height': `${MENU_MAX_HEIGHT_PX}px`,
+ }}
+ use:floatWithElement={{
+ element: handleElem,
+ floatingOptions: { placement: 'bottom-end' },
+ spacing: 4,
+ }}
+ use:clickOutside={() => setMenuOpen(false)}
+ onPointerDown={(e) => e.preventDefault()}
+ >
+ <For each={INSERT_ITEMS}>{(item) => menuItemButton(item)}</For>
+ <For each={DELETE_ITEMS}>
+ {(item) => menuItemButton(item, true)}
+ </For>
+ <Show when={anchorCellMerged()}>
+ <button
+ type="button"
+ aria-label="Split cell"
+ title="Split cell"
+ class="col-span-2 flex items-center justify-center gap-1.5 rounded-md py-2 ring-1 ring-edge active:bg-accent/10 text-ink-muted"
+ onClick={() => runMenuAction(() => $unmergeCell())}
+ >
+ <CornersOutIcon class="size-4" />
+ <span class="text-xs">Split cell</span>
+ </button>
+ </Show>
+ </div>
+ </Show>
+ </Layer>
+ </ScopedPortal>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx
new file mode 100644
index 0000000000..a6e1a0662c
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/TableSelectionActionBar.tsx
@@ -0,0 +1,298 @@
+/**
+ * @file Floating cut/copy/paste/merge/split bar shown over a table cell
+ * selection on touch devices, where there is no keyboard shortcut or context
+ * menu for the clipboard and no format popup for table selections. On
+ * desktop, merge/split live in the normal selection popup (FormatTools).
+ */
+import { mdStore } from '@block-md/signal/markdownBlockData';
+import { ScopedPortal } from '@core/component/ScopedPortal';
+import { toast } from '@core/component/Toast/Toast';
+import {
+ readClipboardAsDataTransfer,
+ writeClipboardData,
+} from '@core/util/dataTransfer';
+import {
+ $getClipboardDataFromSelection,
+ $insertDataTransferForRichText,
+} from '@lexical/clipboard';
+import {
+ $getTableCellNodeFromLexicalNode,
+ $isTableCellNode,
+ $isTableSelection,
+ $mergeCells,
+ $unmergeCell,
+} from '@lexical/table';
+import ClipboardIcon from '@phosphor/clipboard.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import CornersInIcon from '@phosphor/corners-in.svg';
+import CornersOutIcon from '@phosphor/corners-out.svg';
+import ScissorsIcon from '@phosphor/scissors.svg';
+import { createCallback } from '@solid-primitives/rootless';
+import { Layer } from '@ui';
+import {
+ $getNodeByKey,
+ $getSelection,
+ $isRangeSelection,
+ $setSelection,
+ BLUR_COMMAND,
+ COMMAND_PRIORITY_LOW,
+ KEY_BACKSPACE_COMMAND,
+ SELECTION_CHANGE_COMMAND,
+} from 'lexical';
+import {
+ type Component,
+ type ComponentProps,
+ createMemo,
+ createSignal,
+ onCleanup,
+ Show,
+} from 'solid-js';
+import { floatWithElement } from '../../directive/floatWithElement';
+import { createLayoutTick } from './createLayoutTick';
+
+false && floatWithElement;
+
+export function TableSelectionActionBar() {
+ const mdData = mdStore.get;
+ const editor = () => mdData.editor;
+
+ const [anchorCellKey, setAnchorCellKey] = createSignal<string>();
+ const [focusCellKey, setFocusCellKey] = createSignal<string>();
+ const [hasMergedCell, setHasMergedCell] = createSignal(false);
+ const { layoutTick, bumpLayout } = createLayoutTick();
+
+ const isMultiCell = () => anchorCellKey() !== focusCellKey();
+
+ const trackSelection = createCallback(() => {
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ currentEditor.read(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection)) {
+ setAnchorCellKey(undefined);
+ setFocusCellKey(undefined);
+ setHasMergedCell(false);
+ return;
+ }
+ // Use $getNodeByKey to avoid throws when nodes were just removed (e.g. post-merge).
+ const anchorNode = $getNodeByKey(selection.anchor.key);
+ const focusNode = $getNodeByKey(selection.focus.key);
+ if (!anchorNode || !focusNode) {
+ setAnchorCellKey(undefined);
+ setFocusCellKey(undefined);
+ setHasMergedCell(false);
+ return;
+ }
+ const anchorCell = $getTableCellNodeFromLexicalNode(anchorNode);
+ const focusCell = $getTableCellNodeFromLexicalNode(focusNode);
+ setAnchorCellKey(anchorCell?.getKey());
+ setFocusCellKey(focusCell?.getKey());
+ const cells = selection.getNodes().filter($isTableCellNode);
+ setHasMergedCell(
+ cells.some((c) => c.getColSpan() > 1 || c.getRowSpan() > 1)
+ );
+ });
+ });
+
+ const removeSelectionListener = editor()?.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ trackSelection();
+ return false;
+ },
+ COMMAND_PRIORITY_LOW
+ );
+ const removeUpdateListener = editor()?.registerUpdateListener(() => {
+ trackSelection();
+ bumpLayout();
+ });
+ // Tapping outside the editor blurs it without a selection change; the
+ // selection the bar acted on is gone, so hide it. (Bar taps themselves
+ // preventDefault pointerdown and never blur.)
+ const removeBlurListener = editor()?.registerCommand(
+ BLUR_COMMAND,
+ () => {
+ setAnchorCellKey(undefined);
+ setFocusCellKey(undefined);
+ setHasMergedCell(false);
+ return false;
+ },
+ COMMAND_PRIORITY_LOW
+ );
+
+ onCleanup(() => {
+ removeSelectionListener?.();
+ removeUpdateListener?.();
+ removeBlurListener?.();
+ });
+
+ // Bounding rect of the union of the anchor and focus cells; an invisible
+ // fixed div at this rect anchors the floating bar.
+ const anchorRect = createMemo(() => {
+ layoutTick();
+ const currentEditor = editor();
+ const aKey = anchorCellKey();
+ const fKey = focusCellKey();
+ if (!currentEditor || !aKey || !fKey) return;
+
+ const a = currentEditor.getElementByKey(aKey)?.getBoundingClientRect();
+ const f = currentEditor.getElementByKey(fKey)?.getBoundingClientRect();
+ if (!a || !f) return;
+
+ const left = Math.min(a.left, f.left);
+ const top = Math.min(a.top, f.top);
+ return {
+ left,
+ top,
+ width: Math.max(a.right, f.right) - left,
+ height: Math.max(a.bottom, f.bottom) - top,
+ };
+ });
+
+ // Collapse the selection so the bar dismisses after an action, the way a
+ // normal context menu closes once you pick something.
+ const clearSelection = createCallback(() => {
+ editor()?.update(() => $setSelection(null));
+ });
+
+ // Serialize the current table selection to clipboard MIME strings; null
+ // when there is no table selection to copy.
+ const readSelectionData = () => {
+ const currentEditor = editor();
+ if (!currentEditor) return null;
+ return currentEditor.read(() => {
+ const selection = $getSelection();
+ return $isTableSelection(selection)
+ ? $getClipboardDataFromSelection(selection)
+ : null;
+ });
+ };
+
+ const runCut = createCallback(async () => {
+ const currentEditor = editor();
+ const data = readSelectionData();
+ if (!currentEditor || !data) return;
+ if (!(await writeClipboardData(data))) {
+ toast.failure('Failed to cut cells');
+ return;
+ }
+ // Clear the selected cells via the same path as backspacing a table
+ // selection ($clearText), which also collapses the selection.
+ currentEditor.dispatchCommand(
+ KEY_BACKSPACE_COMMAND,
+ new KeyboardEvent('keydown', { key: 'Backspace' })
+ );
+ });
+
+ const runCopy = createCallback(async () => {
+ const data = readSelectionData();
+ if (!data) return;
+ if (await writeClipboardData(data)) {
+ toast.success('Copied cells');
+ // Dismiss the bar once the action is taken, like a normal menu.
+ clearSelection();
+ }
+ });
+
+ const runMerge = createCallback(() => {
+ editor()?.update(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection)) return;
+ $mergeCells(selection.getNodes().filter($isTableCellNode));
+ $setSelection(null);
+ });
+ });
+
+ const runSplit = createCallback(() => {
+ editor()?.update(() => {
+ $unmergeCell();
+ $setSelection(null);
+ });
+ });
+
+ // Replays the system clipboard through the normal rich-text paste pipeline
+ // (which routes a copied cell range through the table grid overlay), then
+ // collapses the selection so the bar dismisses. Inserting the DataTransfer
+ // directly avoids a synthetic ClipboardEvent, whose clipboardData is null
+ // on WebKit/mobile — the reason paste silently did nothing there.
+ const runPaste = createCallback(async () => {
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ const dataTransfer = await readClipboardAsDataTransfer();
+ if (!dataTransfer) {
+ toast.failure('Nothing to paste');
+ return;
+ }
+ currentEditor.update(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection) && !$isRangeSelection(selection)) {
+ return;
+ }
+ $insertDataTransferForRichText(dataTransfer, selection, currentEditor);
+ $setSelection(null);
+ });
+ });
+
+ const barButton = (
+ label: string,
+ icon: Component<ComponentProps<'svg'>>,
+ onClick: () => void,
+ danger?: boolean
+ ) => {
+ const Icon = icon;
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ class="flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-sm active:bg-accent/10"
+ classList={{ 'text-failure': danger, 'text-ink-muted': !danger }}
+ onPointerDown={(e) => e.preventDefault()}
+ onClick={onClick}
+ >
+ <Icon class="size-4" />
+ {label}
+ </button>
+ );
+ };
+
+ const [anchorElem, setAnchorElem] = createSignal<HTMLDivElement>();
+
+ return (
+ <Show when={anchorRect()}>
+ {(rect) => (
+ <ScopedPortal scope="split">
+ {/* Same elevated surface as the other floating bars. */}
+ <Layer depth={2}>
+ <div
+ ref={setAnchorElem}
+ class="pointer-events-none fixed"
+ style={{
+ left: `${rect().left}px`,
+ top: `${rect().top}px`,
+ width: `${rect().width}px`,
+ height: `${rect().height}px`,
+ }}
+ />
+ <div
+ class="z-30 flex items-center gap-0.5 rounded-lg bg-surface p-1 shadow-lg ring-1 ring-edge"
+ use:floatWithElement={{
+ element: anchorElem,
+ floatingOptions: { placement: 'top' },
+ }}
+ >
+ {barButton('Cut', ScissorsIcon, () => void runCut())}
+ {barButton('Copy', CopyIcon, () => void runCopy())}
+ {barButton('Paste', ClipboardIcon, () => void runPaste())}
+ <Show when={isMultiCell()}>
+ {barButton('Merge', CornersInIcon, runMerge)}
+ </Show>
+ <Show when={hasMergedCell()}>
+ {barButton('Split', CornersOutIcon, runSplit)}
+ </Show>
+ </div>
+ </Layer>
+ </ScopedPortal>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/createLayoutTick.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/createLayoutTick.ts
new file mode 100644
index 0000000000..e8d0ee5ad2
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/misc/createLayoutTick.ts
@@ -0,0 +1,33 @@
+import { createSignal, onCleanup } from 'solid-js';
+
+/**
+ * Returns a reactive tick counter and a bump function. Reading `layoutTick()`
+ * inside a memo subscribes it to layout changes; call `bumpLayout()` on scroll,
+ * resize, or any event that moves DOM elements without triggering reactive state.
+ *
+ * Scroll and resize listeners are registered immediately and cleaned up via
+ * onCleanup — call this inside a reactive root (component, createRoot, etc.).
+ */
+export function createLayoutTick(): {
+ layoutTick: () => number;
+ bumpLayout: () => void;
+} {
+ const [layoutTick, setLayoutTick] = createSignal(0);
+ // Void body: Lexical treats an update listener's return value as a cleanup fn.
+ const bumpLayout = () => {
+ setLayoutTick((t) => t + 1);
+ };
+
+ document.addEventListener('scroll', bumpLayout, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener('resize', bumpLayout);
+
+ onCleanup(() => {
+ document.removeEventListener('scroll', bumpLayout, { capture: true });
+ window.removeEventListener('resize', bumpLayout);
+ });
+
+ return { layoutTick, bumpLayout };
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
index 7ffbc6fdd9..c416911438 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/actions/actions.ts
@@ -43,6 +43,7 @@ import { TRY_INSERT_LINK_COMMAND } from '../links';
import { TRY_INSERT_MEDIA_UPLOAD_COMMAND } from '../media';
import { INSERT_DOCUMENT_MENTION_COMMAND } from '../mentions/mentionsPlugin';
import { NODE_TRANSFORM } from '../node-transform';
+import { TRY_INSERT_TABLE_PICKER_COMMAND } from '../tables';
import { type Action, ActionCategory, type ActionContext } from './types';
async function trackSlashTaskMention(
@@ -292,11 +293,17 @@ export const ACTIONS: Action[] = [
category: ActionCategory.MEDIA,
action: (editor: LexicalEditor) => {
queueMicrotask(() => {
- editor.dispatchCommand(INSERT_TABLE_COMMAND, {
- columns: '5',
- rows: '3',
- includeHeaders: false,
- });
+ const pickerOpened = editor.dispatchCommand(
+ TRY_INSERT_TABLE_PICKER_COMMAND,
+ undefined
+ );
+ if (!pickerOpened) {
+ editor.dispatchCommand(INSERT_TABLE_COMMAND, {
+ columns: '3',
+ rows: '3',
+ includeHeaders: false,
+ });
+ }
});
},
dependencies: [TableNode],
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts
index a32754204b..b4b80b554b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts
@@ -39,7 +39,8 @@ function registerMarkdownPastePlugin(editor: LexicalEditor) {
const clipboard = event.clipboardData;
if (!clipboard) return false;
// do not handle richer clipboards.
- if (clipboard.getData('application/x-lexical-clipboard')) {
+ // https://github.com/facebook/lexical/blob/main/packages/lexical-clipboard/src/clipboard.ts#L67
+ if (clipboard.getData('application/x-lexical-editor')) {
return false;
}
if (clipboard.getData('text/html')) {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
index b22fe0ede8..196b29163b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/popup/popupPlugin.ts
@@ -1,3 +1,4 @@
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { $convertFromMarkdownString } from '@lexical/markdown';
import {
$isTableCellNode,
@@ -168,14 +169,18 @@ function registerPopupPlugin(editor: LexicalEditor, props: PopupPluginProps) {
let cachedLastSelection: EnhancedSelection | null = null;
function $validateAndSetSelection(selection: BaseSelection) {
- if (selection.getTextContent().length === 0) {
- return null;
- }
-
if ($isTableSelection(selection)) {
+ // Touch cell selections get their own action bar
+ // (TableSelectionActionBar); the popup would stack on top of it.
+ // No text-length gate: empty cells can still be merged.
+ if (isTouchDevice()) return null;
return $enhanceTableSelection(selection);
}
+ if (selection.getTextContent().length === 0) {
+ return null;
+ }
+
if ($isRangeSelection(selection)) {
return $enhanceRangeSelection(selection);
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/selection-data/selectionDataPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/selection-data/selectionDataPlugin.ts
index b2b27346ee..d6e969a613 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/selection-data/selectionDataPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/selection-data/selectionDataPlugin.ts
@@ -6,6 +6,11 @@ import { $isAutoLinkNode, $isLinkNode } from '@lexical/link';
import type { ListNode } from '@lexical/list';
// import { mergeRegister } from '@lexical/utils';
import type { HeadingNode } from '@lexical/rich-text';
+import {
+ $getTableCellNodeFromLexicalNode,
+ $isTableCellNode,
+ $isTableSelection,
+} from '@lexical/table';
import type { ElementName } from '@macro-inc/lexical-core';
import {
$getSelection,
@@ -29,7 +34,7 @@ import type { LexicalWrapper } from '../../context/LexicalWrapperContext';
* are only valid if the selection is a RangeSelection.
*/
export type SelectionData = {
- type: 'range' | 'node' | null;
+ type: 'range' | 'node' | 'table' | null;
bold: boolean;
italic: boolean;
underline: boolean;
@@ -41,6 +46,8 @@ export type SelectionData = {
elementsInRange: Set<ElementName>;
nodeKeys: Set<NodeKey>;
hasLinks: boolean;
+ onMergableCells: boolean;
+ onSplittableCells: boolean;
};
export const defaultSelectionData: SelectionData = {
@@ -56,6 +63,8 @@ export const defaultSelectionData: SelectionData = {
elementsInRange: new Set(),
nodeKeys: new Set(),
hasLinks: false,
+ onMergableCells: false,
+ onSplittableCells: false,
};
function resetSelectionData(setSelectionData: SetStoreFunction<SelectionData>) {
@@ -70,6 +79,16 @@ function $getSelectionData(selection: BaseSelection | null): SelectionData {
const data = structuredClone(defaultSelectionData);
if (selection === null) return data;
+ if ($isTableSelection(selection)) {
+ data.type = 'table';
+ const cells = selection.getNodes().filter($isTableCellNode);
+ data.onMergableCells = cells.length > 1;
+ data.onSplittableCells = cells.some(
+ (cell) => cell.getColSpan() > 1 || cell.getRowSpan() > 1
+ );
+ return data;
+ }
+
if ($isRangeSelection(selection)) {
data.type = 'range';
data.bold = selection.hasFormat('bold');
@@ -82,6 +101,9 @@ function $getSelectionData(selection: BaseSelection | null): SelectionData {
data.highlight = selection.hasFormat('highlight');
data.elementsInRange = $extractNodeTypes(selection);
data.hasLinks = $hasLinks(selection);
+ const cell = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
+ data.onSplittableCells =
+ !!cell && (cell.getColSpan() > 1 || cell.getRowSpan() > 1);
}
if ($isNodeSelection(selection)) {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/index.ts
index 47b48ba9ef..cb56d0d999 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/index.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/index.ts
@@ -1,3 +1,7 @@
-export * from './tableActionMenuPlugin';
+export * from './listToTable';
+export * from './listToTablePlugin';
+export * from './tableCellResize';
export * from './tableCellResizerPlugin';
+export * from './tablePickerPlugin';
export * from './tablePlugin';
+export * from './tableTouchSelection';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.test.ts
new file mode 100644
index 0000000000..fa470592a2
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.test.ts
@@ -0,0 +1,382 @@
+import {
+ $createListItemNode,
+ $createListNode,
+ $isListNode,
+ type ListItemNode,
+ type ListNode,
+ type ListType,
+} from '@lexical/list';
+import { registerRichText } from '@lexical/rich-text';
+import {
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+ TableCellHeaderStates,
+ type TableNode,
+} from '@lexical/table';
+import { SupportedNodeTypes } from '@macro-inc/lexical-core/node-list';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $isTextNode,
+ createEditor,
+ type LexicalEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+
+import {
+ $getConvertibleListFromSelection,
+ $listToGrid,
+ LIST_TO_TABLE_COMMAND,
+ registerListToTableCommand,
+} from './listToTable';
+import { tablePlugin } from './tablePlugin';
+
+function createTestEditor(): LexicalEditor {
+ const editor = createEditor({
+ namespace: 'list-to-table-test',
+ nodes: SupportedNodeTypes,
+ onError: (error) => {
+ throw error;
+ },
+ });
+ tablePlugin({
+ hasCellMerge: true,
+ hasCellBackgroundColor: true,
+ hasTabHandler: true,
+ })(editor);
+ registerListToTableCommand(editor);
+ registerRichText(editor);
+ const rootElement = document.createElement('div');
+ rootElement.contentEditable = 'true';
+ document.body.appendChild(rootElement);
+ editor.setRootElement(rootElement);
+ return editor;
+}
+
+function $item(text: string): ListItemNode {
+ const item = $createListItemNode();
+ item.append($createTextNode(text));
+ return item;
+}
+
+/** Wraps items in the tree-nesting shape: a wrapper item holding a sub-list. */
+function $wrap(items: ListItemNode[], type: ListType = 'bullet'): ListItemNode {
+ const wrapper = $createListItemNode();
+ const sub = $createListNode(type);
+ sub.append(...items);
+ wrapper.append(sub);
+ return wrapper;
+}
+
+/** Builds `- header / - rows...` columns as Lexical's list plugin nests them. */
+function $buildColumns(
+ columns: Array<[string, string[]]>,
+ type: ListType = 'bullet'
+): ListNode {
+ const list = $createListNode(type);
+ for (const [header, rows] of columns) {
+ list.append($item(header));
+ if (rows.length > 0) list.append($wrap(rows.map($item), type));
+ }
+ return list;
+}
+
+async function mount(editor: LexicalEditor, $build: () => ListNode) {
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $getRoot().clear().append($build());
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+}
+
+function getListKey(editor: LexicalEditor): string {
+ return editor.getEditorState().read(() => {
+ const list = $getRoot().getFirstChild();
+ if (!$isListNode(list)) throw new Error('no list');
+ return list.getKey();
+ });
+}
+
+async function convert(editor: LexicalEditor): Promise<boolean> {
+ const handled = editor.dispatchCommand(
+ LIST_TO_TABLE_COMMAND,
+ getListKey(editor)
+ );
+ await Promise.resolve();
+ return handled;
+}
+
+function $getTable(): TableNode {
+ const table = $getRoot().getFirstChild();
+ if (!$isTableNode(table)) throw new Error('no table');
+ return table;
+}
+
+function readCellTexts(editor: LexicalEditor): string[][] {
+ return editor.getEditorState().read(() =>
+ $getTable()
+ .getChildren()
+ .filter($isTableRowNode)
+ .map((row) =>
+ row
+ .getChildren()
+ .filter($isTableCellNode)
+ .map((cell) => cell.getTextContent())
+ )
+ );
+}
+
+describe('list to table conversion', () => {
+ it('turns top-level items into columns and nested items into rows', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['column 1', ['a1', 'a2', 'a3']],
+ ['column 2', ['b1', 'b2', 'b3']],
+ ['column 3', ['c1', 'c2', 'c3']],
+ ])
+ );
+
+ expect(await convert(editor)).toBe(true);
+ expect(readCellTexts(editor)).toEqual([
+ ['column 1', 'column 2', 'column 3'],
+ ['a1', 'b1', 'c1'],
+ ['a2', 'b2', 'c2'],
+ ['a3', 'b3', 'c3'],
+ ]);
+ });
+
+ it('marks the first row as header cells', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['x', ['1']],
+ ['y', ['2']],
+ ])
+ );
+ await convert(editor);
+
+ editor.getEditorState().read(() => {
+ const [headerRow, bodyRow] = $getTable()
+ .getChildren()
+ .filter($isTableRowNode);
+ for (const cell of headerRow.getChildren().filter($isTableCellNode)) {
+ expect(cell.getHeaderStyles()).toBe(TableCellHeaderStates.ROW);
+ }
+ for (const cell of bodyRow.getChildren().filter($isTableCellNode)) {
+ expect(cell.getHeaderStyles()).toBe(TableCellHeaderStates.NO_STATUS);
+ }
+ });
+ });
+
+ it('pads ragged columns with empty cells', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['column 1', ['a1', 'a2', 'a3']],
+ ['column 2', ['b1']],
+ ])
+ );
+
+ expect(await convert(editor)).toBe(true);
+ expect(readCellTexts(editor)).toEqual([
+ ['column 1', 'column 2'],
+ ['a1', 'b1'],
+ ['a2', ''],
+ ['a3', ''],
+ ]);
+ });
+
+ it('keeps content nested deeper than two levels as a list inside the cell', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () => {
+ const list = $createListNode('bullet');
+ list.append($item('column 1'));
+ const a1 = $item('a1');
+ list.append($wrap([a1, $wrap([$item('deep 1'), $item('deep 2')])]));
+ list.append($item('column 2'));
+ list.append($wrap([$item('b1')]));
+ return list;
+ });
+
+ expect(await convert(editor)).toBe(true);
+ editor.getEditorState().read(() => {
+ const bodyRow = $getTable().getChildren().filter($isTableRowNode)[1];
+ const cell = bodyRow.getChildren().filter($isTableCellNode)[0];
+ const [paragraph, nested] = cell.getChildren();
+ expect(paragraph.getTextContent()).toBe('a1');
+ expect($isListNode(nested)).toBe(true);
+ expect(nested.getTextContent()).toContain('deep 1');
+ expect(nested.getTextContent()).toContain('deep 2');
+ });
+ });
+
+ it('preserves inline formatting when moving content into cells', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () => {
+ const list = $createListNode('bullet');
+ const header = $createListItemNode();
+ const bold = $createTextNode('column 1');
+ bold.setFormat('bold');
+ header.append(bold);
+ list.append(header, $wrap([$item('a1')]));
+ list.append($item('column 2'), $wrap([$item('b1')]));
+ return list;
+ });
+
+ expect(await convert(editor)).toBe(true);
+ editor.getEditorState().read(() => {
+ const headerRow = $getTable().getChildren().filter($isTableRowNode)[0];
+ const cell = headerRow.getChildren().filter($isTableCellNode)[0];
+ const text = cell.getFirstDescendant();
+ expect(text?.getTextContent()).toBe('column 1');
+ expect($isTextNode(text) && text.hasFormat('bold')).toBe(true);
+ });
+ });
+
+ it('rejects a flat list', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () => {
+ const list = $createListNode('bullet');
+ list.append($item('one'), $item('two'), $item('three'));
+ return list;
+ });
+
+ expect(await convert(editor)).toBe(false);
+ editor.getEditorState().read(() => {
+ expect($isListNode($getRoot().getFirstChild())).toBe(true);
+ });
+ });
+
+ it('rejects a single-column list', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () => $buildColumns([['column 1', ['a1', 'a2']]]));
+ expect(await convert(editor)).toBe(false);
+ });
+
+ it('rejects a list where a top-level item has no nested content', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['column 1', ['a1']],
+ ['column 2', []],
+ ])
+ );
+ expect(await convert(editor)).toBe(false);
+ });
+
+ it('rejects checklists', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns(
+ [
+ ['column 1', ['a1']],
+ ['column 2', ['b1']],
+ ],
+ 'check'
+ )
+ );
+ expect(await convert(editor)).toBe(false);
+ });
+
+ it('handles nested lists embedded directly in their parent item', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () => {
+ const list = $createListNode('bullet');
+ for (const [header, rows] of [
+ ['column 1', ['a1', 'a2']],
+ ['column 2', ['b1', 'b2']],
+ ] as Array<[string, string[]]>) {
+ const item = $item(header);
+ const sub = $createListNode('bullet');
+ sub.append(...rows.map($item));
+ item.append(sub);
+ list.append(item);
+ }
+ return list;
+ });
+
+ expect(await convert(editor)).toBe(true);
+ expect(readCellTexts(editor)).toEqual([
+ ['column 1', 'column 2'],
+ ['a1', 'b1'],
+ ['a2', 'b2'],
+ ]);
+ });
+
+ it('finds the convertible list from a selection inside it, but not elsewhere', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['column 1', ['a1']],
+ ['column 2', ['b1']],
+ ])
+ );
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode('outside'));
+ $getRoot().append(paragraph);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ const $selectText = (content: string) => {
+ const text = $getRoot()
+ .getAllTextNodes()
+ .find((node) => node.getTextContent() === content);
+ if (!text) throw new Error(`no text node "${content}"`);
+ text.select(0, 0);
+ };
+
+ await new Promise<void>((resolve) => {
+ editor.update(() => $selectText('a1'), { onUpdate: () => resolve() });
+ });
+ editor.getEditorState().read(() => {
+ expect($getConvertibleListFromSelection()?.getKey()).toBe(
+ $getRoot().getFirstChild()?.getKey()
+ );
+ });
+
+ await new Promise<void>((resolve) => {
+ editor.update(() => $selectText('outside'), {
+ onUpdate: () => resolve(),
+ });
+ });
+ editor.getEditorState().read(() => {
+ expect($getConvertibleListFromSelection()).toBeNull();
+ });
+ });
+
+ it('reads the grid without mutating the list', async () => {
+ const editor = createTestEditor();
+ await mount(editor, () =>
+ $buildColumns([
+ ['column 1', ['a1']],
+ ['column 2', ['b1', 'b2']],
+ ])
+ );
+
+ const shape = editor.getEditorState().read(() => {
+ const list = $getRoot().getFirstChild();
+ if (!$isListNode(list)) throw new Error('no list');
+ const grid = $listToGrid(list);
+ return grid?.map((column) => ({
+ header: column.header.getTextContent(),
+ cells: column.cells.map((cell) => cell.item.getTextContent()),
+ }));
+ });
+
+ expect(shape).toEqual([
+ { header: 'column 1', cells: ['a1'] },
+ { header: 'column 2', cells: ['b1', 'b2'] },
+ ]);
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.ts
new file mode 100644
index 0000000000..756cb4cd3b
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTable.ts
@@ -0,0 +1,247 @@
+/**
+ * @file Converts a nested list into a table: each top-level item becomes a
+ * column header and its nested items become that column's cells, so
+ *
+ * - column 1 | column 1 | column 2 |
+ * - goes in row 1 |----------|----------|
+ * - goes in row 2 | row 1 | row 1 |
+ * - column 2 → | row 2 | row 2 |
+ * - goes in row 1 | | |
+ * - goes in row 2 | | |
+ *
+ * Content nested deeper than two levels stays a list inside its cell.
+ */
+import {
+ $createListNode,
+ $isListItemNode,
+ $isListNode,
+ type ListItemNode,
+ type ListNode,
+ type ListType,
+} from '@lexical/list';
+import {
+ $createTableCellNode,
+ $createTableNode,
+ $createTableRowNode,
+ TableCellHeaderStates,
+ type TableCellNode,
+ type TableNode,
+} from '@lexical/table';
+import {
+ $createParagraphNode,
+ $getNodeByKey,
+ $getSelection,
+ $isElementNode,
+ $isRangeSelection,
+ $isRootNode,
+ COMMAND_PRIORITY_EDITOR,
+ createCommand,
+ type LexicalCommand,
+ type LexicalEditor,
+ type NodeKey,
+} from 'lexical';
+import { $collectNestedGroup } from '../draggable-block/draggableBlockPlugin';
+
+/** Converts the ListNode with the given key into a table. */
+export const LIST_TO_TABLE_COMMAND: LexicalCommand<NodeKey> = createCommand(
+ 'LIST_TO_TABLE_COMMAND'
+);
+
+export type ListGridCell = {
+ /** Item whose inline content becomes the cell's paragraph. */
+ item: ListItemNode;
+ /** Nested lists holding deeper content; moved into the cell as-is. */
+ nestedLists: ListNode[];
+ /** Deeper flat-indent items; moved into a new list inside the cell. */
+ deepItems: ListItemNode[];
+};
+
+export type ListGridColumn = {
+ header: ListItemNode;
+ cells: ListGridCell[];
+};
+
+/** A list item whose only children are lists — the tree-nesting wrapper shape. */
+function isNestingWrapper(item: ListItemNode): boolean {
+ const children = item.getChildren();
+ return children.length > 0 && children.every((child) => $isListNode(child));
+}
+
+function $newCell(item: ListItemNode): ListGridCell {
+ return {
+ item,
+ // Lists embedded directly in the item are deeper content for its cell.
+ nestedLists: item.getChildren().filter($isListNode),
+ deepItems: [],
+ };
+}
+
+/** Items of a nested list become cells; anything deeper stays with its cell. */
+function $subListToCells(sub: ListNode, cells: ListGridCell[]): void {
+ let cellIndent: number | null = null;
+ for (const node of sub.getChildren()) {
+ if (!$isListItemNode(node)) continue;
+ if (isNestingWrapper(node)) {
+ const lists = node.getChildren().filter($isListNode);
+ const last = cells[cells.length - 1];
+ if (last) last.nestedLists.push(...lists);
+ else for (const list of lists) $subListToCells(list, cells);
+ continue;
+ }
+ cellIndent ??= node.getIndent();
+ if (node.getIndent() > cellIndent && cells.length > 0) {
+ cells[cells.length - 1].deepItems.push(node);
+ continue;
+ }
+ cells.push($newCell(node));
+ }
+}
+
+/** Turns a header item plus its nested group (see $collectNestedGroup) into cells. */
+function $groupToCells(group: ListItemNode[]): ListGridCell[] {
+ const [header, ...rest] = group;
+ const cells: ListGridCell[] = [];
+ for (const child of header.getChildren()) {
+ if ($isListNode(child)) $subListToCells(child, cells);
+ }
+ let cellIndent: number | null = null;
+ for (const item of rest) {
+ if (isNestingWrapper(item)) {
+ for (const sub of item.getChildren()) {
+ if ($isListNode(sub)) $subListToCells(sub, cells);
+ }
+ continue;
+ }
+ cellIndent ??= item.getIndent();
+ if (item.getIndent() > cellIndent && cells.length > 0) {
+ cells[cells.length - 1].deepItems.push(item);
+ } else {
+ cells.push($newCell(item));
+ }
+ }
+ return cells;
+}
+
+/**
+ * Reads a list as a table grid. Returns null when the list doesn't have a
+ * table shape: fewer than two top-level items, or a top-level item without
+ * nested content. Does not mutate — safe in a read context.
+ */
+export function $listToGrid(list: ListNode): ListGridColumn[] | null {
+ if (list.getListType() === 'check') return null;
+ const children = list.getChildren();
+ const columns: ListGridColumn[] = [];
+ let i = 0;
+ while (i < children.length) {
+ const item = children[i];
+ if (!$isListItemNode(item) || isNestingWrapper(item)) return null;
+ const group = $collectNestedGroup(item);
+ const cells = $groupToCells(group);
+ if (cells.length === 0) return null;
+ columns.push({ header: item, cells });
+ i += group.length;
+ }
+ return columns.length >= 2 ? columns : null;
+}
+
+/**
+ * Whether LIST_TO_TABLE_COMMAND would convert this list. Requires a top-level
+ * list (tables aren't allowed inside table cells or other lists) with a table
+ * shape.
+ */
+export function $canConvertListToTable(list: ListNode): boolean {
+ return $isRootNode(list.getParent()) && $listToGrid(list) !== null;
+}
+
+/**
+ * The convertible list containing the current selection, if any. Must be
+ * called within a Lexical read/update context.
+ */
+export function $getConvertibleListFromSelection(): ListNode | null {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return null;
+ const list = selection.anchor.getNode().getTopLevelElement();
+ return $isListNode(list) && $canConvertListToTable(list) ? list : null;
+}
+
+/** Moves a cell's source content out of the list into a fresh table cell. */
+function $fillCell(
+ cell: TableCellNode,
+ source: ListGridCell,
+ listType: ListType
+): TableCellNode {
+ const paragraph = $createParagraphNode();
+ for (const child of source.item.getChildren()) {
+ if (!$isListNode(child)) paragraph.append(child);
+ }
+ cell.append(paragraph);
+ for (const nested of source.nestedLists) cell.append(nested);
+ if (source.deepItems.length > 0) {
+ const list = $createListNode(listType);
+ list.append(...source.deepItems);
+ cell.append(list);
+ }
+ return cell;
+}
+
+/**
+ * Builds a table from the grid, moving the list's content into it. Ragged
+ * columns are padded with empty cells. The caller replaces the (now gutted)
+ * list with the returned table.
+ */
+export function $gridToTable(
+ columns: ListGridColumn[],
+ listType: ListType
+): TableNode {
+ const table = $createTableNode();
+
+ const headerRow = $createTableRowNode();
+ for (const column of columns) {
+ headerRow.append(
+ $fillCell(
+ $createTableCellNode(TableCellHeaderStates.ROW),
+ { item: column.header, nestedLists: [], deepItems: [] },
+ listType
+ )
+ );
+ }
+ table.append(headerRow);
+
+ const rowCount = Math.max(...columns.map((column) => column.cells.length));
+ for (let r = 0; r < rowCount; r++) {
+ const row = $createTableRowNode();
+ for (const column of columns) {
+ const cell = $createTableCellNode(TableCellHeaderStates.NO_STATUS);
+ const source = column.cells[r];
+ if (source) $fillCell(cell, source, listType);
+ else cell.append($createParagraphNode());
+ row.append(cell);
+ }
+ table.append(row);
+ }
+ return table;
+}
+
+function $selectTableStart(table: TableNode): void {
+ const row = table.getFirstChild();
+ const cell = $isElementNode(row) ? row.getFirstChild() : null;
+ const paragraph = $isElementNode(cell) ? cell.getFirstChild() : null;
+ if ($isElementNode(paragraph)) paragraph.selectEnd();
+}
+
+export function registerListToTableCommand(editor: LexicalEditor): () => void {
+ return editor.registerCommand(
+ LIST_TO_TABLE_COMMAND,
+ (listKey) => {
+ const list = $getNodeByKey(listKey);
+ if (!$isListNode(list) || !$isRootNode(list.getParent())) return false;
+ const columns = $listToGrid(list);
+ if (!columns) return false;
+ const table = $gridToTable(columns, list.getListType());
+ list.replace(table);
+ $selectTableStart(table);
+ return true;
+ },
+ COMMAND_PRIORITY_EDITOR
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTablePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTablePlugin.ts
new file mode 100644
index 0000000000..bdf9242c09
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/listToTablePlugin.ts
@@ -0,0 +1,7 @@
+import type { LexicalEditor } from 'lexical';
+import { registerListToTableCommand } from './listToTable';
+
+/** List → table conversion: registers LIST_TO_TABLE_COMMAND. */
+export function listToTablePlugin() {
+ return (editor: LexicalEditor) => registerListToTableCommand(editor);
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableActionMenuPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableActionMenuPlugin.ts
deleted file mode 100644
index 4446ea0605..0000000000
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableActionMenuPlugin.ts
+++ /dev/null
@@ -1,279 +0,0 @@
-import {
- $getTableCellNodeFromLexicalNode,
- $getTableNodeFromLexicalNodeOrThrow,
- $isTableCellNode,
- $isTableSelection,
- getTableElement,
- getTableObserverFromTableElement,
- TableCellNode,
- TableNode,
- type TableObserver,
-} from '@lexical/table';
-import { mergeRegister } from '@lexical/utils';
-import { createCallback } from '@solid-primitives/rootless';
-import {
- $getSelection,
- $isRangeSelection,
- COMMAND_PRIORITY_CRITICAL,
- getDOMSelection,
- type LexicalEditor,
- SELECTION_CHANGE_COMMAND,
-} from 'lexical';
-import type { Accessor } from 'solid-js';
-import { nodeByKey } from '../../utils';
-import { registerEditorWidthObserver } from '../shared/utils';
-
-interface TableActionsMenuPluginProps {
- menuButtonRef: Accessor<HTMLDivElement | undefined>;
- anchorElem: Accessor<HTMLElement | undefined>;
- tableCellNodeKey: Accessor<string | undefined>;
- setTableCellNodeKey: (cellNode: string | null) => void;
-}
-
-const checkTableCellOverflow = createCallback(
- (tableCellParentNodeDOM: HTMLElement): boolean => {
- const scrollableContainer = tableCellParentNodeDOM.closest(
- '.md-table-scrollable-wrapper'
- );
- if (scrollableContainer) {
- const containerRect = (
- scrollableContainer as HTMLElement
- ).getBoundingClientRect();
- const cellRect = tableCellParentNodeDOM.getBoundingClientRect();
-
- // Calculate where the action button would be positioned (5px from right edge of cell)
- // Also account for the button width and table cell padding (8px)
- const actionButtonRight = cellRect.right - 5;
- const actionButtonLeft = actionButtonRight - 28; // 20px width + 8px padding
-
- // Only hide if the action button would overflow the container
- if (
- actionButtonRight > containerRect.right ||
- actionButtonLeft < containerRect.left
- ) {
- return true;
- }
- }
- return false;
- }
-);
-
-function registerTableActionMenuPlugin(
- editor: LexicalEditor,
- props: TableActionsMenuPluginProps
-) {
- const $moveMenu = createCallback(() => {
- const menu = props.menuButtonRef();
-
- function disable() {
- if (menu) {
- menu.classList.remove('table-cell-action-button-container--active');
- menu.classList.add('table-cell-action-button-container--inactive');
- }
- props.setTableCellNodeKey(null);
- }
-
- if (!menu) {
- return disable();
- }
-
- const selection = $getSelection();
- const nativeSelection = getDOMSelection(editor._window);
- const activeElement = document.activeElement;
-
- if (selection === null || menu === null) {
- return disable();
- }
-
- const rootElement = editor.getRootElement();
- let tableObserver: TableObserver | null = null;
- let tableCellParentNodeDOM: HTMLElement | null = null;
- let tableCellNodeFromSelection: TableCellNode | null = null;
-
- if (
- $isRangeSelection(selection) &&
- rootElement !== null &&
- nativeSelection !== null &&
- rootElement.contains(nativeSelection.anchorNode)
- ) {
- tableCellNodeFromSelection = $getTableCellNodeFromLexicalNode(
- selection.anchor.getNode()
- );
-
- if (!tableCellNodeFromSelection) {
- return disable();
- }
-
- tableCellParentNodeDOM = editor.getElementByKey(
- tableCellNodeFromSelection.getKey()
- );
-
- if (
- tableCellParentNodeDOM === null ||
- !tableCellNodeFromSelection.isAttached()
- ) {
- return disable();
- }
-
- if (checkTableCellOverflow(tableCellParentNodeDOM)) {
- return disable();
- }
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(
- tableCellNodeFromSelection
- );
- const tableElement = getTableElement(
- tableNode,
- editor.getElementByKey(tableNode.getKey())
- );
-
- if (!tableElement) {
- return disable();
- }
- tableObserver = getTableObserverFromTableElement(tableElement);
- } else if ($isTableSelection(selection)) {
- const anchorNode = $getTableCellNodeFromLexicalNode(
- selection.anchor.getNode()
- );
-
- if (!$isTableCellNode(anchorNode)) {
- return disable();
- }
-
- const tableNode = $getTableNodeFromLexicalNodeOrThrow(anchorNode);
- const tableElement = getTableElement(
- tableNode,
- editor.getElementByKey(tableNode.getKey())
- );
-
- if (!tableElement) {
- return disable();
- }
-
- tableObserver = getTableObserverFromTableElement(tableElement);
- tableCellParentNodeDOM = editor.getElementByKey(anchorNode.getKey());
- } else if (!activeElement) {
- return disable();
- }
-
- if (!tableObserver || !tableCellParentNodeDOM) {
- return disable();
- }
-
- const enabled = !tableObserver || !tableObserver.isSelecting;
- const anchorElem = props.anchorElem();
-
- if (
- enabled &&
- anchorElem &&
- tableCellParentNodeDOM &&
- tableCellNodeFromSelection
- ) {
- props.setTableCellNodeKey(tableCellNodeFromSelection.getKey());
-
- menu.classList.toggle(
- 'table-cell-action-button-container--active',
- enabled
- );
- menu.classList.toggle(
- 'table-cell-action-button-container--inactive',
- !enabled
- );
-
- // Calculate position
- const tableCellRect = tableCellParentNodeDOM.getBoundingClientRect();
- const anchorRect = anchorElem.getBoundingClientRect();
- const top = tableCellRect.top - anchorRect.top;
- const left = tableCellRect.right - anchorRect.left;
- const offsetX = -35;
- const offsetY = 10;
-
- // Set positioning
- menu.style.position = 'absolute';
- menu.style.top = '0';
- menu.style.left = '0';
- menu.style.transform = `translate(${left + offsetX}px, ${top + offsetY}px)`;
- }
- });
-
- // Handle delayed callback for menu movement
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
-
- const delayedCallback = (delay = 10) => {
- if (!timeoutId) {
- timeoutId = setTimeout(() => {
- timeoutId = undefined;
- editor.read($moveMenu);
- }, delay);
- }
- return false;
- };
-
- return mergeRegister(
- editor.registerUpdateListener(() => delayedCallback(100)),
-
- editor.registerCommand(
- SELECTION_CHANGE_COMMAND,
- () => delayedCallback(0),
- COMMAND_PRIORITY_CRITICAL
- ),
-
- editor.registerRootListener((rootElement, prevRootElement) => {
- const noDelayCallback = () => delayedCallback(0);
- if (prevRootElement) {
- prevRootElement.removeEventListener('pointerup', noDelayCallback);
- }
- if (rootElement) {
- rootElement.addEventListener('pointerup', noDelayCallback);
- noDelayCallback();
- }
- }),
-
- // Add table scroll listeners.
- editor.registerMutationListener(
- TableNode,
- (mutations) => {
- for (const [key, mutation] of mutations) {
- if (mutation === 'created') {
- const tableElement = editor.getElementByKey(key);
- if (tableElement) {
- tableElement.addEventListener('scroll', () => delayedCallback(0));
- }
- }
- }
- },
- { skipInitialization: false }
- ),
-
- registerEditorWidthObserver(editor, () => {
- delayedCallback();
- }),
-
- editor.registerMutationListener(
- TableCellNode,
- createCallback((nodeMutations) => {
- const _tableCellNodeKey = props.tableCellNodeKey();
- if (!_tableCellNodeKey) return;
-
- const _tableCellNode = nodeByKey(editor, _tableCellNodeKey);
- if (!_tableCellNode) return;
-
- const nodeUpdated =
- nodeMutations.get(_tableCellNode.getKey()) === 'updated';
- if (nodeUpdated) {
- editor.read(() => {
- props.setTableCellNodeKey(_tableCellNode.getLatest().getKey());
- });
- }
- }),
- { skipInitialization: true }
- ),
-
- () => clearTimeout(timeoutId)
- );
-}
-
-export function tableActionMenuPlugin(props: TableActionsMenuPluginProps) {
- return (editor: LexicalEditor) =>
- registerTableActionMenuPlugin(editor, props);
-}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts
new file mode 100644
index 0000000000..9054547cf5
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.test.ts
@@ -0,0 +1,202 @@
+import {
+ $createTableCellNode,
+ $createTableNode,
+ $createTableRowNode,
+ TableCellHeaderStates,
+} from '@lexical/table';
+import { $getRoot, type LexicalEditor } from 'lexical';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ $applyResizeDrag,
+ $captureResizeDrag,
+ $revertResizeDrag,
+ MIN_COLUMN_WIDTH,
+} from './tableCellResize';
+import {
+ $getCell,
+ $getTable,
+ buildTable,
+ coordGrid,
+ createTableTestEditor,
+} from './tableTestUtils';
+
+function createTestEditor(): LexicalEditor {
+ return createTableTestEditor();
+}
+
+function getCellElement(
+ editor: LexicalEditor,
+ row: number,
+ column: number
+): HTMLElement {
+ const cellKey = editor.read(() => $getCell(row, column).getKey());
+ const elem = editor.getElementByKey(cellKey);
+ if (!elem) throw new Error('no cell element');
+ return elem;
+}
+
+// jsdom lays nothing out, so rendered sizes are stubbed per element.
+function stubRect(elem: HTMLElement, width: number) {
+ elem.getBoundingClientRect = () =>
+ ({
+ width,
+ height: 0,
+ top: 0,
+ left: 0,
+ right: width,
+ bottom: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }) as DOMRect;
+}
+
+function getColWidths(editor: LexicalEditor): readonly number[] | undefined {
+ return editor.read(() => $getTable().getColWidths());
+}
+
+describe('table column resize drag', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('captures rendered column widths and applies the delta live', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 3));
+ const renderedWidths = [150, 200, 250];
+ for (let row = 0; row < 2; row++) {
+ for (let column = 0; column < 3; column++) {
+ stubRect(getCellElement(editor, row, column), renderedWidths[column]);
+ }
+ }
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 1), 'right', 1)
+ );
+ expect(drag).toMatchObject({
+ columnIndex: 1,
+ baseWidths: renderedWidths,
+ revertWidths: undefined,
+ });
+
+ editor.update(() => $applyResizeDrag(drag!, 40));
+ expect(getColWidths(editor)).toEqual([150, 240, 250]);
+
+ // Each frame applies against the drag-start snapshot, not the last frame.
+ editor.update(() => $applyResizeDrag(drag!, 10));
+ expect(getColWidths(editor)).toEqual([150, 210, 250]);
+ });
+
+ it('resizes the previous column when dragging a left edge', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(1, 3));
+ for (let column = 0; column < 3; column++) {
+ stubRect(getCellElement(editor, 0, column), 100 + column * 10);
+ }
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 1), 'left', 1)
+ );
+ expect(drag).toMatchObject({ columnIndex: 0 });
+
+ editor.update(() => $applyResizeDrag(drag!, 30));
+ expect(getColWidths(editor)).toEqual([130, 110, 120]);
+ });
+
+ it('has no drag for the left edge of the first column', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(1, 2));
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 0), 'left', 1)
+ );
+ expect(drag).toBeUndefined();
+ });
+
+ it('clamps the column to the minimum width', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(1, 2));
+ stubRect(getCellElement(editor, 0, 0), 300);
+ stubRect(getCellElement(editor, 0, 1), 300);
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 0), 'right', 1)
+ );
+ editor.update(() => $applyResizeDrag(drag!, -1000));
+ expect(getColWidths(editor)).toEqual([MIN_COLUMN_WIDTH, 300]);
+ });
+
+ it('resizes the last spanned column of a merged cell', async () => {
+ const editor = createTestEditor();
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const table = $createTableNode();
+ const mergedRow = $createTableRowNode();
+ mergedRow.append(
+ $createTableCellNode(TableCellHeaderStates.NO_STATUS, 2),
+ $createTableCellNode(TableCellHeaderStates.NO_STATUS)
+ );
+ const plainRow = $createTableRowNode();
+ for (let c = 0; c < 3; c++) {
+ plainRow.append(
+ $createTableCellNode(TableCellHeaderStates.NO_STATUS)
+ );
+ }
+ table.append(mergedRow, plainRow);
+ $getRoot().clear().append(table);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+ for (let column = 0; column < 3; column++) {
+ stubRect(getCellElement(editor, 1, column), 100 + column * 10);
+ }
+
+ const mergedCellElem = getCellElement(editor, 0, 0);
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, mergedCellElem, 'right', 1)
+ );
+ expect(drag).toMatchObject({ columnIndex: 1 });
+
+ editor.update(() => $applyResizeDrag(drag!, 50));
+ expect(getColWidths(editor)).toEqual([100, 160, 120]);
+ });
+
+ it('reverts a cancelled drag to the pre-drag colWidths', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(1, 2));
+ await new Promise<void>((resolve) => {
+ editor.update(() => $getTable().setColWidths([130, 140]), {
+ onUpdate: () => resolve(),
+ });
+ });
+ stubRect(getCellElement(editor, 0, 0), 130);
+ stubRect(getCellElement(editor, 0, 1), 140);
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 0), 'right', 1)
+ );
+ editor.update(() => $applyResizeDrag(drag!, 400));
+ expect(getColWidths(editor)).toEqual([530, 140]);
+
+ editor.update(() => $revertResizeDrag(drag!));
+ expect(getColWidths(editor)).toEqual([130, 140]);
+ });
+
+ it('reverts to unset colWidths when the table had none', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(1, 2));
+ stubRect(getCellElement(editor, 0, 0), 200);
+ stubRect(getCellElement(editor, 0, 1), 200);
+
+ const drag = editor.read(() =>
+ $captureResizeDrag(editor, getCellElement(editor, 0, 0), 'right', 1)
+ );
+ editor.update(() => $applyResizeDrag(drag!, 25));
+ expect(getColWidths(editor)).toEqual([225, 200]);
+
+ editor.update(() => $revertResizeDrag(drag!));
+ expect(getColWidths(editor)).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts
new file mode 100644
index 0000000000..241236f815
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResize.ts
@@ -0,0 +1,102 @@
+/**
+ * @file Column resize logic for tables, driven by the TableCellResizer
+ * component. A drag captures a snapshot up front (which column, the rendered
+ * widths, and the stored widths to restore on cancel), then applies its
+ * running delta against that snapshot on every frame.
+ */
+import {
+ $computeTableMapSkipCellCheck,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $isTableCellNode,
+ $isTableNode,
+} from '@lexical/table';
+import {
+ $getNearestNodeFromDOMNode,
+ $getNodeByKey,
+ type LexicalEditor,
+} from 'lexical';
+
+export const MIN_COLUMN_WIDTH = 120;
+
+// Which vertical edge of the cell is being dragged. Both name a column
+// border: 'right' resizes the cell's own (last spanned) column, 'left' the
+// column before it.
+export type ResizeEdge = 'left' | 'right';
+
+export type ResizeDragSnapshot = {
+ tableKey: string;
+ columnIndex: number;
+ // Rendered column widths at drag start; the drag applies its delta to
+ // these so the grabbed edge stays under the pointer even when the stored
+ // colWidths disagree with the browser's actual layout.
+ baseWidths: number[];
+ revertWidths: readonly number[] | undefined;
+};
+
+export function $captureResizeDrag(
+ editor: LexicalEditor,
+ cellElem: HTMLElement,
+ edge: ResizeEdge,
+ zoom: number
+): ResizeDragSnapshot | undefined {
+ const cellNode = $getNearestNodeFromDOMNode(cellElem);
+ if (!$isTableCellNode(cellNode)) return;
+ const tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNode);
+
+ const [tableMap] = $computeTableMapSkipCellCheck(tableNode, null, null);
+ const position = tableMap.flat().find((value) => value.cell === cellNode);
+ if (!position) return;
+ // A merged cell's right edge belongs to the last column it spans.
+ const columnIndex =
+ edge === 'right'
+ ? position.startColumn + cellNode.getColSpan() - 1
+ : position.startColumn - 1;
+ if (columnIndex < 0) return;
+
+ const revertWidths = tableNode.getColWidths();
+ const columnCount = tableMap[0]?.length ?? 0;
+ const baseWidths: number[] = [];
+ for (let column = 0; column < columnCount; column++) {
+ // Measure the column through any unmerged cell in it that has a layout
+ // (zero width means hidden or not laid out yet).
+ let width: number | undefined;
+ for (const mapRow of tableMap) {
+ const entry = mapRow[column];
+ if (entry.cell.getColSpan() !== 1) continue;
+ const rect = editor
+ .getElementByKey(entry.cell.getKey())
+ ?.getBoundingClientRect();
+ if (rect && rect.width > 0) {
+ width = rect.width / zoom;
+ break;
+ }
+ }
+ baseWidths.push(width ?? revertWidths?.[column] ?? MIN_COLUMN_WIDTH);
+ }
+ return {
+ tableKey: tableNode.getKey(),
+ columnIndex,
+ baseWidths,
+ revertWidths,
+ };
+}
+
+export function $applyResizeDrag(
+ drag: ResizeDragSnapshot,
+ delta: number
+): void {
+ const tableNode = $getNodeByKey(drag.tableKey);
+ if (!$isTableNode(tableNode) || !tableNode.isAttached()) return;
+ const widths = [...drag.baseWidths];
+ widths[drag.columnIndex] = Math.max(
+ MIN_COLUMN_WIDTH,
+ drag.baseWidths[drag.columnIndex] + delta
+ );
+ tableNode.setColWidths(widths);
+}
+
+export function $revertResizeDrag(drag: ResizeDragSnapshot): void {
+ const tableNode = $getNodeByKey(drag.tableKey);
+ if (!$isTableNode(tableNode) || !tableNode.isAttached()) return;
+ tableNode.setColWidths(drag.revertWidths);
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin.ts
index f96d262172..807f79f4cd 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin.ts
@@ -8,7 +8,7 @@
import { TableNode } from '@lexical/table';
import { mergeRegister } from '@lexical/utils';
import type { LexicalEditor } from 'lexical';
-import { MIN_COLUMN_WIDTH } from '../../component/misc/TableCellResizer';
+import { MIN_COLUMN_WIDTH } from './tableCellResize';
function registerTableCellResizerPlugin(editor: LexicalEditor) {
return mergeRegister(
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableClear.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableClear.test.ts
new file mode 100644
index 0000000000..7b0f520508
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableClear.test.ts
@@ -0,0 +1,157 @@
+import { $createTableSelection } from '@lexical/table';
+import {
+ $isParagraphNode,
+ $setSelection,
+ CUT_COMMAND,
+ KEY_BACKSPACE_COMMAND,
+ KEY_DELETE_COMMAND,
+ type LexicalCommand,
+ type LexicalEditor,
+} from 'lexical';
+import { describe, expect, it, vi } from 'vitest';
+
+// markdownPastePlugin (pulled in transitively) only needs this for plain-text
+// pastes, which these tests never exercise.
+vi.mock('../../utils', () => ({
+ setEditorStateFromMarkdown: vi.fn(),
+}));
+
+import {
+ $getCell,
+ $getTable,
+ buildTable,
+ createTableTestEditor,
+ readCellTexts,
+ textGrid,
+} from './tableTestUtils';
+
+// jsdom implements neither ClipboardEvent nor execCommand; the cut path only
+// needs `instanceof ClipboardEvent` checks to fail so it takes the null branch.
+if (typeof globalThis.ClipboardEvent === 'undefined') {
+ class PolyfillClipboardEvent extends Event {
+ clipboardData: DataTransfer | null = null;
+ }
+ globalThis.ClipboardEvent =
+ PolyfillClipboardEvent as unknown as typeof ClipboardEvent;
+}
+if (typeof document.execCommand !== 'function') {
+ document.execCommand = () => true;
+}
+
+function createTableEditor(): LexicalEditor {
+ return createTableTestEditor();
+}
+
+/** Selects the rectangle of cells and dispatches `command`. */
+async function selectAndDispatch(
+ editor: LexicalEditor,
+ from: [number, number],
+ to: [number, number],
+ command: LexicalCommand<unknown>,
+ payload: unknown
+) {
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const selection = $createTableSelection();
+ selection.set(
+ $getTable().getKey(),
+ $getCell(...from).getKey(),
+ $getCell(...to).getKey()
+ );
+ $setSelection(selection);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+ editor.dispatchCommand(command, payload);
+ await Promise.resolve();
+}
+
+const GRID = [
+ ['01', '02', '03'],
+ ['04', '05', '06'],
+ ['07', '08', '09'],
+];
+
+describe('table cell clearing', () => {
+ it('clears the selected cells on cut', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, textGrid(GRID));
+
+ await selectAndDispatch(
+ editor,
+ [0, 0],
+ [1, 1],
+ CUT_COMMAND as LexicalCommand<unknown>,
+ null
+ );
+
+ expect(readCellTexts(editor)).toEqual([
+ ['', '', '03'],
+ ['', '', '06'],
+ ['07', '08', '09'],
+ ]);
+ });
+
+ it('clears the selected cells on Delete', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, textGrid(GRID));
+
+ await selectAndDispatch(
+ editor,
+ [0, 0],
+ [0, 2],
+ KEY_DELETE_COMMAND as LexicalCommand<unknown>,
+ null
+ );
+
+ expect(readCellTexts(editor)).toEqual([
+ ['', '', ''],
+ ['04', '05', '06'],
+ ['07', '08', '09'],
+ ]);
+ });
+
+ it('clears the selected cells on Backspace', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, textGrid(GRID));
+
+ await selectAndDispatch(
+ editor,
+ [2, 0],
+ [2, 2],
+ KEY_BACKSPACE_COMMAND as LexicalCommand<unknown>,
+ null
+ );
+
+ expect(readCellTexts(editor)).toEqual([
+ ['01', '02', '03'],
+ ['04', '05', '06'],
+ ['', '', ''],
+ ]);
+ });
+
+ it('leaves each cleared cell with a childless paragraph (no empty TextNode)', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, textGrid(GRID));
+
+ await selectAndDispatch(
+ editor,
+ [0, 0],
+ [0, 0],
+ KEY_DELETE_COMMAND as LexicalCommand<unknown>,
+ null
+ );
+
+ editor.getEditorState().read(() => {
+ const children = $getCell(0, 0).getChildren();
+ expect(children).toHaveLength(1);
+ const paragraph = children[0];
+ if (!$isParagraphNode(paragraph)) throw new Error('not a paragraph');
+ // The crash we're guarding against comes from an empty TextNode that the
+ // text normalizer tries to remove — so there must be none here.
+ expect(paragraph.getChildrenSize()).toBe(0);
+ });
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.test.ts
new file mode 100644
index 0000000000..00c55af55a
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.test.ts
@@ -0,0 +1,112 @@
+import { $isListItemNode } from '@lexical/list';
+import { $isTableCellNode } from '@lexical/table';
+import { $findMatchingParent } from '@lexical/utils';
+import { $getSelection, $isRangeSelection, type LexicalEditor } from 'lexical';
+import { describe, expect, it } from 'vitest';
+import {
+ $createListCell,
+ $createTextCell,
+ $getCell,
+ buildTable,
+ createTableTestEditor,
+ placeCaret,
+ pressTab,
+} from './tableTestUtils';
+
+function createTableEditor(): LexicalEditor {
+ return createTableTestEditor({ tabIndentation: true });
+}
+
+function readAnchorListItemIndent(editor: LexicalEditor): number | null {
+ return editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return null;
+ const listItem = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isListItemNode
+ );
+ return listItem ? listItem.getIndent() : null;
+ });
+}
+
+function readAnchorCellKey(editor: LexicalEditor): string | null {
+ return editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return null;
+ const cell = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isTableCellNode
+ );
+ return cell ? cell.getKey() : null;
+ });
+}
+
+function readCellKey(editor: LexicalEditor, row: number, column: number) {
+ return editor.getEditorState().read(() => $getCell(row, column).getKey());
+}
+
+describe('tab inside lists in table cells', () => {
+ it('indents a list item instead of hopping to the next cell', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createListCell(['one', 'two']), () => $createTextCell('other')],
+ ]);
+ await placeCaret(editor, 'two');
+
+ await pressTab(editor);
+
+ expect(readAnchorListItemIndent(editor)).toBe(1);
+ expect(readAnchorCellKey(editor)).toBe(readCellKey(editor, 0, 0));
+ });
+
+ it('falls through to cell navigation once the item cannot indent deeper', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createListCell(['one', 'two']), () => $createTextCell('other')],
+ ]);
+ await placeCaret(editor, 'two');
+
+ await pressTab(editor); // indent to depth 1
+ await pressTab(editor); // cannot go deeper -> hop to next cell
+
+ expect(readAnchorCellKey(editor)).toBe(readCellKey(editor, 0, 1));
+ });
+
+ it('outdents a nested list item on Shift+Tab', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createListCell(['one', 'two']), () => $createTextCell('other')],
+ ]);
+ await placeCaret(editor, 'two');
+
+ await pressTab(editor);
+ expect(readAnchorListItemIndent(editor)).toBe(1);
+
+ await pressTab(editor, true);
+ expect(readAnchorListItemIndent(editor)).toBe(0);
+ });
+
+ it('navigates to the previous cell on Shift+Tab at the top level', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('first'), () => $createListCell(['one', 'two'])],
+ ]);
+ await placeCaret(editor, 'two');
+
+ await pressTab(editor, true);
+
+ expect(readAnchorCellKey(editor)).toBe(readCellKey(editor, 0, 0));
+ });
+
+ it('still navigates cells from plain paragraph content', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('first'), () => $createTextCell('second')],
+ ]);
+ await placeCaret(editor, 'first');
+
+ await pressTab(editor);
+
+ expect(readAnchorCellKey(editor)).toBe(readCellKey(editor, 0, 1));
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.ts
new file mode 100644
index 0000000000..2eb5cd058c
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableListTab.ts
@@ -0,0 +1,59 @@
+import { $isListItemNode } from '@lexical/list';
+import { $isTableCellNode } from '@lexical/table';
+import { $findMatchingParent } from '@lexical/utils';
+import {
+ $getSelection,
+ $isElementNode,
+ $isRangeSelection,
+ COMMAND_PRIORITY_CRITICAL,
+ INDENT_CONTENT_COMMAND,
+ KEY_TAB_COMMAND,
+ type LexicalEditor,
+ OUTDENT_CONTENT_COMMAND,
+} from 'lexical';
+
+/**
+ * The table selection observer claims Tab at HIGH priority to hop between
+ * cells, which makes list indentation unreachable inside cells. Claim Tab
+ * first when the caret is in a list item that can indent (or outdent, for
+ * Shift+Tab), and fall through to cell navigation otherwise.
+ */
+export function registerTableListTab(editor: LexicalEditor) {
+ return editor.registerCommand<KeyboardEvent>(
+ KEY_TAB_COMMAND,
+ (event) => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
+ return false;
+ }
+
+ const listItem = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isListItemNode
+ );
+ if (!listItem || !$findMatchingParent(listItem, $isTableCellNode)) {
+ return false;
+ }
+
+ if (event.shiftKey) {
+ if (listItem.getIndent() <= 0) return false;
+ event.preventDefault();
+ editor.dispatchCommand(OUTDENT_CONTENT_COMMAND, undefined);
+ return true;
+ }
+
+ // Same depth limit as tabIndentationPlugin: at most one level deeper
+ // than the previous sibling.
+ const prevSibling = listItem.getPreviousSibling();
+ const prevDepth = $isElementNode(prevSibling)
+ ? prevSibling.getIndent()
+ : 0;
+ if (listItem.getIndent() >= prevDepth + 1) return false;
+
+ event.preventDefault();
+ editor.dispatchCommand(INDENT_CONTENT_COMMAND, undefined);
+ return true;
+ },
+ COMMAND_PRIORITY_CRITICAL
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableMove.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableMove.ts
new file mode 100644
index 0000000000..601acfed8f
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableMove.ts
@@ -0,0 +1,96 @@
+import {
+ $generateJSONFromSelectedNodes,
+ $generateNodesFromSerializedNodes,
+} from '@lexical/clipboard';
+import {
+ $createTableSelection,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $isTableCellNode,
+ $isTableRowNode,
+ type TableCellNode,
+ type TableNode,
+} from '@lexical/table';
+import {
+ $createParagraphNode,
+ $getSelection,
+ type LexicalEditor,
+ type LexicalNode,
+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,
+} from 'lexical';
+
+/**
+ * Moves the contents of the cell range spanned by `anchorCell`..`focusCell`
+ * onto the grid anchored at `targetCell`: the range is snapshotted, the
+ * source cells are emptied, and the snapshot is dispatched through the same
+ * grid-insert command as pasting a copied range — so overflow growth (new
+ * rows/columns) and node-id reassignment behave identically to paste.
+ *
+ * Must be called inside an editor update. Returns true when a move happened.
+ */
+export function $moveCellRange(
+ editor: LexicalEditor,
+ anchorCell: TableCellNode,
+ focusCell: TableCellNode,
+ targetCell: TableCellNode
+): boolean {
+ const table = $getTableNodeFromLexicalNodeOrThrow(anchorCell);
+ const sourceSelection = $createTableSelection();
+ sourceSelection.set(table.getKey(), anchorCell.getKey(), focusCell.getKey());
+ const sourceCells = sourceSelection.getNodes().filter($isTableCellNode);
+
+ if (sourceCells.length === 0) return false;
+ if (sourceCells.some((cell) => cell.is(targetCell))) return false;
+
+ const serialized = $generateJSONFromSelectedNodes(
+ editor,
+ sourceSelection
+ ).nodes;
+ const nodes = $generateNodesFromSerializedNodes(serialized);
+
+ for (const cell of sourceCells) {
+ cell.clear();
+ cell.append($createParagraphNode());
+ }
+
+ targetCell.selectStart();
+ const dropSelection = $getSelection();
+ if (!dropSelection) {
+ $restoreSourceCells(sourceCells, nodes);
+ return false;
+ }
+
+ const handled = editor.dispatchCommand(
+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,
+ { nodes, selection: dropSelection }
+ );
+ if (!handled) {
+ $restoreSourceCells(sourceCells, nodes);
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Fallback if the grid-insert command went unhandled after the source cells
+ * were already emptied: put the snapshotted content back.
+ */
+function $restoreSourceCells(
+ sourceCells: TableCellNode[],
+ nodes: LexicalNode[]
+): void {
+ const template = nodes[0] as TableNode | undefined;
+ if (!template) return;
+ const templateCells: TableCellNode[] = [];
+ for (const row of template.getChildren()) {
+ if (!$isTableRowNode(row)) continue;
+ for (const cell of row.getChildren()) {
+ if ($isTableCellNode(cell)) templateCells.push(cell);
+ }
+ }
+ sourceCells.forEach((cell, index) => {
+ const templateCell = templateCells[index];
+ if (!templateCell) return;
+ cell.clear();
+ cell.append(...templateCell.getChildren());
+ });
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePickerPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePickerPlugin.ts
new file mode 100644
index 0000000000..7ea7dc55c4
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePickerPlugin.ts
@@ -0,0 +1,41 @@
+import {
+ $getSelection,
+ COMMAND_PRIORITY_NORMAL,
+ createCommand,
+ type LexicalCommand,
+ type LexicalEditor,
+} from 'lexical';
+
+type TablePickerPluginProps = {
+ onCreateTable: () => void;
+};
+
+/**
+ * Requests the table size picker UI. Handled by FloatingTableMenu when
+ * mounted; dispatchers should fall back to a direct insert when this
+ * returns false.
+ */
+export const TRY_INSERT_TABLE_PICKER_COMMAND: LexicalCommand<void> =
+ createCommand('TRY_INSERT_TABLE_PICKER_COMMAND');
+
+function registerTablePickerPlugin(
+ editor: LexicalEditor,
+ props: TablePickerPluginProps
+) {
+ return editor.registerCommand(
+ TRY_INSERT_TABLE_PICKER_COMMAND,
+ () => {
+ const selection = $getSelection();
+ if (!selection) {
+ return false;
+ }
+ props.onCreateTable();
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ );
+}
+
+export function tablePickerPlugin(props: TablePickerPluginProps) {
+ return (editor: LexicalEditor) => registerTablePickerPlugin(editor, props);
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePlugin.ts
index a36ebb21c7..2773869c8a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tablePlugin.ts
@@ -7,6 +7,9 @@ import {
} from '@lexical/table';
import { mergeRegister } from '@lexical/utils';
import type { LexicalEditor } from 'lexical';
+import { registerTableListTab } from './tableListTab';
+import { registerTableSelectAll } from './tableSelectAll';
+import { registerTableTabInsertRow } from './tableTabInsertRow';
interface TablePluginProps {
// When `false` (default `true`), merged cell support (colspan and rowspan) will be disabled and all
@@ -30,6 +33,18 @@ function _registerTablePlugin(editor: LexicalEditor, props: TablePluginProps) {
// Register the table selection observer
registerTableSelectionObserver(editor, props.hasTabHandler ?? true),
+ // Let list items claim Tab for indentation before cell navigation
+ (props.hasTabHandler ?? true) ? registerTableListTab(editor) : () => {},
+
+ // Tab in the bottom-right cell grows the table with a new row (registered
+ // after tableListTab so list indentation still wins when it applies)
+ (props.hasTabHandler ?? true)
+ ? registerTableTabInsertRow(editor)
+ : () => {},
+
+ // Ctrl/Cmd+A inside a table selects the table before the document
+ registerTableSelectAll(editor),
+
// Unmerge cells when the feature isn't enabled
(() => {
return !props.hasCellMerge
@@ -47,9 +62,17 @@ function _registerTablePlugin(editor: LexicalEditor, props: TablePluginProps) {
});
})(),
- // Only allow paragraph nodes within Table Cells
+ // Restrict table cells to block content that renders sanely inside them
+ // (notably: no nested tables).
(() => {
- const allowedNodesInTableCellNode = ['paragraph'];
+ const allowedNodesInTableCellNode = [
+ 'paragraph',
+ 'heading',
+ 'list',
+ 'quote',
+ 'code',
+ 'custom-code',
+ ];
return editor.registerNodeTransform(TableCellNode, (node) => {
const children = node.getChildren();
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.test.ts
new file mode 100644
index 0000000000..80ed07b182
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.test.ts
@@ -0,0 +1,141 @@
+import {
+ $createTableNode,
+ $createTableRowNode,
+ $createTableSelectionFrom,
+ $isTableSelection,
+ type TableCellNode,
+ type TableRowNode,
+} from '@lexical/table';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $isRangeSelection,
+ $setSelection,
+ type LexicalEditor,
+ SELECT_ALL_COMMAND,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import {
+ $createTextCell,
+ $getTable,
+ createTableTestEditor,
+ placeCaret,
+} from './tableTestUtils';
+
+function createTableEditor(): LexicalEditor {
+ return createTableTestEditor();
+}
+
+/** Builds: paragraph("before"), 2x2 table, paragraph("after"). */
+async function buildDoc(editor: LexicalEditor) {
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const table = $createTableNode();
+ for (const rowTexts of [
+ ['a1', 'b1'],
+ ['a2', 'b2'],
+ ]) {
+ const row = $createTableRowNode();
+ row.append(...rowTexts.map((text) => $createTextCell(text)));
+ table.append(row);
+ }
+ const before = $createParagraphNode();
+ before.append($createTextNode('before'));
+ const after = $createParagraphNode();
+ after.append($createTextNode('after'));
+ $getRoot().clear().append(before, table, after);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+}
+
+async function pressSelectAll(editor: LexicalEditor) {
+ editor.dispatchCommand(
+ SELECT_ALL_COMMAND,
+ new KeyboardEvent('keydown', { key: 'a', ctrlKey: true })
+ );
+ await Promise.resolve();
+}
+
+describe('tableSelectAll', () => {
+ it('selects the whole table when the caret is in a cell', async () => {
+ const editor = createTableEditor();
+ await buildDoc(editor);
+ await placeCaret(editor, 'b1');
+
+ await pressSelectAll(editor);
+
+ editor.read(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection)) throw new Error('no table selection');
+ const shape = selection.getShape();
+ expect(shape).toEqual({ fromX: 0, fromY: 0, toX: 1, toY: 1 });
+ });
+ });
+
+ it('expands a partial cell selection to the whole table', async () => {
+ const editor = createTableEditor();
+ await buildDoc(editor);
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const table = $getTable();
+ const firstCell = table
+ .getFirstChildOrThrow<TableRowNode>()
+ .getFirstChildOrThrow<TableCellNode>();
+ $setSelection($createTableSelectionFrom(table, firstCell, firstCell));
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ await pressSelectAll(editor);
+
+ editor.read(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection)) throw new Error('no table selection');
+ expect(selection.getShape()).toEqual({
+ fromX: 0,
+ fromY: 0,
+ toX: 1,
+ toY: 1,
+ });
+ });
+ });
+
+ it('escalates to the document when the table is already fully selected', async () => {
+ const editor = createTableEditor();
+ await buildDoc(editor);
+ await placeCaret(editor, 'a2');
+
+ await pressSelectAll(editor);
+ await pressSelectAll(editor);
+
+ editor.read(() => {
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.getTextContent()).toContain('before');
+ expect(selection.getTextContent()).toContain('after');
+ });
+ });
+
+ it('leaves select-all alone outside tables', async () => {
+ const editor = createTableEditor();
+ await buildDoc(editor);
+ await placeCaret(editor, 'before');
+
+ await pressSelectAll(editor);
+
+ editor.read(() => {
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.getTextContent()).toContain('after');
+ });
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.ts
new file mode 100644
index 0000000000..f0b770e85b
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableSelectAll.ts
@@ -0,0 +1,69 @@
+import {
+ $computeTableMapSkipCellCheck,
+ $createTableSelectionFrom,
+ $getTableNodeFromLexicalNodeOrThrow,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableSelection,
+ type TableNode,
+} from '@lexical/table';
+import { $findMatchingParent } from '@lexical/utils';
+import {
+ $getNodeByKey,
+ $getSelection,
+ $isRangeSelection,
+ $setSelection,
+ COMMAND_PRIORITY_HIGH,
+ type LexicalEditor,
+ SELECT_ALL_COMMAND,
+} from 'lexical';
+
+/**
+ * Scope Ctrl/Cmd+A inside a table: select the whole table first, and only
+ * escalate to the document when the table is already fully selected.
+ */
+export function registerTableSelectAll(editor: LexicalEditor) {
+ return editor.registerCommand(
+ SELECT_ALL_COMMAND,
+ () => {
+ const selection = $getSelection();
+
+ let tableNode: TableNode;
+ if ($isRangeSelection(selection)) {
+ const cellNode = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isTableCellNode
+ );
+ if (!cellNode) return false;
+ tableNode = $getTableNodeFromLexicalNodeOrThrow(cellNode);
+ } else if ($isTableSelection(selection)) {
+ const node = $getNodeByKey(selection.tableKey);
+ if (!$isTableNode(node)) return false;
+ tableNode = node;
+ } else {
+ return false;
+ }
+
+ const [tableMap] = $computeTableMapSkipCellCheck(tableNode, null, null);
+ const lastRow = tableMap[tableMap.length - 1];
+ if (!lastRow) return false;
+ const firstCell = tableMap[0][0]?.cell;
+ const lastCell = lastRow[lastRow.length - 1]?.cell;
+ if (!firstCell || !lastCell) return false;
+
+ if ($isTableSelection(selection)) {
+ const shape = selection.getShape();
+ const isFullTable =
+ shape.fromX === 0 &&
+ shape.fromY === 0 &&
+ shape.toX === lastRow.length - 1 &&
+ shape.toY === tableMap.length - 1;
+ if (isFullTable) return false;
+ }
+
+ $setSelection($createTableSelectionFrom(tableNode, firstCell, lastCell));
+ return true;
+ },
+ COMMAND_PRIORITY_HIGH
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.test.ts
new file mode 100644
index 0000000000..c939452798
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.test.ts
@@ -0,0 +1,141 @@
+import { $isListItemNode } from '@lexical/list';
+import { $isTableCellNode, $isTableRowNode } from '@lexical/table';
+import { $findMatchingParent } from '@lexical/utils';
+import { $getSelection, $isRangeSelection, type LexicalEditor } from 'lexical';
+import { describe, expect, it } from 'vitest';
+import {
+ $createListCell,
+ $createTextCell,
+ $getTable,
+ buildTable,
+ createTableTestEditor,
+ placeCaret,
+ pressTab,
+} from './tableTestUtils';
+
+function createTableEditor(): LexicalEditor {
+ return createTableTestEditor({ tabIndentation: true });
+}
+
+function readRowCount(editor: LexicalEditor): number {
+ return editor.getEditorState().read(() => {
+ return $getTable().getChildren().filter($isTableRowNode).length;
+ });
+}
+
+/** Returns the row/column index of the cell holding the caret, or null. */
+function readAnchorCellPosition(
+ editor: LexicalEditor
+): { row: number; column: number } | null {
+ return editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return null;
+ const cell = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isTableCellNode
+ );
+ if (!$isTableCellNode(cell)) return null;
+ const rowNode = cell.getParent();
+ if (!$isTableRowNode(rowNode)) return null;
+ const table = $getTable();
+ const rows = table.getChildren().filter($isTableRowNode);
+ const row = rows.indexOf(rowNode);
+ const column = rowNode.getChildren().filter($isTableCellNode).indexOf(cell);
+ return { row, column };
+ });
+}
+
+/** Indent of the list item holding the caret, or null when not in one. */
+function readAnchorListItemIndent(editor: LexicalEditor): number | null {
+ return editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection)) return null;
+ const listItem = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isListItemNode
+ );
+ return listItem ? listItem.getIndent() : null;
+ });
+}
+
+describe('tab in the bottom-right table cell', () => {
+ it('adds a new row and moves the caret into its first cell', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('a'), () => $createTextCell('b')],
+ [() => $createTextCell('c'), () => $createTextCell('d')],
+ ]);
+ await placeCaret(editor, 'd'); // bottom-right cell
+
+ await pressTab(editor);
+
+ expect(readRowCount(editor)).toBe(3);
+ expect(readAnchorCellPosition(editor)).toEqual({ row: 2, column: 0 });
+ });
+
+ it('does not add a row from a non-terminal cell', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('a'), () => $createTextCell('b')],
+ [() => $createTextCell('c'), () => $createTextCell('d')],
+ ]);
+ await placeCaret(editor, 'a'); // top-left cell
+
+ await pressTab(editor);
+
+ expect(readRowCount(editor)).toBe(2);
+ expect(readAnchorCellPosition(editor)).toEqual({ row: 0, column: 1 });
+ });
+
+ it('does not add a row on Shift+Tab in the bottom-right cell', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('a'), () => $createTextCell('b')],
+ [() => $createTextCell('c'), () => $createTextCell('d')],
+ ]);
+ await placeCaret(editor, 'd');
+
+ await pressTab(editor, true);
+
+ expect(readRowCount(editor)).toBe(2);
+ expect(readAnchorCellPosition(editor)).toEqual({ row: 1, column: 0 });
+ });
+
+ // The list-indent handler (registerTableListTab) is registered before this
+ // row-insert handler, both at CRITICAL priority, so list indentation must
+ // win over row insertion whenever the bottom-right cell holds an indentable
+ // list item.
+ it('indents an indentable list item instead of inserting a row', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('a'), () => $createTextCell('b')],
+ [() => $createTextCell('c'), () => $createListCell(['one', 'two'])],
+ ]);
+ await placeCaret(editor, 'two'); // list item in the bottom-right cell
+
+ await pressTab(editor);
+
+ // List indentation wins; no new row is added.
+ expect(readAnchorListItemIndent(editor)).toBe(1);
+ expect(readRowCount(editor)).toBe(2);
+ expect(readAnchorCellPosition(editor)).toEqual({ row: 1, column: 1 });
+ });
+
+ it('inserts a row once the bottom-right list item can no longer indent', async () => {
+ const editor = createTableEditor();
+ await buildTable(editor, [
+ [() => $createTextCell('a'), () => $createTextCell('b')],
+ [() => $createTextCell('c'), () => $createListCell(['one', 'two'])],
+ ]);
+ await placeCaret(editor, 'two');
+
+ await pressTab(editor); // indent to depth 1
+ expect(readAnchorListItemIndent(editor)).toBe(1);
+ expect(readRowCount(editor)).toBe(2);
+
+ await pressTab(editor); // cannot indent deeper -> falls through to row insert
+
+ expect(readRowCount(editor)).toBe(3);
+ expect(readAnchorCellPosition(editor)).toEqual({ row: 2, column: 0 });
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.ts
new file mode 100644
index 0000000000..a3947aa2b7
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTabInsertRow.ts
@@ -0,0 +1,64 @@
+import {
+ $insertTableRowAtSelection,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+} from '@lexical/table';
+import { $findMatchingParent } from '@lexical/utils';
+import {
+ $getSelection,
+ $isRangeSelection,
+ COMMAND_PRIORITY_CRITICAL,
+ KEY_TAB_COMMAND,
+ type LexicalEditor,
+} from 'lexical';
+
+/**
+ * When Tab is pressed with the caret in the bottom-right cell of a table, the
+ * table selection observer would move the selection out of the table. Instead,
+ * append a new row and drop the caret into its leftmost cell, matching the
+ * "Tab to grow the table" behavior found in most rich-text editors.
+ *
+ * Registered at CRITICAL priority (like {@link registerTableListTab}) so it
+ * preempts the library's HIGH-priority cell-navigation handler. It must be
+ * registered *after* {@link registerTableListTab} so list indentation inside a
+ * cell still wins when it applies.
+ */
+export function registerTableTabInsertRow(editor: LexicalEditor) {
+ return editor.registerCommand<KeyboardEvent>(
+ KEY_TAB_COMMAND,
+ (event) => {
+ // Shift+Tab keeps its "go to previous cell" behavior.
+ if (event.shiftKey) return false;
+
+ const selection = $getSelection();
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
+ return false;
+ }
+
+ const cell = $findMatchingParent(
+ selection.anchor.getNode(),
+ $isTableCellNode
+ );
+ if (!$isTableCellNode(cell)) return false;
+
+ const row = cell.getParent();
+ if (!$isTableRowNode(row)) return false;
+
+ const table = row.getParent();
+ if (!$isTableNode(table)) return false;
+
+ // Only the bottom-right cell: no cell to the right and no row below.
+ if (cell.getNextSibling() !== null || row.getNextSibling() !== null) {
+ return false;
+ }
+
+ event.preventDefault();
+ const newRow = $insertTableRowAtSelection(true);
+ const firstCell = newRow?.getFirstChild();
+ if ($isTableCellNode(firstCell)) firstCell.selectStart();
+ return true;
+ },
+ COMMAND_PRIORITY_CRITICAL
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTestUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTestUtils.ts
new file mode 100644
index 0000000000..83b29410f1
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTestUtils.ts
@@ -0,0 +1,198 @@
+import { $createListItemNode, $createListNode } from '@lexical/list';
+import { registerRichText } from '@lexical/rich-text';
+import {
+ $createTableCellNode,
+ $createTableNode,
+ $createTableRowNode,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+ TableCellHeaderStates,
+ type TableCellNode,
+ type TableNode,
+} from '@lexical/table';
+import { SupportedNodeTypes } from '@macro-inc/lexical-core/node-list';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+ KEY_TAB_COMMAND,
+ type LexicalEditor,
+} from 'lexical';
+import { tabIndentationPlugin } from '../tab-indentation';
+import { tablePlugin } from './tablePlugin';
+import { tableTouchSelectionPlugin } from './tableTouchSelection';
+
+interface CreateTableTestEditorOptions {
+ /** Register {@link tabIndentationPlugin} (needed for list/tab tests). */
+ tabIndentation?: boolean;
+ /** Register {@link tableTouchSelectionPlugin} before rich text. */
+ touchSelection?: boolean;
+ /** Forwarded to {@link tablePlugin}; defaults to `true`. */
+ hasCellMerge?: boolean;
+ /** Forwarded to {@link tablePlugin}; defaults to `true`. */
+ hasCellBackgroundColor?: boolean;
+ /** Forwarded to {@link tablePlugin}; defaults to `true`. */
+ hasTabHandler?: boolean;
+}
+
+/**
+ * Single parameterized editor factory shared by the table plugin tests. The
+ * plugin registration order mirrors the original per-file factories: the table
+ * plugin first, then (optionally) the touch-selection plugin, then rich text,
+ * then (optionally) tab indentation.
+ */
+export function createTableTestEditor(
+ opts: CreateTableTestEditorOptions = {}
+): LexicalEditor {
+ const {
+ tabIndentation = false,
+ touchSelection = false,
+ hasCellMerge = true,
+ hasCellBackgroundColor = true,
+ hasTabHandler = true,
+ } = opts;
+
+ const editor = createEditor({
+ namespace: 'table-test',
+ nodes: SupportedNodeTypes,
+ onError: (error) => {
+ throw error;
+ },
+ });
+ tablePlugin({ hasCellMerge, hasCellBackgroundColor, hasTabHandler })(editor);
+ if (touchSelection) tableTouchSelectionPlugin()(editor);
+ registerRichText(editor);
+ if (tabIndentation) tabIndentationPlugin()(editor);
+ const rootElement = document.createElement('div');
+ rootElement.contentEditable = 'true';
+ document.body.appendChild(rootElement);
+ editor.setRootElement(rootElement);
+ return editor;
+}
+
+/** A cell containing a single paragraph with `text`. */
+export function $createTextCell(text: string): TableCellNode {
+ const cell = $createTableCellNode(TableCellHeaderStates.NO_STATUS);
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode(text));
+ cell.append(paragraph);
+ return cell;
+}
+
+/** A cell containing a bullet list with one item per entry in `items`. */
+export function $createListCell(items: string[]): TableCellNode {
+ const cell = $createTableCellNode(TableCellHeaderStates.NO_STATUS);
+ const list = $createListNode('bullet');
+ for (const item of items) {
+ const listItem = $createListItemNode();
+ listItem.append($createTextNode(item));
+ list.append(listItem);
+ }
+ cell.append(list);
+ return cell;
+}
+
+/**
+ * Builds a table from a grid of cell factories and installs it as the sole
+ * child of the root. The factory-grid shape is the most general; use
+ * {@link textGrid} / {@link coordGrid} to adapt simpler inputs.
+ */
+export async function buildTable(
+ editor: LexicalEditor,
+ grid: Array<Array<() => TableCellNode>>
+) {
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const table = $createTableNode();
+ for (const rowCells of grid) {
+ const row = $createTableRowNode();
+ row.append(...rowCells.map(($createCell) => $createCell()));
+ table.append(row);
+ }
+ $getRoot().clear().append(table);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+}
+
+/** Adapts a `string[][]` grid to text-cell factories for {@link buildTable}. */
+export function textGrid(rows: string[][]): Array<Array<() => TableCellNode>> {
+ return rows.map((row) => row.map((text) => () => $createTextCell(text)));
+}
+
+/**
+ * Produces a `rows`x`columns` grid whose cells are labeled `"${r},${c}"`,
+ * matching the numeric `buildTable(editor, rows, cols)` the resize and touch
+ * tests used to build inline.
+ */
+export function coordGrid(
+ rows: number,
+ columns: number
+): Array<Array<() => TableCellNode>> {
+ return Array.from({ length: rows }, (_, r) =>
+ Array.from(
+ { length: columns },
+ (_, c) => () => $createTextCell(`${r},${c}`)
+ )
+ );
+}
+
+/** The first table node in the document. Must run inside editor.read/update. */
+export function $getTable(): TableNode {
+ const table = $getRoot()
+ .getChildren()
+ .find((node) => $isTableNode(node));
+ if (!table || !$isTableNode(table)) throw new Error('no table');
+ return table;
+}
+
+/** The cell at `row`/`column`. Must run inside editor.read/update. */
+export function $getCell(row: number, column: number): TableCellNode {
+ const rowNode = $getTable().getChildren().filter($isTableRowNode)[row];
+ return rowNode.getChildren().filter($isTableCellNode)[column];
+}
+
+/** The text content of every cell, row by row. */
+export function readCellTexts(editor: LexicalEditor): string[][] {
+ return editor.getEditorState().read(() =>
+ $getTable()
+ .getChildren()
+ .filter($isTableRowNode)
+ .map((row) =>
+ row
+ .getChildren()
+ .filter($isTableCellNode)
+ .map((cell) => cell.getTextContent())
+ )
+ );
+}
+
+/** Places a collapsed caret at the end of the text node matching `text`. */
+export async function placeCaret(editor: LexicalEditor, text: string) {
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const textNode = $getRoot()
+ .getAllTextNodes()
+ .find((node) => node.getTextContent() === text);
+ if (!textNode) throw new Error(`no text node "${text}"`);
+ const size = textNode.getTextContentSize();
+ textNode.select(size, size);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+}
+
+/** Dispatches a Tab (or Shift+Tab) key command and flushes microtasks. */
+export async function pressTab(editor: LexicalEditor, shiftKey = false) {
+ editor.dispatchCommand(
+ KEY_TAB_COMMAND,
+ new KeyboardEvent('keydown', { key: 'Tab', shiftKey })
+ );
+ await Promise.resolve();
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.test.ts
new file mode 100644
index 0000000000..7913702177
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.test.ts
@@ -0,0 +1,260 @@
+import {
+ $getTableCellNodeFromLexicalNode,
+ $isTableSelection,
+ type TableCellNode,
+} from '@lexical/table';
+import { $getSelection, type LexicalEditor } from 'lexical';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ $getCell,
+ buildTable,
+ coordGrid,
+ createTableTestEditor,
+} from './tableTestUtils';
+
+// jsdom implements neither PointerEvent nor elementsFromPoint. The plugin
+// only reads pointerType/pointerId/isPrimary/coordinates from events, and
+// hit-testing is redirected through this controllable stub.
+class PolyfillPointerEvent extends MouseEvent {
+ pointerId: number;
+ pointerType: string;
+ isPrimary: boolean;
+ constructor(
+ type: string,
+ init: MouseEventInit & {
+ pointerId?: number;
+ pointerType?: string;
+ isPrimary?: boolean;
+ } = {}
+ ) {
+ super(type, init);
+ this.pointerId = init.pointerId ?? 0;
+ this.pointerType = init.pointerType ?? '';
+ this.isPrimary = init.isPrimary ?? false;
+ }
+}
+if (typeof globalThis.PointerEvent === 'undefined') {
+ globalThis.PointerEvent =
+ PolyfillPointerEvent as unknown as typeof PointerEvent;
+}
+
+let elementsUnderPointer: Element[] = [];
+document.elementsFromPoint = () => elementsUnderPointer;
+
+function createTestEditor(): LexicalEditor {
+ return createTableTestEditor({ touchSelection: true });
+}
+
+function getCellNode(editor: LexicalEditor, row: number, column: number) {
+ return editor.getEditorState().read(() => $getCell(row, column));
+}
+
+function getCellElement(
+ editor: LexicalEditor,
+ row: number,
+ column: number
+): HTMLElement {
+ const elem = editor.getElementByKey(
+ getCellNode(editor, row, column).getKey()
+ );
+ if (!elem) throw new Error('no cell element');
+ return elem;
+}
+
+function touchEvent(
+ type: string,
+ init: { clientX?: number; clientY?: number } = {}
+): PointerEvent {
+ return new PolyfillPointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ clientX: init.clientX ?? 0,
+ clientY: init.clientY ?? 0,
+ isPrimary: true,
+ pointerId: 1,
+ pointerType: 'touch',
+ }) as unknown as PointerEvent;
+}
+
+/** Anchor and focus cell of the current selection, or null when not a table selection. */
+function readTableSelection(
+ editor: LexicalEditor
+): { anchor: TableCellNode; focus: TableCellNode } | null {
+ return editor.getEditorState().read(() => {
+ const selection = $getSelection();
+ if (!$isTableSelection(selection)) return null;
+ const anchor = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
+ const focus = $getTableCellNodeFromLexicalNode(selection.focus.getNode());
+ return anchor && focus ? { anchor, focus } : null;
+ });
+}
+
+async function flush() {
+ await Promise.resolve();
+}
+
+describe('table touch selection', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ elementsUnderPointer = [];
+ });
+ afterEach(() => {
+ // Tests that fire a long press without a matching pointerup/pointercancel
+ // leave the plugin's document-level gesture listeners attached; end
+ // whatever gesture (armed or active) is in progress before teardown.
+ document.dispatchEvent(touchEvent('pointercancel'));
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ });
+
+ it('selects the pressed cell after a long press', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(3, 3));
+ const cellElem = getCellElement(editor, 1, 1);
+
+ cellElem.dispatchEvent(touchEvent('pointerdown'));
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ const selection = readTableSelection(editor);
+ expect(selection).not.toBeNull();
+ const pressedKey = getCellNode(editor, 1, 1).getKey();
+ expect(selection?.anchor.getKey()).toBe(pressedKey);
+ expect(selection?.focus.getKey()).toBe(pressedKey);
+ });
+
+ it('extends the selection while swiping across cells', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(3, 3));
+
+ getCellElement(editor, 0, 0).dispatchEvent(touchEvent('pointerdown'));
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ elementsUnderPointer = [getCellElement(editor, 2, 1)];
+ document.dispatchEvent(
+ touchEvent('pointermove', { clientX: 50, clientY: 80 })
+ );
+ await flush();
+
+ const selection = readTableSelection(editor);
+ expect(selection?.anchor.getKey()).toBe(getCellNode(editor, 0, 0).getKey());
+ expect(selection?.focus.getKey()).toBe(getCellNode(editor, 2, 1).getKey());
+ });
+
+ it('keeps the selection after the finger lifts', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+
+ getCellElement(editor, 0, 0).dispatchEvent(touchEvent('pointerdown'));
+ vi.advanceTimersByTime(500);
+ await flush();
+ elementsUnderPointer = [getCellElement(editor, 1, 1)];
+ document.dispatchEvent(
+ touchEvent('pointermove', { clientX: 40, clientY: 40 })
+ );
+ await flush();
+ document.dispatchEvent(
+ touchEvent('pointerup', { clientX: 40, clientY: 40 })
+ );
+ await flush();
+
+ const selection = readTableSelection(editor);
+ expect(selection?.focus.getKey()).toBe(getCellNode(editor, 1, 1).getKey());
+ });
+
+ it('does nothing when the finger drifts before the long press fires', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+
+ getCellElement(editor, 0, 0).dispatchEvent(
+ touchEvent('pointerdown', { clientX: 0, clientY: 0 })
+ );
+ document.dispatchEvent(
+ touchEvent('pointermove', { clientX: 0, clientY: 30 })
+ );
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ expect(readTableSelection(editor)).toBeNull();
+ });
+
+ it('does nothing on a quick tap', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+
+ getCellElement(editor, 0, 0).dispatchEvent(touchEvent('pointerdown'));
+ document.dispatchEvent(touchEvent('pointerup'));
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ expect(readTableSelection(editor)).toBeNull();
+ });
+
+ it('ignores mouse pointers', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+
+ getCellElement(editor, 0, 0).dispatchEvent(
+ new PolyfillPointerEvent('pointerdown', {
+ bubbles: true,
+ isPrimary: true,
+ pointerId: 1,
+ pointerType: 'mouse',
+ })
+ );
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ expect(readTableSelection(editor)).toBeNull();
+ });
+
+ it('blocks scrolling only while selecting', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+ const cellElem = getCellElement(editor, 0, 0);
+
+ cellElem.dispatchEvent(touchEvent('pointerdown'));
+
+ // Armed but not yet selecting: scrolling must stay possible.
+ const armedScroll = new Event('touchmove', { cancelable: true });
+ document.dispatchEvent(armedScroll);
+ expect(armedScroll.defaultPrevented).toBe(false);
+
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ const selectingScroll = new Event('touchmove', { cancelable: true });
+ document.dispatchEvent(selectingScroll);
+ expect(selectingScroll.defaultPrevented).toBe(true);
+
+ document.dispatchEvent(touchEvent('pointerup'));
+ const afterScroll = new Event('touchmove', { cancelable: true });
+ document.dispatchEvent(afterScroll);
+ expect(afterScroll.defaultPrevented).toBe(false);
+ });
+
+ it('suppresses the long-press context menu during the gesture', async () => {
+ const editor = createTestEditor();
+ await buildTable(editor, coordGrid(2, 2));
+ const cellElem = getCellElement(editor, 0, 0);
+
+ cellElem.dispatchEvent(touchEvent('pointerdown'));
+ vi.advanceTimersByTime(500);
+ await flush();
+
+ const menu = new Event('contextmenu', { bubbles: true, cancelable: true });
+ cellElem.dispatchEvent(menu);
+ expect(menu.defaultPrevented).toBe(true);
+
+ document.dispatchEvent(touchEvent('pointerup'));
+ const menuAfter = new Event('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ cellElem.dispatchEvent(menuAfter);
+ expect(menuAfter.defaultPrevented).toBe(false);
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.ts
new file mode 100644
index 0000000000..42dc784c45
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/tables/tableTouchSelection.ts
@@ -0,0 +1,168 @@
+/**
+ * @file Touch cell selection for tables: long-press a cell to select it, then
+ * swipe in any direction to extend the selection cell-by-cell. Mouse/pen
+ * drags already do this via @lexical/table's own pointer handlers; on touch
+ * the browser claims the drag for scrolling before those handlers see any
+ * movement. Long-press is the disambiguator: a finger that hasn't moved by
+ * then isn't scrolling, so from that point the gesture is ours to keep (a
+ * non-passive touchmove listener blocks the pan) and the selection is driven
+ * through the same TableObserver the desktop drag uses.
+ */
+import {
+ getDOMCellFromTarget,
+ getTableObserverFromTableElement,
+ type TableDOMCell,
+} from '@lexical/table';
+import type { LexicalEditor } from 'lexical';
+
+// Must beat the native long-press UI (iOS loupe / Android context menu,
+// both around 500ms) so the gesture is ours before the OS reacts.
+const LONG_PRESS_MS = 400;
+// Finger drift beyond this before the timer fires means a scroll, not a press.
+const SLOP_PX = 10;
+
+function registerTableTouchSelection(editor: LexicalEditor): () => void {
+ // True from touch-down on a cell until the gesture ends; used to swallow
+ // the context menu Android fires on long-press.
+ let gestureActive = false;
+ let endGesture: (() => void) | null = null;
+
+ const attach = (root: HTMLElement): (() => void) => {
+ const onPointerDown = (down: PointerEvent) => {
+ if (down.pointerType !== 'touch' || !down.isPrimary) return;
+ if (!editor.isEditable()) return;
+ endGesture?.();
+
+ const domCell =
+ down.target instanceof Node ? getDOMCellFromTarget(down.target) : null;
+ const tableElem = domCell?.elem.closest('table');
+ if (!domCell || !tableElem) return;
+
+ const observer = getTableObserverFromTableElement(
+ tableElem as Parameters<typeof getTableObserverFromTableElement>[0]
+ );
+ if (!observer) return;
+
+ gestureActive = true;
+ const { clientX: startX, clientY: startY, pointerId } = down;
+ let timer = 0;
+
+ const cleanupArmed = () => {
+ window.clearTimeout(timer);
+ document.removeEventListener('pointermove', onArmedMove);
+ document.removeEventListener('pointerup', cancelArmed);
+ document.removeEventListener('pointercancel', cancelArmed);
+ };
+ const cancelArmed = () => {
+ cleanupArmed();
+ gestureActive = false;
+ endGesture = null;
+ };
+ const onArmedMove = (move: PointerEvent) => {
+ if (move.pointerId !== pointerId) return;
+ const drift = Math.hypot(move.clientX - startX, move.clientY - startY);
+ if (drift > SLOP_PX) cancelArmed();
+ };
+
+ const startSelecting = () => {
+ // The native selection UI (iOS text loupe) would fight the cell
+ // selection from here on; suppress it for the rest of the gesture.
+ tableElem.style.setProperty('-webkit-user-select', 'none');
+ tableElem.style.setProperty('-webkit-touch-callout', 'none');
+ navigator.vibrate?.(10);
+
+ editor.update(() => {
+ observer.$setAnchorCellForSelection(domCell);
+ // ignoreStart forces the single-cell highlight immediately instead
+ // of waiting for the finger to leave the first cell.
+ observer.$setFocusCellForSelection(domCell, true);
+ });
+
+ let lastFocusElem = domCell.elem;
+
+ // pointermove can't stop the page from panning; only preventDefault
+ // from a non-passive touchmove listener can.
+ const blockScroll = (event: TouchEvent) => event.preventDefault();
+
+ const onSelectMove = (move: PointerEvent) => {
+ if (move.pointerId !== pointerId) return;
+ // Keep @lexical/table's window-level drag handler (attached on the
+ // same pointerdown) from fighting over the selection.
+ move.stopPropagation();
+ let focusCell: TableDOMCell | null = null;
+ for (const el of document.elementsFromPoint(
+ move.clientX,
+ move.clientY
+ )) {
+ const cell = getDOMCellFromTarget(el);
+ if (cell && tableElem.contains(cell.elem)) {
+ focusCell = cell;
+ break;
+ }
+ }
+ if (!focusCell || focusCell.elem === lastFocusElem) return;
+ lastFocusElem = focusCell.elem;
+ const focus = focusCell;
+ editor.update(() => {
+ observer.$setFocusCellForSelection(focus, true);
+ });
+ };
+
+ const endSelecting = () => {
+ document.removeEventListener('pointermove', onSelectMove);
+ document.removeEventListener('pointerup', endSelecting);
+ document.removeEventListener('pointercancel', endSelecting);
+ document.removeEventListener('touchmove', blockScroll);
+ tableElem.style.removeProperty('-webkit-user-select');
+ tableElem.style.removeProperty('-webkit-touch-callout');
+ gestureActive = false;
+ endGesture = null;
+ };
+
+ document.addEventListener('pointermove', onSelectMove);
+ document.addEventListener('pointerup', endSelecting);
+ document.addEventListener('pointercancel', endSelecting);
+ document.addEventListener('touchmove', blockScroll, { passive: false });
+ endGesture = endSelecting;
+ };
+
+ timer = window.setTimeout(() => {
+ cleanupArmed();
+ startSelecting();
+ }, LONG_PRESS_MS);
+
+ document.addEventListener('pointermove', onArmedMove);
+ document.addEventListener('pointerup', cancelArmed);
+ document.addEventListener('pointercancel', cancelArmed);
+ endGesture = cancelArmed;
+ };
+
+ const onContextMenu = (event: Event) => {
+ if (gestureActive) event.preventDefault();
+ };
+
+ root.addEventListener('pointerdown', onPointerDown);
+ root.addEventListener('contextmenu', onContextMenu);
+ return () => {
+ root.removeEventListener('pointerdown', onPointerDown);
+ root.removeEventListener('contextmenu', onContextMenu);
+ endGesture?.();
+ };
+ };
+
+ let cleanupRoot: (() => void) | null = null;
+ const removeRootListener = editor.registerRootListener((root) => {
+ cleanupRoot?.();
+ cleanupRoot = root ? attach(root) : null;
+ });
+
+ return () => {
+ removeRootListener();
+ cleanupRoot?.();
+ cleanupRoot = null;
+ };
+}
+
+export function tableTouchSelectionPlugin() {
+ return (editor: LexicalEditor) => registerTableTouchSelection(editor);
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
index 7685a9d7ce..384b2d6438 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
@@ -177,7 +177,7 @@ function registerTextPastePlugin(editor: LexicalEditor) {
// clipboards, and only when the cursor is a collapsed selection.
const clipboard = event.clipboardData;
const isRichClipboard = Boolean(
- clipboard?.getData('application/x-lexical-clipboard') ||
+ clipboard?.getData('application/x-lexical-editor') ||
clipboard?.getData('text/html')
);
if (
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
index 589dd7095f..1d9f773add 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
@@ -360,7 +360,9 @@ ol.static-md.depth-6 > li:not(.list-none)::before {
width: fit-content;
vertical-align: top;
text-align: start;
- padding: 0.5rem;
+ /* Roomy enough that the floating insert/delete buttons on cell edges don't
+ cover text. */
+ padding: 0.75rem;
position: relative;
outline: none;
overflow: auto;
@@ -374,6 +376,16 @@ ref: https://bugzilla.mozilla.org/show_bug.cgi?id=1904159
overflow: inherit;
}
+/*
+Lists indent with margin-left, so bullet/number markers paint outside the
+list's own box. The overflow inherited above clips them for top-level lists
+in a cell — move the indent inside the box so markers stay visible.
+*/
+.md-table-cell > .md-list {
+ margin-left: 0;
+ padding-left: 1.5em;
+}
+
.md-table-cell-resizer {
position: absolute;
right: -4px;
@@ -470,30 +482,6 @@ ref: https://bugzilla.mozilla.org/show_bug.cgi?id=1904159
top: 0;
}
-.md-table-cell-action-button-container {
- display: block;
- right: 5px;
- top: 6px;
- position: absolute;
- z-index: 4;
- width: 20px;
- height: 20px;
-}
-
-.md-table-cell-action-button {
- display: block;
- border: 0;
- border-radius: 20px;
- width: 20px;
- height: 20px;
- color: var(--color-ink-muted);
- background-color: transparent;
-}
-
-.md-table-cell-action-button:hover {
- background-color: rgb(from var(--color-edge) r g b / 0.15);
-}
-
.md-editor-equation {
user-select: none;
}
diff --git a/apps/web/src/lib/core/mobile/isTouchDevice.ts b/apps/web/src/lib/core/mobile/isTouchDevice.ts
index 78afb068c4..eff6b83536 100644
--- a/apps/web/src/lib/core/mobile/isTouchDevice.ts
+++ b/apps/web/src/lib/core/mobile/isTouchDevice.ts
@@ -1,18 +1,23 @@
+import { createSignal } from 'solid-js';
+
+const coarsePointerQuery =
+ typeof window !== 'undefined' && typeof window.matchMedia === 'function'
+ ? window.matchMedia('(pointer: coarse)')
+ : null;
+
+const [isCoarsePointer, setIsCoarsePointer] = createSignal(
+ coarsePointerQuery?.matches ?? false
+);
+
+// Tracks the media query live (rather than caching the first answer) so
+// devtools touch emulation toggled after load is picked up reactively.
+coarsePointerQuery?.addEventListener('change', (event) =>
+ setIsCoarsePointer(event.matches)
+);
+
/**
* This function returns true if the device is PRIMARILY touch device, E.g. this should return false for touchscreen laptops. However, the user might still be using a keyboard, e.g. if they have a physical keyboard attached to their iPad. In that case, you may want to use isModality('touch') instead.
*/
-let cachedIsTouchDevice: boolean | null = null;
-
export function isTouchDevice(): boolean {
- if (cachedIsTouchDevice !== null) return cachedIsTouchDevice;
-
- if (
- typeof window === 'undefined' ||
- typeof window.matchMedia !== 'function'
- ) {
- return false;
- }
-
- cachedIsTouchDevice = window.matchMedia('(pointer: coarse)').matches;
- return cachedIsTouchDevice;
+ return isCoarsePointer();
}
diff --git a/apps/web/src/lib/core/util/dataTransfer.ts b/apps/web/src/lib/core/util/dataTransfer.ts
index 237633e4e7..46105a9630 100644
--- a/apps/web/src/lib/core/util/dataTransfer.ts
+++ b/apps/web/src/lib/core/util/dataTransfer.ts
@@ -3,6 +3,72 @@ type ExtractedEntries = {
directoryEntries: FileSystemDirectoryEntry[];
};
+/**
+ * Reads the system clipboard into a DataTransfer — rich text/html when the
+ * browser grants clipboard read access, plain text otherwise — so the
+ * content can be replayed through paste pipelines that expect paste-event
+ * data. Returns null when the clipboard is empty or unreadable. Must be
+ * called from a user gesture on mobile browsers.
+ */
+export async function readClipboardAsDataTransfer(): Promise<DataTransfer | null> {
+ const clipboard = navigator.clipboard;
+ if (!clipboard) return null;
+
+ const dataTransfer = new DataTransfer();
+ const items = await clipboard.read().catch(() => []);
+ for (const item of items) {
+ for (const type of item.types) {
+ if (type !== 'text/html' && type !== 'text/plain') continue;
+ const blob = await item.getType(type);
+ dataTransfer.setData(type, await blob.text());
+ }
+ }
+
+ if (dataTransfer.types.length === 0) {
+ const text = await clipboard.readText().catch(() => '');
+ if (text) dataTransfer.setData('text/plain', text);
+ }
+
+ return dataTransfer.types.length > 0 ? dataTransfer : null;
+}
+
+/**
+ * Writes clipboard data (MIME type → serialized string, as produced by
+ * lexical's `$getClipboardDataFromSelection`) to the system clipboard via
+ * the async Clipboard API. Unlike the `execCommand('copy')` path this works
+ * reliably inside a user gesture on mobile browsers. Rich (text/html) write
+ * is attempted first, falling back to plain text. Returns whether anything
+ * was written. Must be called from a user gesture on mobile browsers.
+ */
+export async function writeClipboardData(
+ data: Record<string, string | undefined>
+): Promise<boolean> {
+ const clipboard = navigator.clipboard;
+ if (!clipboard) return false;
+
+ const html = data['text/html'];
+ const text = data['text/plain'] ?? '';
+
+ if (typeof ClipboardItem !== 'undefined' && clipboard.write) {
+ const items: Record<string, Blob> = {
+ 'text/plain': new Blob([text], { type: 'text/plain' }),
+ };
+ if (html !== undefined) {
+ items['text/html'] = new Blob([html], { type: 'text/html' });
+ }
+ const wrote = await clipboard
+ .write([new ClipboardItem(items)])
+ .then(() => true)
+ .catch(() => false);
+ if (wrote) return true;
+ }
+
+ return clipboard
+ .writeText(text)
+ .then(() => true)
+ .catch(() => false);
+}
+
const EMPTY_RESULT: ExtractedEntries = {
fileEntries: [],
directoryEntries: [],
diff --git a/bun.lock b/bun.lock
index 080e43e1dc..fd6411df85 100644
--- a/bun.lock
+++ b/bun.lock
@@ -330,12 +330,13 @@
"esbuild",
],
"patchedDependencies": {
+ "@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
+ "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
+ "[email protected]": "apps/web/patches/[email protected]",
"@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
- "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
"@thisbeyond/[email protected]": "apps/web/patches/@thisbeyond%[email protected]",
- "[email protected]": "apps/web/patches/[email protected]",
},
"overrides": {
"@kobalte/core": "0.13.11",
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 0713df9422..5e33437d18 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
"aarch64-darwin": "sha256-cLWPkAkYqrye5JYmgs1lUhTzntvA3lKefsBTQtqFVdk=",
- "x86_64-linux": "sha256-VKX+owwjk3dXI4DRnYyRorxmOafrm/2gjKOqBOw+q+4="
+ "x86_64-linux": "sha256-DCbmGcXs+OGOH+ibJXHOQRkXI4xwqG6EZlXOLNrTSlk="
}
}
diff --git a/package.json b/package.json
index 218e62a1ae..a95730279f 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,8 @@
"@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]",
"@kobalte/[email protected]": "apps/web/patches/@kobalte%[email protected]",
"[email protected]": "apps/web/patches/[email protected]",
- "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]"
+ "@tanstack/[email protected]": "apps/web/patches/@tanstack%[email protected]",
+ "@lexical/[email protected]": "apps/web/patches/@lexical%[email protected]"
},
"private": true,
"scripts": {
diff --git a/packages/lexical-core/plugins/nodeIdPlugin.ts b/packages/lexical-core/plugins/nodeIdPlugin.ts
index 4e7e55cf7b..55905c2c19 100644
--- a/packages/lexical-core/plugins/nodeIdPlugin.ts
+++ b/packages/lexical-core/plugins/nodeIdPlugin.ts
@@ -186,14 +186,17 @@ function registerNodeIdPlugin(editor: LexicalEditor, props: NodeIdProps) {
return mergeRegister(
...cleanupHandlers,
+ // Invalidate ids on pasted nodes so the transforms assign fresh ones,
+ // but do NOT claim the command: lower-priority handlers (notably
+ // @lexical/table's grid-aware paste) and @lexical/clipboard's own
+ // insertNodes fallback perform the actual insertion.
editor.registerCommand(
SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,
- ({ nodes, selection }) => {
+ ({ nodes }) => {
nodes.forEach((node) => {
$invalidateId(node);
});
- selection.insertNodes(nodes);
- return true;
+ return false;
},
COMMAND_PRIORITY_CRITICAL
),
diff --git a/packages/lexical-core/tests/tables.test.ts b/packages/lexical-core/tests/tables.test.ts
new file mode 100644
index 0000000000..3b8aab9c8e
--- /dev/null
+++ b/packages/lexical-core/tests/tables.test.ts
@@ -0,0 +1,320 @@
+import { $isListItemNode, $isListNode, type ListNode } from '@lexical/list';
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+} from '@lexical/markdown';
+import {
+ $createTableCellNode,
+ $createTableNode,
+ $createTableRowNode,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+ TableCellHeaderStates,
+ type TableCellNode,
+ type TableNode,
+ type TableRowNode,
+} from '@lexical/table';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { SupportedNodeTypes } from '../node-list';
+import { EXTERNAL_TRANSFORMERS, INTERNAL_TRANSFORMERS } from '../transformers';
+
+function createTestEditor() {
+ return createEditor({
+ nodes: SupportedNodeTypes,
+ onError: (error) => {
+ throw error;
+ },
+ });
+}
+
+function $createCell(
+ text: string,
+ headerState: number = TableCellHeaderStates.NO_STATUS
+): TableCellNode {
+ const cell = $createTableCellNode(headerState);
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode(text));
+ cell.append(paragraph);
+ return cell;
+}
+
+async function buildEditorState(
+ editor: ReturnType<typeof createEditor>,
+ $build: () => void
+) {
+ await new Promise<void>((resolve) => {
+ editor.update($build, { onUpdate: () => resolve() });
+ });
+}
+
+function exportMarkdown(
+ editor: ReturnType<typeof createEditor>,
+ transformers = INTERNAL_TRANSFORMERS
+): string {
+ let markdown = '';
+ editor.getEditorState().read(() => {
+ markdown = $convertToMarkdownString(transformers);
+ });
+ return markdown;
+}
+
+async function importMarkdown(
+ editor: ReturnType<typeof createEditor>,
+ markdown: string
+) {
+ await buildEditorState(editor, () => {
+ $getRoot().clear();
+ $convertFromMarkdownString(markdown, INTERNAL_TRANSFORMERS);
+ });
+}
+
+function $getFirstTable(): TableNode {
+ const table = $getRoot()
+ .getChildren()
+ .find((child) => $isTableNode(child));
+ expect(table).toBeDefined();
+ return table as TableNode;
+}
+
+describe('m-table internal transformer', () => {
+ it('round-trips colspan, rowspan, header state, col widths and row height', async () => {
+ const editor = createTestEditor();
+
+ await buildEditorState(editor, () => {
+ const table = $createTableNode();
+ table.setColWidths([120, 240, 360]);
+
+ const headerRow = $createTableRowNode();
+ headerRow.append(
+ $createCell('Name', TableCellHeaderStates.ROW),
+ $createCell('Role', TableCellHeaderStates.ROW),
+ $createCell('Team', TableCellHeaderStates.ROW)
+ );
+
+ const mergedRow = $createTableRowNode();
+ mergedRow.setHeight(48);
+ const mergedCell = $createCell('Wolf');
+ mergedCell.setColSpan(2);
+ mergedCell.setRowSpan(2);
+ mergedRow.append(mergedCell, $createCell('Eng'));
+
+ const lastRow = $createTableRowNode();
+ lastRow.append($createCell('Design'));
+
+ table.append(headerRow, mergedRow, lastRow);
+ $getRoot().append(table);
+ });
+
+ const markdown = exportMarkdown(editor);
+ expect(markdown).toContain('<m-table col-widths="120,240,360">');
+ expect(markdown).toContain('<m-table-row height="48">');
+ expect(markdown).toContain('<m-table-cell colspan="2" rowspan="2">Wolf');
+ expect(markdown).toContain('<m-table-cell header="row">Name');
+
+ await importMarkdown(editor, markdown);
+
+ editor.getEditorState().read(() => {
+ const table = $getFirstTable();
+ expect(table.getColWidths()).toEqual([120, 240, 360]);
+
+ const rows = table.getChildren().filter($isTableRowNode);
+ expect(rows).toHaveLength(3);
+ expect((rows[1] as TableRowNode).getHeight()).toBe(48);
+
+ const headerCells = (rows[0] as TableRowNode)
+ .getChildren()
+ .filter($isTableCellNode);
+ for (const cell of headerCells) {
+ expect(cell.__headerState).toBe(TableCellHeaderStates.ROW);
+ }
+
+ const [mergedCell] = (rows[1] as TableRowNode)
+ .getChildren()
+ .filter($isTableCellNode);
+ expect(mergedCell.getColSpan()).toBe(2);
+ expect(mergedCell.getRowSpan()).toBe(2);
+ expect(mergedCell.getTextContent()).toBe('Wolf');
+ });
+ });
+
+ it('serializes plain tables without attributes, identical to the legacy format', async () => {
+ const editor = createTestEditor();
+
+ await buildEditorState(editor, () => {
+ const table = $createTableNode();
+ const row = $createTableRowNode();
+ row.append($createCell('a'), $createCell('b'));
+ table.append(row);
+ $getRoot().append(table);
+ });
+
+ expect(exportMarkdown(editor)).toBe(
+ '<m-table><m-table-row><m-table-cell>a</m-table-cell><m-table-cell>b</m-table-cell></m-table-row></m-table>'
+ );
+ });
+
+ it('imports legacy attribute-less markup', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table><m-table-row><m-table-cell>a</m-table-cell><m-table-cell>b\\nc</m-table-cell></m-table-row></m-table>'
+ );
+
+ editor.getEditorState().read(() => {
+ const table = $getFirstTable();
+ const [row] = table.getChildren().filter($isTableRowNode);
+ const cells = (row as TableRowNode)
+ .getChildren()
+ .filter($isTableCellNode);
+ expect(cells).toHaveLength(2);
+ expect(cells[0].getColSpan()).toBe(1);
+ expect(cells[0].getRowSpan()).toBe(1);
+ expect(cells[0].__headerState).toBe(TableCellHeaderStates.NO_STATUS);
+ expect(cells[0].getTextContent()).toBe('a');
+ });
+ });
+
+ it('ignores malformed attribute values', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table col-widths="abc,def"><m-table-row height="-5"><m-table-cell colspan="0" rowspan="x" header="nope">a</m-table-cell></m-table-row></m-table>'
+ );
+
+ editor.getEditorState().read(() => {
+ const table = $getFirstTable();
+ expect(table.getColWidths()).toBeUndefined();
+ const [row] = table.getChildren().filter($isTableRowNode);
+ expect((row as TableRowNode).getHeight()).toBeUndefined();
+ const [cell] = (row as TableRowNode)
+ .getChildren()
+ .filter($isTableCellNode);
+ expect(cell.getColSpan()).toBe(1);
+ expect(cell.getRowSpan()).toBe(1);
+ expect(cell.__headerState).toBe(TableCellHeaderStates.NO_STATUS);
+ });
+ });
+});
+
+describe('lists inside table cells', () => {
+ function $getFirstCellList(): ListNode {
+ const table = $getFirstTable();
+ const [row] = table.getChildren().filter($isTableRowNode);
+ const [cell] = (row as TableRowNode).getChildren().filter($isTableCellNode);
+ const list = cell.getChildren().find($isListNode);
+ expect(list).toBeDefined();
+ return list as ListNode;
+ }
+
+ it('round-trips a bullet list in a cell through internal markdown', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table><m-table-row><m-table-cell>- one\\n- two</m-table-cell></m-table-row></m-table>'
+ );
+
+ const markdown = exportMarkdown(editor);
+ expect(markdown).toBe(
+ '<m-table><m-table-row><m-table-cell>- one\\n- two</m-table-cell></m-table-row></m-table>'
+ );
+
+ await importMarkdown(editor, markdown);
+ editor.getEditorState().read(() => {
+ const items = $getFirstCellList().getChildren().filter($isListItemNode);
+ expect(items).toHaveLength(2);
+ expect(items[0].getTextContent()).toBe('one');
+ expect(items[1].getTextContent()).toBe('two');
+ });
+ });
+
+ it('round-trips a nested list in a cell', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table><m-table-row><m-table-cell>- one\\n - nested\\n- two</m-table-cell></m-table-row></m-table>'
+ );
+
+ await importMarkdown(editor, exportMarkdown(editor));
+ editor.getEditorState().read(() => {
+ const list = $getFirstCellList();
+ expect(list.getTextContent()).toContain('nested');
+ // The nested item lives in a child list, one level down
+ const wrapper = list
+ .getChildren()
+ .filter($isListItemNode)
+ .find((item) => item.getChildren().some($isListNode));
+ expect(wrapper).toBeDefined();
+ });
+ });
+
+ it('round-trips a checklist in a cell', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table><m-table-row><m-table-cell>- [ ] todo\\n- [x] done</m-table-cell></m-table-row></m-table>'
+ );
+
+ await importMarkdown(editor, exportMarkdown(editor));
+ editor.getEditorState().read(() => {
+ const list = $getFirstCellList();
+ expect(list.getListType()).toBe('check');
+ const items = list.getChildren().filter($isListItemNode);
+ expect(items).toHaveLength(2);
+ expect(items[0].getChecked()).toBeFalsy();
+ expect(items[1].getChecked()).toBe(true);
+ });
+ });
+
+ it('round-trips a list in a cell through external pipe-table markdown', async () => {
+ const editor = createTestEditor();
+ await importMarkdown(
+ editor,
+ '<m-table><m-table-row><m-table-cell>- one\\n- two</m-table-cell><m-table-cell>plain</m-table-cell></m-table-row></m-table>'
+ );
+
+ const markdown = exportMarkdown(editor, EXTERNAL_TRANSFORMERS);
+ expect(markdown).toBe('| - one\\n- two | plain |');
+
+ await buildEditorState(editor, () => {
+ $getRoot().clear();
+ $convertFromMarkdownString(markdown, EXTERNAL_TRANSFORMERS);
+ });
+ editor.getEditorState().read(() => {
+ const items = $getFirstCellList().getChildren().filter($isListItemNode);
+ expect(items).toHaveLength(2);
+ });
+ });
+});
+
+describe('pipe table external transformer', () => {
+ it('pads merged cells so exported rows stay rectangular', async () => {
+ const editor = createTestEditor();
+
+ await buildEditorState(editor, () => {
+ const table = $createTableNode();
+
+ const firstRow = $createTableRowNode();
+ const wideCell = $createCell('wide');
+ wideCell.setColSpan(2);
+ firstRow.append(wideCell, $createCell('c'));
+
+ const secondRow = $createTableRowNode();
+ secondRow.append($createCell('x'), $createCell('y'), $createCell('z'));
+
+ table.append(firstRow, secondRow);
+ $getRoot().append(table);
+ });
+
+ const markdown = exportMarkdown(editor, EXTERNAL_TRANSFORMERS);
+ const lines = markdown.split('\n');
+ expect(lines[0]).toBe('| wide | | c |');
+ expect(lines[1]).toBe('| x | y | z |');
+ });
+});
diff --git a/packages/lexical-core/transformers/tables.ts b/packages/lexical-core/transformers/tables.ts
index b41845c83f..bc8e8b6e6b 100644
--- a/packages/lexical-core/transformers/tables.ts
+++ b/packages/lexical-core/transformers/tables.ts
@@ -1,141 +1,233 @@
import {
- $convertFromMarkdownString,
- $convertToMarkdownString,
- CHECK_LIST,
- type ElementTransformer,
- TRANSFORMERS,
- type Transformer,
-} from '@lexical/markdown';
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+ CHECK_LIST,
+ type ElementTransformer,
+ TRANSFORMERS,
+ type Transformer,
+} from "@lexical/markdown";
import {
- $createTableNode,
- $createTableRowNode,
- $isTableCellNode,
- $isTableNode,
- $isTableRowNode,
- TableCellHeaderStates,
- TableCellNode,
- TableNode,
- TableRowNode,
-} from '@lexical/table';
-import { $isParagraphNode, $isTextNode, type LexicalNode } from 'lexical';
-import { CUSTOM_TRANSFORMERS } from './customTransformers';
-import { E_BLOCK_EQUATION_NODE, I_EQUATION_NODE } from './katex';
+ $computeTableMapSkipCellCheck,
+ $createTableNode,
+ $createTableRowNode,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+ TableCellHeaderStates,
+ TableCellNode,
+ TableNode,
+ TableRowNode,
+} from "@lexical/table";
+import { $isParagraphNode, $isTextNode, type LexicalNode } from "lexical";
+import { z } from "zod";
+import { CUSTOM_TRANSFORMERS } from "./customTransformers";
+import { E_BLOCK_EQUATION_NODE, I_EQUATION_NODE } from "./katex";
import {
- E_CONTACT_MENTION,
- E_DOCUMENT_MENTION,
- E_USER_MENTION,
- I_CONTACT_MENTION,
- I_DOCUMENT_MENTION,
- I_USER_MENTION,
-} from './mentions';
-import {
- BR_TAG_TO_LINE_BREAK,
- HTML_ENTITY_TRANSFORMERS,
- xmlMatcher,
-} from './transformers';
+ E_CONTACT_MENTION,
+ E_DOCUMENT_MENTION,
+ E_USER_MENTION,
+ I_CONTACT_MENTION,
+ I_DOCUMENT_MENTION,
+ I_USER_MENTION,
+} from "./mentions";
+import { BR_TAG_TO_LINE_BREAK, HTML_ENTITY_TRANSFORMERS } from "./transformers";
// Internal Table Node
-const TAG_TABLE = 'm-table';
-const TAG_TABLE_ROW = 'm-table-row';
-const TAG_TABLE_CELL = 'm-table-cell';
+const TAG_TABLE = "m-table";
+const TAG_TABLE_ROW = "m-table-row";
+const TAG_TABLE_CELL = "m-table-cell";
+
+// Like `xmlMatcher`, but tolerates optional `key="value"` attributes on the
+// opening tag so attribute-less tags from older documents still match.
+// Group 1 is the raw attribute string, group 2 the tag content.
+function xmlMatcherWithAttrs(tag: string, flags?: string) {
+ return new RegExp(
+ `<${tag}((?:\\s+[\\w-]+="[^"]*")*)\\s*>(.*?)</${tag}>`,
+ flags ?? "s",
+ );
+}
+
+function serializeXmlAttrs(
+ attrs: Record<string, string | number | undefined>,
+): string {
+ return Object.entries(attrs)
+ .filter(([, value]) => value !== undefined)
+ .map(([key, value]) => ` ${key}="${value}"`)
+ .join("");
+}
+
+function parseXmlAttrs(raw: string | undefined): Record<string, string> {
+ const attrs: Record<string, string> = {};
+ for (const match of (raw ?? "").matchAll(/([\w-]+)="([^"]*)"/g)) {
+ attrs[match[1]] = match[2];
+ }
+ return attrs;
+}
+
+// Attribute strings from parseXmlAttrs → validated numbers; invalid values are
+// coerced away so a bad attr falls back to the node's default.
+const A_POSITIVE = z.coerce.number().finite().positive();
+const A_SPAN = z.coerce.number().int().min(2);
+
+// Upstream's exact definition from @lexical/table's LexicalTableCellNode.ts;
+// the package doesn't re-export the type from its root (not even on main).
+type TableCellHeaderState =
+ (typeof TableCellHeaderStates)[keyof typeof TableCellHeaderStates];
+
+const HEADER_ATTR_BY_STATE: Record<number, string> = {
+ [TableCellHeaderStates.ROW]: "row",
+ [TableCellHeaderStates.COLUMN]: "col",
+ [TableCellHeaderStates.BOTH]: "both",
+};
+
+const HEADER_STATE_BY_ATTR: Record<string, TableCellHeaderState> = {
+ row: TableCellHeaderStates.ROW,
+ col: TableCellHeaderStates.COLUMN,
+ both: TableCellHeaderStates.BOTH,
+};
-const REG_EXP_XML_TABLE = xmlMatcher(TAG_TABLE, '');
-const REG_EXP_XML_TABLE_ROW = xmlMatcher(TAG_TABLE_ROW, 'gs');
-const REG_EXP_XML_TABLE_CELL = xmlMatcher(TAG_TABLE_CELL, 'gs');
+const REG_EXP_XML_TABLE = xmlMatcherWithAttrs(TAG_TABLE, "");
+const REG_EXP_XML_TABLE_ROW = xmlMatcherWithAttrs(TAG_TABLE_ROW, "gs");
+const REG_EXP_XML_TABLE_CELL = xmlMatcherWithAttrs(TAG_TABLE_CELL, "gs");
const internalTransformersWithinTables: Transformer[] = [
- CHECK_LIST,
- I_USER_MENTION,
- I_DOCUMENT_MENTION,
- I_CONTACT_MENTION,
- I_EQUATION_NODE,
- ...TRANSFORMERS,
+ CHECK_LIST,
+ I_USER_MENTION,
+ I_DOCUMENT_MENTION,
+ I_CONTACT_MENTION,
+ I_EQUATION_NODE,
+ ...TRANSFORMERS,
];
// Transformers used inside table cells
const _TABLE_CELL_TRANSFORMERS: Transformer[] = [
- ...CUSTOM_TRANSFORMERS,
- I_EQUATION_NODE,
- I_USER_MENTION,
- I_DOCUMENT_MENTION,
- I_CONTACT_MENTION,
+ ...CUSTOM_TRANSFORMERS,
+ I_EQUATION_NODE,
+ I_USER_MENTION,
+ I_DOCUMENT_MENTION,
+ I_CONTACT_MENTION,
];
// Transformers that export table cells to markdown
const _TABLE_CELL_EXPORT_TRANSFORMERS: Transformer[] = [
- ...CUSTOM_TRANSFORMERS,
- I_EQUATION_NODE,
- I_USER_MENTION,
- I_DOCUMENT_MENTION,
- I_CONTACT_MENTION,
+ ...CUSTOM_TRANSFORMERS,
+ I_EQUATION_NODE,
+ I_USER_MENTION,
+ I_DOCUMENT_MENTION,
+ I_CONTACT_MENTION,
];
export const I_TABLE_NODE: ElementTransformer = {
- dependencies: [TableNode, TableRowNode, TableCellNode],
- type: 'element',
- regExp: REG_EXP_XML_TABLE,
-
- export: (node) => {
- if (!(node instanceof TableNode)) return null;
-
- let output = `<${TAG_TABLE}>`;
- const rows = node.getChildren();
-
- for (const row of rows) {
- if (row instanceof TableRowNode) {
- output += `<${TAG_TABLE_ROW}>`;
- const cells = row.getChildren();
-
- for (const cell of cells) {
- if (cell instanceof TableCellNode) {
- output += `<${TAG_TABLE_CELL}>`;
- output += $convertToMarkdownString(
- internalTransformersWithinTables,
- cell
- ).replace(/\n/g, '\\n');
- output += `</${TAG_TABLE_CELL}>`;
- }
- }
-
- output += `</${TAG_TABLE_ROW}>`;
- }
- }
-
- output += `</${TAG_TABLE}>`;
- return output;
- },
-
- replace: (node, _children, match, _isImport) => {
- try {
- const xmlContent = match[0];
- const tableNode = new TableNode();
- const rowMatches = xmlContent.matchAll(REG_EXP_XML_TABLE_ROW);
-
- for (const rowMatch of rowMatches) {
- const rowContent = rowMatch[1];
- const rowNode = new TableRowNode();
- const cellMatches = rowContent.matchAll(REG_EXP_XML_TABLE_CELL);
-
- for (const cellMatch of cellMatches) {
- const cellContent = cellMatch[1];
- const cellNode = new TableCellNode();
- $convertFromMarkdownString(
- cellContent.replace(/\\n/g, '\n').replaceAll('<br>', ''),
- internalTransformersWithinTables,
- cellNode
- );
- rowNode.append(cellNode);
- }
-
- tableNode.append(rowNode);
- }
-
- node.replace(tableNode);
- } catch (error) {
- console.error('Error parsing m-table:', error);
- }
- },
+ dependencies: [TableNode, TableRowNode, TableCellNode],
+ type: "element",
+ regExp: REG_EXP_XML_TABLE,
+
+ export: (node) => {
+ if (!(node instanceof TableNode)) return null;
+
+ const colWidths = node.getColWidths();
+ let output = `<${TAG_TABLE}${serializeXmlAttrs({
+ "col-widths": colWidths?.map((width) => Math.round(width)).join(","),
+ })}>`;
+ const rows = node.getChildren();
+
+ for (const row of rows) {
+ if (row instanceof TableRowNode) {
+ output += `<${TAG_TABLE_ROW}${serializeXmlAttrs({
+ height: row.getHeight(),
+ })}>`;
+ const cells = row.getChildren();
+
+ for (const cell of cells) {
+ if (cell instanceof TableCellNode) {
+ output += `<${TAG_TABLE_CELL}${serializeXmlAttrs({
+ colspan: cell.getColSpan() > 1 ? cell.getColSpan() : undefined,
+ rowspan: cell.getRowSpan() > 1 ? cell.getRowSpan() : undefined,
+ header: HEADER_ATTR_BY_STATE[cell.__headerState],
+ })}>`;
+ output += $convertToMarkdownString(
+ internalTransformersWithinTables,
+ cell,
+ ).replace(/\n/g, "\\n");
+ output += `</${TAG_TABLE_CELL}>`;
+ }
+ }
+
+ output += `</${TAG_TABLE_ROW}>`;
+ }
+ }
+
+ output += `</${TAG_TABLE}>`;
+ return output;
+ },
+
+ replace: (node, _children, match, _isImport) => {
+ try {
+ const xmlContent = match[0];
+ const tableAttrs = parseXmlAttrs(match[1]);
+ const tableNode = new TableNode();
+ const rowMatches = xmlContent.matchAll(REG_EXP_XML_TABLE_ROW);
+
+ for (const rowMatch of rowMatches) {
+ const rowAttrs = parseXmlAttrs(rowMatch[1]);
+ const rowContent = rowMatch[2];
+ const rowNode = new TableRowNode();
+
+ const height = A_POSITIVE.optional()
+ .catch(undefined)
+ .parse(rowAttrs.height);
+ if (height) {
+ rowNode.setHeight(height);
+ }
+
+ const cellMatches = rowContent.matchAll(REG_EXP_XML_TABLE_CELL);
+
+ for (const cellMatch of cellMatches) {
+ const cellAttrs = parseXmlAttrs(cellMatch[1]);
+ const cellContent = cellMatch[2];
+ const cellNode = new TableCellNode();
+
+ const colSpan = A_SPAN.optional()
+ .catch(undefined)
+ .parse(cellAttrs.colspan);
+ if (colSpan) {
+ cellNode.setColSpan(colSpan);
+ }
+ const rowSpan = A_SPAN.optional()
+ .catch(undefined)
+ .parse(cellAttrs.rowspan);
+ if (rowSpan) {
+ cellNode.setRowSpan(rowSpan);
+ }
+ const headerState = HEADER_STATE_BY_ATTR[cellAttrs.header];
+ if (headerState !== undefined) {
+ cellNode.setHeaderStyles(headerState);
+ }
+
+ $convertFromMarkdownString(
+ cellContent.replace(/\\n/g, "\n").replaceAll("<br>", ""),
+ internalTransformersWithinTables,
+ cellNode,
+ );
+ rowNode.append(cellNode);
+ }
+
+ tableNode.append(rowNode);
+ }
+
+ const colWidths = z
+ .array(A_POSITIVE)
+ .safeParse(tableAttrs["col-widths"]?.split(","));
+ if (colWidths.success && colWidths.data.length) {
+ tableNode.setColWidths(colWidths.data);
+ }
+
+ node.replace(tableNode);
+ } catch (error) {
+ console.error("Error parsing m-table:", error);
+ }
+ },
};
// External Table Node
@@ -144,167 +236,182 @@ const REG_EXP_TABLE_ROW = /^(?:\|)(.+)(?:\|)\s?$/;
const REG_EXP_TABLE_ROW_DIVIDER = /^(\| ?:?-*:? ?)+\|\s?$/;
const externalTransformersWithinTables: Transformer[] = [
- BR_TAG_TO_LINE_BREAK,
- CHECK_LIST,
- E_USER_MENTION,
- I_DOCUMENT_MENTION, // for citations
- E_DOCUMENT_MENTION,
- E_CONTACT_MENTION,
- E_BLOCK_EQUATION_NODE,
- ...HTML_ENTITY_TRANSFORMERS,
- ...TRANSFORMERS,
+ BR_TAG_TO_LINE_BREAK,
+ CHECK_LIST,
+ E_USER_MENTION,
+ I_DOCUMENT_MENTION, // for citations
+ E_DOCUMENT_MENTION,
+ E_CONTACT_MENTION,
+ E_BLOCK_EQUATION_NODE,
+ ...HTML_ENTITY_TRANSFORMERS,
+ ...TRANSFORMERS,
];
function getTableColumnsSize(table: TableNode): number {
- const row = table.getFirstChild();
- return $isTableRowNode(row) ? row.getChildrenSize() : 0;
+ const row = table.getFirstChild();
+ return $isTableRowNode(row) ? row.getChildrenSize() : 0;
}
function createTableCell(cellContent: string): TableCellNode {
- const cellNode = new TableCellNode();
- $convertFromMarkdownString(
- cellContent,
- externalTransformersWithinTables,
- cellNode,
- true
- );
- return cellNode;
+ const cellNode = new TableCellNode();
+ // Export escapes cell newlines as `\n` so rows stay on one line; restore
+ // them so multi-line content (lists, multiple blocks) survives the trip.
+ $convertFromMarkdownString(
+ cellContent.replace(/\\n/g, "\n"),
+ externalTransformersWithinTables,
+ cellNode,
+ true,
+ );
+ return cellNode;
}
function mapToTableCells(textContent: string): Array<TableCellNode> | null {
- const match = textContent.match(REG_EXP_TABLE_ROW);
- if (!match || !match[1]) {
- return null;
- }
+ const match = textContent.match(REG_EXP_TABLE_ROW);
+ if (!match || !match[1]) {
+ return null;
+ }
- return match[1].split('|').map((text) => createTableCell(text));
+ return match[1].split("|").map((text) => createTableCell(text));
}
export const E_TABLE_NODE: ElementTransformer = {
- dependencies: [TableNode, TableRowNode, TableCellNode],
- type: 'element',
- regExp: REG_EXP_TABLE_ROW,
- export: (node: LexicalNode) => {
- if (!$isTableNode(node)) {
- return null;
- }
-
- const output: string[] = [];
- for (const row of node.getChildren()) {
- if (!$isTableRowNode(row)) {
- continue;
- }
-
- const rowOutput = [];
- let isHeaderRow = false;
- for (const cell of row.getChildren()) {
- if ($isTableCellNode(cell)) {
- const cellContent = $convertToMarkdownString(
- externalTransformersWithinTables,
- cell
- )
- .replace(/\n/g, '\\n')
- .trim();
-
- rowOutput.push(cellContent);
- if (cell.__headerState === TableCellHeaderStates.ROW) {
- isHeaderRow = true;
- }
- }
- }
-
- output.push(`| ${rowOutput.join(' | ')} |`);
- if (isHeaderRow) {
- output.push(`| ${rowOutput.map(() => '---').join(' | ')} |`);
- }
- }
- return output.join('\n');
- },
- replace: (parentNode, _unused, match) => {
- if (REG_EXP_TABLE_ROW_DIVIDER.test(match[0])) {
- const table = parentNode.getPreviousSibling();
- if (!table || !$isTableNode(table)) {
- return;
- }
-
- const rows = table.getChildren();
- const lastRow = rows[rows.length - 1];
- if (!lastRow || !$isTableRowNode(lastRow)) {
- return;
- }
-
- for (const cell of lastRow.getChildren()) {
- if (!$isTableCellNode(cell)) {
- continue;
- }
- cell.setHeaderStyles(
- TableCellHeaderStates.NO_STATUS,
- TableCellHeaderStates.NO_STATUS
- // TableCellHeaderStates.ROW, // disable header for now
- // TableCellHeaderStates.ROW // disable header for now
- );
- }
-
- parentNode.remove();
- return;
- }
-
- const matchCells = mapToTableCells(match[0]);
- if (matchCells == null) {
- return;
- }
-
- const rows = [matchCells];
- let sibling = parentNode.getPreviousSibling();
- let maxCells = matchCells.length;
-
- while (sibling) {
- if (!$isParagraphNode(sibling)) {
- break;
- }
- if (sibling.getChildrenSize() !== 1) {
- break;
- }
-
- const firstChild = sibling.getFirstChild();
- if (!$isTextNode(firstChild)) {
- break;
- }
-
- const cells = mapToTableCells(firstChild.getTextContent());
- if (cells == null) {
- break;
- }
-
- maxCells = Math.max(maxCells, cells.length);
- rows.unshift(cells);
-
- const previousSibling = sibling.getPreviousSibling();
- sibling.remove();
- sibling = previousSibling;
- }
-
- const table = $createTableNode();
- for (const cells of rows) {
- const tableRow = $createTableRowNode();
- table.append(tableRow);
-
- for (let i = 0; i < maxCells; i++) {
- tableRow.append(i < cells.length ? cells[i] : createTableCell(''));
- }
- }
-
- const previousSibling = parentNode.getPreviousSibling();
- if (
- $isTableNode(previousSibling) &&
- getTableColumnsSize(previousSibling) === maxCells
- ) {
- previousSibling.append(...table.getChildren());
- parentNode.remove();
- } else {
- parentNode.replace(table);
- }
-
- table.selectEnd();
- },
+ dependencies: [TableNode, TableRowNode, TableCellNode],
+ type: "element",
+ regExp: REG_EXP_TABLE_ROW,
+ export: (node: LexicalNode) => {
+ if (!$isTableNode(node)) {
+ return null;
+ }
+
+ // Walk the computed grid rather than the row children so merged cells
+ // (colspan/rowspan) pad the slots they cover and rows stay rectangular —
+ // pipe tables cannot express merges.
+ const [gridMap] = $computeTableMapSkipCellCheck(node, null, null);
+
+ const output: string[] = [];
+ for (let row = 0; row < gridMap.length; row++) {
+ const rowOutput: string[] = [];
+ let isHeaderRow = false;
+
+ for (let column = 0; column < gridMap[row].length; column++) {
+ const mapCell = gridMap[row][column];
+ if (!mapCell?.cell) {
+ rowOutput.push("");
+ continue;
+ }
+
+ if (mapCell.startRow === row && mapCell.startColumn === column) {
+ const cellContent = $convertToMarkdownString(
+ externalTransformersWithinTables,
+ mapCell.cell,
+ )
+ .replace(/\n/g, "\\n")
+ .trim();
+ rowOutput.push(cellContent);
+ } else {
+ rowOutput.push("");
+ }
+
+ if (
+ mapCell.cell.__headerState === TableCellHeaderStates.ROW ||
+ mapCell.cell.__headerState === TableCellHeaderStates.BOTH
+ ) {
+ isHeaderRow = true;
+ }
+ }
+
+ output.push(`| ${rowOutput.join(" | ")} |`);
+ if (isHeaderRow) {
+ output.push(`| ${rowOutput.map(() => "---").join(" | ")} |`);
+ }
+ }
+ return output.join("\n");
+ },
+ replace: (parentNode, _unused, match) => {
+ if (REG_EXP_TABLE_ROW_DIVIDER.test(match[0])) {
+ const table = parentNode.getPreviousSibling();
+ if (!table || !$isTableNode(table)) {
+ return;
+ }
+
+ const rows = table.getChildren();
+ const lastRow = rows[rows.length - 1];
+ if (!lastRow || !$isTableRowNode(lastRow)) {
+ return;
+ }
+
+ for (const cell of lastRow.getChildren()) {
+ if (!$isTableCellNode(cell)) {
+ continue;
+ }
+ cell.setHeaderStyles(
+ TableCellHeaderStates.NO_STATUS,
+ TableCellHeaderStates.NO_STATUS,
+ // TableCellHeaderStates.ROW, // disable header for now
+ // TableCellHeaderStates.ROW // disable header for now
+ );
+ }
+
+ parentNode.remove();
+ return;
+ }
+
+ const matchCells = mapToTableCells(match[0]);
+ if (matchCells == null) {
+ return;
+ }
+
+ const rows = [matchCells];
+ let sibling = parentNode.getPreviousSibling();
+ let maxCells = matchCells.length;
+
+ while (sibling) {
+ if (!$isParagraphNode(sibling)) {
+ break;
+ }
+ if (sibling.getChildrenSize() !== 1) {
+ break;
+ }
+
+ const firstChild = sibling.getFirstChild();
+ if (!$isTextNode(firstChild)) {
+ break;
+ }
+
+ const cells = mapToTableCells(firstChild.getTextContent());
+ if (cells == null) {
+ break;
+ }
+
+ maxCells = Math.max(maxCells, cells.length);
+ rows.unshift(cells);
+
+ const previousSibling = sibling.getPreviousSibling();
+ sibling.remove();
+ sibling = previousSibling;
+ }
+
+ const table = $createTableNode();
+ for (const cells of rows) {
+ const tableRow = $createTableRowNode();
+ table.append(tableRow);
+
+ for (let i = 0; i < maxCells; i++) {
+ tableRow.append(i < cells.length ? cells[i] : createTableCell(""));
+ }
+ }
+
+ const previousSibling = parentNode.getPreviousSibling();
+ if (
+ $isTableNode(previousSibling) &&
+ getTableColumnsSize(previousSibling) === maxCells
+ ) {
+ previousSibling.append(...table.getChildren());
+ parentNode.remove();
+ } else {
+ parentNode.replace(table);
+ }
+
+ table.selectEnd();
+ },
};
diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.ts
index ed2585d5f0..6f510e5166 100644
--- a/packages/lexical-core/utils/parsers.ts
+++ b/packages/lexical-core/utils/parsers.ts
@@ -228,16 +228,22 @@ function snapshotToEmbeddingText(encoded: string): string {
* `\n`; any tags nested in cells are handled by the leaf passes afterwards.
*/
function flattenTables(text: string): string {
- return text.replace(/<m-table>(.*?)<\/m-table>/gs, (_, table: string) =>
- [...table.matchAll(/<m-table-row>(.*?)<\/m-table-row>/gs)]
- .map((row) =>
- [...row[1].matchAll(/<m-table-cell>(.*?)<\/m-table-cell>/gs)]
- .map((cell) =>
- cell[1].replace(/\\n/g, ' ').replaceAll('<br>', ' ').trim()
- )
- .join(' | ')
- )
- .join('\n')
+ return text.replace(
+ /<m-table(?:\s[^>]*)?>(.*?)<\/m-table>/gs,
+ (_, table: string) =>
+ [...table.matchAll(/<m-table-row(?:\s[^>]*)?>(.*?)<\/m-table-row>/gs)]
+ .map((row) =>
+ [
+ ...row[1].matchAll(
+ /<m-table-cell(?:\s[^>]*)?>(.*?)<\/m-table-cell>/gs
+ ),
+ ]
+ .map((cell) =>
+ cell[1].replace(/\\n/g, ' ').replaceAll('<br>', ' ').trim()
+ )
+ .join(' | ')
+ )
+ .join('\n')
);
}