@box/threaded-annotations 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{THREADED_ANNOTATIONS_PORTAL}from"../esm/lib/v2/constants.js";import{THREADED_ANNOTATIONS_RESIN_COMPONENTS,THREADED_ANNOTATIONS_RESIN_FEATURE,THREADED_ANNOTATIONS_RESIN_TARGETS}from"../esm/lib/v2/resin-targets.js";import messages from"../esm/lib/components/v2/message-header/messages.js";import{Button,Popover,Text}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/delete-confirmation-popover.css';var delete_confirmation_popover_module_default={deletePopover:`_deletePopover_1c8ll_2`,footer:`_footer_1c8ll_6`},message_header_module_default={headerContainer:`_headerContainer_1kmrp_29`,information:`_information_1kmrp_37`,textContainer:`_textContainer_1kmrp_44`,author:`_author_1kmrp_52`,optionsMenu:`_optionsMenu_1kmrp_59`,deletePopoverAnchorWrapper:`_deletePopoverAnchorWrapper_1kmrp_78`,deletePopoverAnchor:`_deletePopoverAnchor_1kmrp_78`},DeleteConfirmationPopover=({hasReplies=!1,isAnnotation=!1,open,onOpenChange,onConfirm,onCancel})=>{let intl=useIntl();return jsx(`div`,{className:message_header_module_default.deletePopoverAnchorWrapper,children:jsxs(Popover.Root,{modal:!1,onOpenChange,open,children:[jsx(Popover.Anchor,{children:jsx(Text,{as:`span`,className:message_header_module_default.deletePopoverAnchor})}),jsxs(Popover.ContentContainer,{...THREADED_ANNOTATIONS_PORTAL,align:`end`,"aria-label":intl.formatMessage(messages.deleteConfirmation),className:delete_confirmation_popover_module_default.deletePopover,"data-resin-component":isAnnotation?THREADED_ANNOTATIONS_RESIN_COMPONENTS.ANNOTATION_MENU:THREADED_ANNOTATIONS_RESIN_COMPONENTS.COMMENT_MENU,"data-resin-feature":THREADED_ANNOTATIONS_RESIN_FEATURE,side:`bottom`,children:[jsx(Popover.MainContent,{children:jsx(Text,{as:`p`,color:`textOnLightDefault`,variant:`bodyDefault`,children:intl.formatMessage(messages.deleteQuestion,{hasReplies:hasReplies?`true`:`false`,type:isAnnotation?`annotation`:`comment`})})}),jsxs(Popover.Footer,{className:delete_confirmation_popover_module_default.footer,children:[jsx(Button,{"aria-label":intl.formatMessage(messages.cancelDeleteButtonAriaLabel),"data-resin-target":THREADED_ANNOTATIONS_RESIN_TARGETS.DELETE_CANCEL,onClick:onCancel,size:`small`,variant:`secondary`,children:intl.formatMessage(messages.deleteCancel)}),jsx(Button,{"aria-label":intl.formatMessage(messages.deleteButtonAriaLabel),"data-resin-target":THREADED_ANNOTATIONS_RESIN_TARGETS.DELETE_CONFIRM,onClick:onConfirm,size:`small`,variant:`destructive`,children:intl.formatMessage(messages.delete)})]})]})]})})};export{message_header_module_default as n,DeleteConfirmationPopover as t};
1
+ import{THREADED_ANNOTATIONS_PORTAL}from"../esm/lib/v2/constants.js";import{THREADED_ANNOTATIONS_RESIN_COMPONENTS,THREADED_ANNOTATIONS_RESIN_FEATURE,THREADED_ANNOTATIONS_RESIN_TARGETS}from"../esm/lib/v2/resin-targets.js";import messages from"../esm/lib/components/v2/message-header/messages.js";import{Button,Popover,Text}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/delete-confirmation-popover.css';var delete_confirmation_popover_module_default={deletePopover:`_deletePopover_1c8ll_2`,footer:`_footer_1c8ll_6`},message_header_module_default={headerContainer:`_headerContainer_1kmrp_29`,information:`_information_1kmrp_37`,textContainer:`_textContainer_1kmrp_44`,author:`_author_1kmrp_52`,optionsMenu:`_optionsMenu_1kmrp_59`,deletePopoverAnchorWrapper:`_deletePopoverAnchorWrapper_1kmrp_78`,deletePopoverAnchor:`_deletePopoverAnchor_1kmrp_78`},DeleteConfirmationPopover=({hasReplies=!1,isAnnotation=!1,open,onOpenChange,onConfirm,onCancel})=>{let intl=useIntl();return jsx(`div`,{className:message_header_module_default.deletePopoverAnchorWrapper,children:jsxs(Popover.Root,{modal:!1,onOpenChange,open,children:[jsx(Popover.Anchor,{children:jsx(Text,{as:`span`,className:message_header_module_default.deletePopoverAnchor})}),jsxs(Popover.ContentContainer,{...THREADED_ANNOTATIONS_PORTAL,align:`end`,"aria-label":intl.formatMessage(messages.deleteConfirmation),className:delete_confirmation_popover_module_default.deletePopover,"data-resin-component":isAnnotation?THREADED_ANNOTATIONS_RESIN_COMPONENTS.ANNOTATION_MENU:THREADED_ANNOTATIONS_RESIN_COMPONENTS.COMMENT_MENU,"data-resin-feature":THREADED_ANNOTATIONS_RESIN_FEATURE,onInteractOutside:event=>event.preventDefault(),side:`bottom`,children:[jsx(Popover.MainContent,{children:jsx(Text,{as:`p`,color:`textOnLightDefault`,variant:`bodyDefault`,children:intl.formatMessage(messages.deleteQuestion,{hasReplies:hasReplies?`true`:`false`,type:isAnnotation?`annotation`:`comment`})})}),jsxs(Popover.Footer,{className:delete_confirmation_popover_module_default.footer,children:[jsx(Button,{"aria-label":intl.formatMessage(messages.cancelDeleteButtonAriaLabel),"data-resin-target":THREADED_ANNOTATIONS_RESIN_TARGETS.DELETE_CANCEL,onClick:onCancel,size:`small`,variant:`secondary`,children:intl.formatMessage(messages.deleteCancel)}),jsx(Button,{"aria-label":intl.formatMessage(messages.deleteButtonAriaLabel),"data-resin-target":THREADED_ANNOTATIONS_RESIN_TARGETS.DELETE_CONFIRM,onClick:onConfirm,size:`small`,variant:`destructive`,children:intl.formatMessage(messages.delete)})]})]})]})})};export{message_header_module_default as n,DeleteConfirmationPopover as t};
@@ -1,2 +1,2 @@
1
1
  function findDiffStart(a,b,pos){for(let i=0;;i++){if(i==a.childCount||i==b.childCount)return a.childCount==b.childCount?null:pos;let childA=a.child(i),childB=b.child(i);if(childA==childB){pos+=childA.nodeSize;continue}if(!childA.sameMarkup(childB))return pos;if(childA.isText&&childA.text!=childB.text){let tA=childA.text,tB=childB.text,j=0;for(;tA[j]==tB[j];j++)pos++;return j&&j<tA.length&&j<tB.length&&surrogateHigh(tA.charCodeAt(j-1))&&surrogateLow(tA.charCodeAt(j))&&pos--,pos}if(childA.content.size||childB.content.size){let inner=findDiffStart(childA.content,childB.content,pos+1);if(inner!=null)return inner}pos+=childA.nodeSize}}function findDiffEnd(a,b,posA,posB){for(let iA=a.childCount,iB=b.childCount;;){if(iA==0||iB==0)return iA==iB?null:{a:posA,b:posB};let childA=a.child(--iA),childB=b.child(--iB),size=childA.nodeSize;if(childA==childB){posA-=size,posB-=size;continue}if(!childA.sameMarkup(childB))return{a:posA,b:posB};if(childA.isText&&childA.text!=childB.text){let tA=childA.text,tB=childB.text,iA=tA.length,iB=tB.length;for(;iA>0&&iB>0&&tA[iA-1]==tB[iB-1];)iA--,iB--,posA--,posB--;return iA&&iB&&iA<tA.length&&surrogateHigh(tA.charCodeAt(iA-1))&&surrogateLow(tA.charCodeAt(iA))&&(posA++,posB++),{a:posA,b:posB}}if(childA.content.size||childB.content.size){let inner=findDiffEnd(childA.content,childB.content,posA-1,posB-1);if(inner)return inner}posA-=size,posB-=size}}function surrogateLow(ch){return ch>=56320&&ch<57344}function surrogateHigh(ch){return ch>=55296&&ch<56320}var Fragment=class Fragment{constructor(content,size){if(this.content=content,this.size=size||0,size==null)for(let i=0;i<content.length;i++)this.size+=content[i].nodeSize}nodesBetween(from,to,f,nodeStart=0,parent){for(let i=0,pos=0;pos<to;i++){let child=this.content[i],end=pos+child.nodeSize;if(end>from&&f(child,nodeStart+pos,parent||null,i)!==!1&&child.content.size){let start=pos+1;child.nodesBetween(Math.max(0,from-start),Math.min(child.content.size,to-start),f,nodeStart+start)}pos=end}}descendants(f){this.nodesBetween(0,this.size,f)}textBetween(from,to,blockSeparator,leafText){let text=``,first=!0;return this.nodesBetween(from,to,(node,pos)=>{let nodeText=node.isText?node.text.slice(Math.max(from,pos)-pos,to-pos):node.isLeaf?leafText?typeof leafText==`function`?leafText(node):leafText:node.type.spec.leafText?node.type.spec.leafText(node):``:``;node.isBlock&&(node.isLeaf&&nodeText||node.isTextblock)&&blockSeparator&&(first?first=!1:text+=blockSeparator),text+=nodeText},0),text}append(other){if(!other.size)return this;if(!this.size)return other;let last=this.lastChild,first=other.firstChild,content=this.content.slice(),i=0;for(last.isText&&last.sameMarkup(first)&&(content[content.length-1]=last.withText(last.text+first.text),i=1);i<other.content.length;i++)content.push(other.content[i]);return new Fragment(content,this.size+other.size)}cut(from,to=this.size){if(from==0&&to==this.size)return this;let result=[],size=0;if(to>from)for(let i=0,pos=0;pos<to;i++){let child=this.content[i],end=pos+child.nodeSize;end>from&&((pos<from||end>to)&&(child=child.isText?child.cut(Math.max(0,from-pos),Math.min(child.text.length,to-pos)):child.cut(Math.max(0,from-pos-1),Math.min(child.content.size,to-pos-1))),result.push(child),size+=child.nodeSize),pos=end}return new Fragment(result,size)}cutByIndex(from,to){return from==to?Fragment.empty:from==0&&to==this.content.length?this:new Fragment(this.content.slice(from,to))}replaceChild(index,node){let current=this.content[index];if(current==node)return this;let copy=this.content.slice(),size=this.size+node.nodeSize-current.nodeSize;return copy[index]=node,new Fragment(copy,size)}addToStart(node){return new Fragment([node].concat(this.content),this.size+node.nodeSize)}addToEnd(node){return new Fragment(this.content.concat(node),this.size+node.nodeSize)}eq(other){if(this.content.length!=other.content.length)return!1;for(let i=0;i<this.content.length;i++)if(!this.content[i].eq(other.content[i]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(index){let found=this.content[index];if(!found)throw RangeError(`Index `+index+` out of range for `+this);return found}maybeChild(index){return this.content[index]||null}forEach(f){for(let i=0,p=0;i<this.content.length;i++){let child=this.content[i];f(child,p,i),p+=child.nodeSize}}findDiffStart(other,pos=0){return findDiffStart(this,other,pos)}findDiffEnd(other,pos=this.size,otherPos=other.size){return findDiffEnd(this,other,pos,otherPos)}findIndex(pos){if(pos==0)return retIndex(0,pos);if(pos==this.size)return retIndex(this.content.length,pos);if(pos>this.size||pos<0)throw RangeError(`Position ${pos} outside of fragment (${this})`);for(let i=0,curPos=0;;i++){let cur=this.child(i),end=curPos+cur.nodeSize;if(end>=pos)return end==pos?retIndex(i+1,end):retIndex(i,curPos);curPos=end}}toString(){return`<`+this.toStringInner()+`>`}toStringInner(){return this.content.join(`, `)}toJSON(){return this.content.length?this.content.map(n=>n.toJSON()):null}static fromJSON(schema,value){if(!value)return Fragment.empty;if(!Array.isArray(value))throw RangeError(`Invalid input for Fragment.fromJSON`);return Fragment.fromArray(value.map(schema.nodeFromJSON))}static fromArray(array){if(!array.length)return Fragment.empty;let joined,size=0;for(let i=0;i<array.length;i++){let node=array[i];size+=node.nodeSize,i&&node.isText&&array[i-1].sameMarkup(node)?(joined||=array.slice(0,i),joined[joined.length-1]=node.withText(joined[joined.length-1].text+node.text)):joined&&joined.push(node)}return new Fragment(joined||array,size)}static from(nodes){if(!nodes)return Fragment.empty;if(nodes instanceof Fragment)return nodes;if(Array.isArray(nodes))return this.fromArray(nodes);if(nodes.attrs)return new Fragment([nodes],nodes.nodeSize);throw RangeError(`Can not convert `+nodes+` to a Fragment`+(nodes.nodesBetween?` (looks like multiple versions of prosemirror-model were loaded)`:``))}};Fragment.empty=new Fragment([],0);var found={index:0,offset:0};function retIndex(index,offset){return found.index=index,found.offset=offset,found}function compareDeep(a,b){if(a===b)return!0;if(!(a&&typeof a==`object`)||!(b&&typeof b==`object`))return!1;let array=Array.isArray(a);if(Array.isArray(b)!=array)return!1;if(array){if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++)if(!compareDeep(a[i],b[i]))return!1}else{for(let p in a)if(!(p in b)||!compareDeep(a[p],b[p]))return!1;for(let p in b)if(!(p in a))return!1}return!0}var Mark=class Mark{constructor(type,attrs){this.type=type,this.attrs=attrs}addToSet(set){let copy,placed=!1;for(let i=0;i<set.length;i++){let other=set[i];if(this.eq(other))return set;if(this.type.excludes(other.type))copy||=set.slice(0,i);else if(other.type.excludes(this.type))return set;else !placed&&other.type.rank>this.type.rank&&(copy||=set.slice(0,i),copy.push(this),placed=!0),copy&&copy.push(other)}return copy||=set.slice(),placed||copy.push(this),copy}removeFromSet(set){for(let i=0;i<set.length;i++)if(this.eq(set[i]))return set.slice(0,i).concat(set.slice(i+1));return set}isInSet(set){for(let i=0;i<set.length;i++)if(this.eq(set[i]))return!0;return!1}eq(other){return this==other||this.type==other.type&&compareDeep(this.attrs,other.attrs)}toJSON(){let obj={type:this.type.name};for(let _ in this.attrs){obj.attrs=this.attrs;break}return obj}static fromJSON(schema,json){if(!json)throw RangeError(`Invalid input for Mark.fromJSON`);let type=schema.marks[json.type];if(!type)throw RangeError(`There is no mark type ${json.type} in this schema`);let mark=type.create(json.attrs);return type.checkAttrs(mark.attrs),mark}static sameSet(a,b){if(a==b)return!0;if(a.length!=b.length)return!1;for(let i=0;i<a.length;i++)if(!a[i].eq(b[i]))return!1;return!0}static setFrom(marks){if(!marks||Array.isArray(marks)&&marks.length==0)return Mark.none;if(marks instanceof Mark)return[marks];let copy=marks.slice();return copy.sort((a,b)=>a.type.rank-b.type.rank),copy}};Mark.none=[];var ReplaceError=class extends Error{},Slice=class Slice{constructor(content,openStart,openEnd){this.content=content,this.openStart=openStart,this.openEnd=openEnd}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(pos,fragment){let content=insertInto(this.content,pos+this.openStart,fragment,this.openStart+1,this.openEnd+1);return content&&new Slice(content,this.openStart,this.openEnd)}removeBetween(from,to){return new Slice(removeRange(this.content,from+this.openStart,to+this.openStart),this.openStart,this.openEnd)}eq(other){return this.content.eq(other.content)&&this.openStart==other.openStart&&this.openEnd==other.openEnd}toString(){return this.content+`(`+this.openStart+`,`+this.openEnd+`)`}toJSON(){if(!this.content.size)return null;let json={content:this.content.toJSON()};return this.openStart>0&&(json.openStart=this.openStart),this.openEnd>0&&(json.openEnd=this.openEnd),json}static fromJSON(schema,json){if(!json)return Slice.empty;let openStart=json.openStart||0,openEnd=json.openEnd||0;if(typeof openStart!=`number`||typeof openEnd!=`number`)throw RangeError(`Invalid input for Slice.fromJSON`);return new Slice(Fragment.fromJSON(schema,json.content),openStart,openEnd)}static maxOpen(fragment,openIsolating=!0){let openStart=0,openEnd=0;for(let n=fragment.firstChild;n&&!n.isLeaf&&(openIsolating||!n.type.spec.isolating);n=n.firstChild)openStart++;for(let n=fragment.lastChild;n&&!n.isLeaf&&(openIsolating||!n.type.spec.isolating);n=n.lastChild)openEnd++;return new Slice(fragment,openStart,openEnd)}};Slice.empty=new Slice(Fragment.empty,0,0);function removeRange(content,from,to){let{index,offset}=content.findIndex(from),child=content.maybeChild(index),{index:indexTo,offset:offsetTo}=content.findIndex(to);if(offset==from||child.isText){if(offsetTo!=to&&!content.child(indexTo).isText)throw RangeError(`Removing non-flat range`);return content.cut(0,from).append(content.cut(to))}if(index!=indexTo)throw RangeError(`Removing non-flat range`);return content.replaceChild(index,child.copy(removeRange(child.content,from-offset-1,to-offset-1)))}function insertInto(content,dist,insert,openStart,openEnd,parent){let{index,offset}=content.findIndex(dist),child=content.maybeChild(index);if(offset==dist||child.isText)return parent&&openStart<=0&&openEnd<=0&&!parent.canReplace(index,index,insert)?null:content.cut(0,dist).append(insert).append(content.cut(dist));let inner=insertInto(child.content,dist-offset-1,insert,index==0?openStart-1:0,index==content.childCount-1?openEnd-1:0,child);return inner&&content.replaceChild(index,child.copy(inner))}function replace($from,$to,slice){if(slice.openStart>$from.depth)throw new ReplaceError(`Inserted content deeper than insertion position`);if($from.depth-slice.openStart!=$to.depth-slice.openEnd)throw new ReplaceError(`Inconsistent open depths`);return replaceOuter($from,$to,slice,0)}function replaceOuter($from,$to,slice,depth){let index=$from.index(depth),node=$from.node(depth);if(index==$to.index(depth)&&depth<$from.depth-slice.openStart){let inner=replaceOuter($from,$to,slice,depth+1);return node.copy(node.content.replaceChild(index,inner))}else if(!slice.content.size)return close(node,replaceTwoWay($from,$to,depth));else if(!slice.openStart&&!slice.openEnd&&$from.depth==depth&&$to.depth==depth){let parent=$from.parent,content=parent.content;return close(parent,content.cut(0,$from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)))}else{let{start,end}=prepareSliceForReplace(slice,$from);return close(node,replaceThreeWay($from,start,end,$to,depth))}}function checkJoin(main,sub){if(!sub.type.compatibleContent(main.type))throw new ReplaceError(`Cannot join `+sub.type.name+` onto `+main.type.name)}function joinable($before,$after,depth){let node=$before.node(depth);return checkJoin(node,$after.node(depth)),node}function addNode(child,target){let last=target.length-1;last>=0&&child.isText&&child.sameMarkup(target[last])?target[last]=child.withText(target[last].text+child.text):target.push(child)}function addRange($start,$end,depth,target){let node=($end||$start).node(depth),startIndex=0,endIndex=$end?$end.index(depth):node.childCount;$start&&(startIndex=$start.index(depth),$start.depth>depth?startIndex++:$start.textOffset&&(addNode($start.nodeAfter,target),startIndex++));for(let i=startIndex;i<endIndex;i++)addNode(node.child(i),target);$end&&$end.depth==depth&&$end.textOffset&&addNode($end.nodeBefore,target)}function close(node,content){if(!node.type.validContent(content))throw new ReplaceError(`Invalid content for node `+node.type.name);return node.copy(content)}function replaceThreeWay($from,$start,$end,$to,depth){let openStart=$from.depth>depth&&joinable($from,$start,depth+1),openEnd=$to.depth>depth&&joinable($end,$to,depth+1),content=[];return addRange(null,$from,depth,content),openStart&&openEnd&&$start.index(depth)==$end.index(depth)?(checkJoin(openStart,openEnd),addNode(close(openStart,replaceThreeWay($from,$start,$end,$to,depth+1)),content)):(openStart&&addNode(close(openStart,replaceTwoWay($from,$start,depth+1)),content),addRange($start,$end,depth,content),openEnd&&addNode(close(openEnd,replaceTwoWay($end,$to,depth+1)),content)),addRange($to,null,depth,content),new Fragment(content)}function replaceTwoWay($from,$to,depth){let content=[];return addRange(null,$from,depth,content),$from.depth>depth&&addNode(close(joinable($from,$to,depth+1),replaceTwoWay($from,$to,depth+1)),content),addRange($to,null,depth,content),new Fragment(content)}function prepareSliceForReplace(slice,$along){let extra=$along.depth-slice.openStart,node=$along.node(extra).copy(slice.content);for(let i=extra-1;i>=0;i--)node=$along.node(i).copy(Fragment.from(node));return{start:node.resolveNoCache(slice.openStart+extra),end:node.resolveNoCache(node.content.size-slice.openEnd-extra)}}var ResolvedPos=class ResolvedPos{constructor(pos,path,parentOffset){this.pos=pos,this.path=path,this.parentOffset=parentOffset,this.depth=path.length/3-1}resolveDepth(val){return val==null?this.depth:val<0?this.depth+val:val}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(depth){return this.path[this.resolveDepth(depth)*3]}index(depth){return this.path[this.resolveDepth(depth)*3+1]}indexAfter(depth){return depth=this.resolveDepth(depth),this.index(depth)+(depth==this.depth&&!this.textOffset?0:1)}start(depth){return depth=this.resolveDepth(depth),depth==0?0:this.path[depth*3-1]+1}end(depth){return depth=this.resolveDepth(depth),this.start(depth)+this.node(depth).content.size}before(depth){if(depth=this.resolveDepth(depth),!depth)throw RangeError(`There is no position before the top-level node`);return depth==this.depth+1?this.pos:this.path[depth*3-1]}after(depth){if(depth=this.resolveDepth(depth),!depth)throw RangeError(`There is no position after the top-level node`);return depth==this.depth+1?this.pos:this.path[depth*3-1]+this.path[depth*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let parent=this.parent,index=this.index(this.depth);if(index==parent.childCount)return null;let dOff=this.pos-this.path[this.path.length-1],child=parent.child(index);return dOff?parent.child(index).cut(dOff):child}get nodeBefore(){let index=this.index(this.depth),dOff=this.pos-this.path[this.path.length-1];return dOff?this.parent.child(index).cut(0,dOff):index==0?null:this.parent.child(index-1)}posAtIndex(index,depth){depth=this.resolveDepth(depth);let node=this.path[depth*3],pos=depth==0?0:this.path[depth*3-1]+1;for(let i=0;i<index;i++)pos+=node.child(i).nodeSize;return pos}marks(){let parent=this.parent,index=this.index();if(parent.content.size==0)return Mark.none;if(this.textOffset)return parent.child(index).marks;let main=parent.maybeChild(index-1),other=parent.maybeChild(index);if(!main){let tmp=main;main=other,other=tmp}let marks=main.marks;for(var i=0;i<marks.length;i++)marks[i].type.spec.inclusive===!1&&(!other||!marks[i].isInSet(other.marks))&&(marks=marks[i--].removeFromSet(marks));return marks}marksAcross($end){let after=this.parent.maybeChild(this.index());if(!after||!after.isInline)return null;let marks=after.marks,next=$end.parent.maybeChild($end.index());for(var i=0;i<marks.length;i++)marks[i].type.spec.inclusive===!1&&(!next||!marks[i].isInSet(next.marks))&&(marks=marks[i--].removeFromSet(marks));return marks}sharedDepth(pos){for(let depth=this.depth;depth>0;depth--)if(this.start(depth)<=pos&&this.end(depth)>=pos)return depth;return 0}blockRange(other=this,pred){if(other.pos<this.pos)return other.blockRange(this);for(let d=this.depth-(this.parent.inlineContent||this.pos==other.pos?1:0);d>=0;d--)if(other.pos<=this.end(d)&&(!pred||pred(this.node(d))))return new NodeRange(this,other,d);return null}sameParent(other){return this.pos-this.parentOffset==other.pos-other.parentOffset}max(other){return other.pos>this.pos?other:this}min(other){return other.pos<this.pos?other:this}toString(){let str=``;for(let i=1;i<=this.depth;i++)str+=(str?`/`:``)+this.node(i).type.name+`_`+this.index(i-1);return str+`:`+this.parentOffset}static resolve(doc,pos){if(!(pos>=0&&pos<=doc.content.size))throw RangeError(`Position `+pos+` out of range`);let path=[],start=0,parentOffset=pos;for(let node=doc;;){let{index,offset}=node.content.findIndex(parentOffset),rem=parentOffset-offset;if(path.push(node,index,start+offset),!rem||(node=node.child(index),node.isText))break;parentOffset=rem-1,start+=offset+1}return new ResolvedPos(pos,path,parentOffset)}static resolveCached(doc,pos){let cache=resolveCache.get(doc);if(cache)for(let i=0;i<cache.elts.length;i++){let elt=cache.elts[i];if(elt.pos==pos)return elt}else resolveCache.set(doc,cache=new ResolveCache);let result=cache.elts[cache.i]=ResolvedPos.resolve(doc,pos);return cache.i=(cache.i+1)%resolveCacheSize,result}},ResolveCache=class{constructor(){this.elts=[],this.i=0}},resolveCacheSize=12,resolveCache=new WeakMap,NodeRange=class{constructor($from,$to,depth){this.$from=$from,this.$to=$to,this.depth=depth}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}},emptyAttrs=Object.create(null),Node=class Node{constructor(type,attrs,content,marks=Mark.none){this.type=type,this.attrs=attrs,this.marks=marks,this.content=content||Fragment.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(index){return this.content.child(index)}maybeChild(index){return this.content.maybeChild(index)}forEach(f){this.content.forEach(f)}nodesBetween(from,to,f,startPos=0){this.content.nodesBetween(from,to,f,startPos,this)}descendants(f){this.nodesBetween(0,this.content.size,f)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,``)}textBetween(from,to,blockSeparator,leafText){return this.content.textBetween(from,to,blockSeparator,leafText)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(other){return this==other||this.sameMarkup(other)&&this.content.eq(other.content)}sameMarkup(other){return this.hasMarkup(other.type,other.attrs,other.marks)}hasMarkup(type,attrs,marks){return this.type==type&&compareDeep(this.attrs,attrs||type.defaultAttrs||emptyAttrs)&&Mark.sameSet(this.marks,marks||Mark.none)}copy(content=null){return content==this.content?this:new Node(this.type,this.attrs,content,this.marks)}mark(marks){return marks==this.marks?this:new Node(this.type,this.attrs,this.content,marks)}cut(from,to=this.content.size){return from==0&&to==this.content.size?this:this.copy(this.content.cut(from,to))}slice(from,to=this.content.size,includeParents=!1){if(from==to)return Slice.empty;let $from=this.resolve(from),$to=this.resolve(to),depth=includeParents?0:$from.sharedDepth(to),start=$from.start(depth);return new Slice($from.node(depth).content.cut($from.pos-start,$to.pos-start),$from.depth-depth,$to.depth-depth)}replace(from,to,slice){return replace(this.resolve(from),this.resolve(to),slice)}nodeAt(pos){for(let node=this;;){let{index,offset}=node.content.findIndex(pos);if(node=node.maybeChild(index),!node)return null;if(offset==pos||node.isText)return node;pos-=offset+1}}childAfter(pos){let{index,offset}=this.content.findIndex(pos);return{node:this.content.maybeChild(index),index,offset}}childBefore(pos){if(pos==0)return{node:null,index:0,offset:0};let{index,offset}=this.content.findIndex(pos);if(offset<pos)return{node:this.content.child(index),index,offset};let node=this.content.child(index-1);return{node,index:index-1,offset:offset-node.nodeSize}}resolve(pos){return ResolvedPos.resolveCached(this,pos)}resolveNoCache(pos){return ResolvedPos.resolve(this,pos)}rangeHasMark(from,to,type){let found=!1;return to>from&&this.nodesBetween(from,to,node=>(type.isInSet(node.marks)&&(found=!0),!found)),found}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let name=this.type.name;return this.content.size&&(name+=`(`+this.content.toStringInner()+`)`),wrapMarks(this.marks,name)}contentMatchAt(index){let match=this.type.contentMatch.matchFragment(this.content,0,index);if(!match)throw Error(`Called contentMatchAt on a node with invalid content`);return match}canReplace(from,to,replacement=Fragment.empty,start=0,end=replacement.childCount){let one=this.contentMatchAt(from).matchFragment(replacement,start,end),two=one&&one.matchFragment(this.content,to);if(!two||!two.validEnd)return!1;for(let i=start;i<end;i++)if(!this.type.allowsMarks(replacement.child(i).marks))return!1;return!0}canReplaceWith(from,to,type,marks){if(marks&&!this.type.allowsMarks(marks))return!1;let start=this.contentMatchAt(from).matchType(type),end=start&&start.matchFragment(this.content,to);return end?end.validEnd:!1}canAppend(other){return other.content.size?this.canReplace(this.childCount,this.childCount,other.content):this.type.compatibleContent(other.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let copy=Mark.none;for(let i=0;i<this.marks.length;i++){let mark=this.marks[i];mark.type.checkAttrs(mark.attrs),copy=mark.addToSet(copy)}if(!Mark.sameSet(copy,this.marks))throw RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map(m=>m.type.name)}`);this.content.forEach(node=>node.check())}toJSON(){let obj={type:this.type.name};for(let _ in this.attrs){obj.attrs=this.attrs;break}return this.content.size&&(obj.content=this.content.toJSON()),this.marks.length&&(obj.marks=this.marks.map(n=>n.toJSON())),obj}static fromJSON(schema,json){if(!json)throw RangeError(`Invalid input for Node.fromJSON`);let marks;if(json.marks){if(!Array.isArray(json.marks))throw RangeError(`Invalid mark data for Node.fromJSON`);marks=json.marks.map(schema.markFromJSON)}if(json.type==`text`){if(typeof json.text!=`string`)throw RangeError(`Invalid text node in JSON`);return schema.text(json.text,marks)}let content=Fragment.fromJSON(schema,json.content),node=schema.nodeType(json.type).create(json.attrs,content,marks);return node.type.checkAttrs(node.attrs),node}};Node.prototype.text=void 0;function wrapMarks(marks,str){for(let i=marks.length-1;i>=0;i--)str=marks[i].type.name+`(`+str+`)`;return str}var ContentMatch=class ContentMatch{constructor(validEnd){this.validEnd=validEnd,this.next=[],this.wrapCache=[]}static parse(string,nodeTypes){let stream=new TokenStream(string,nodeTypes);if(stream.next==null)return ContentMatch.empty;let expr=parseExpr(stream);stream.next&&stream.err(`Unexpected trailing text`);let match=dfa(nfa(expr));return checkForDeadEnds(match,stream),match}matchType(type){for(let i=0;i<this.next.length;i++)if(this.next[i].type==type)return this.next[i].next;return null}matchFragment(frag,start=0,end=frag.childCount){let cur=this;for(let i=start;cur&&i<end;i++)cur=cur.matchType(frag.child(i).type);return cur}get inlineContent(){return this.next.length!=0&&this.next[0].type.isInline}get defaultType(){for(let i=0;i<this.next.length;i++){let{type}=this.next[i];if(!(type.isText||type.hasRequiredAttrs()))return type}return null}compatible(other){for(let i=0;i<this.next.length;i++)for(let j=0;j<other.next.length;j++)if(this.next[i].type==other.next[j].type)return!0;return!1}fillBefore(after,toEnd=!1,startIndex=0){let seen=[this];function search(match,types){let finished=match.matchFragment(after,startIndex);if(finished&&(!toEnd||finished.validEnd))return Fragment.from(types.map(tp=>tp.createAndFill()));for(let i=0;i<match.next.length;i++){let{type,next}=match.next[i];if(!(type.isText||type.hasRequiredAttrs())&&seen.indexOf(next)==-1){seen.push(next);let found=search(next,types.concat(type));if(found)return found}}return null}return search(this,[])}findWrapping(target){for(let i=0;i<this.wrapCache.length;i+=2)if(this.wrapCache[i]==target)return this.wrapCache[i+1];let computed=this.computeWrapping(target);return this.wrapCache.push(target,computed),computed}computeWrapping(target){let seen=Object.create(null),active=[{match:this,type:null,via:null}];for(;active.length;){let current=active.shift(),match=current.match;if(match.matchType(target)){let result=[];for(let obj=current;obj.type;obj=obj.via)result.push(obj.type);return result.reverse()}for(let i=0;i<match.next.length;i++){let{type,next}=match.next[i];!type.isLeaf&&!type.hasRequiredAttrs()&&!(type.name in seen)&&(!current.type||next.validEnd)&&(active.push({match:type.contentMatch,type,via:current}),seen[type.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(n){if(n>=this.next.length)throw RangeError(`There's no ${n}th edge in this content match`);return this.next[n]}toString(){let seen=[];function scan(m){seen.push(m);for(let i=0;i<m.next.length;i++)seen.indexOf(m.next[i].next)==-1&&scan(m.next[i].next)}return scan(this),seen.map((m,i)=>{let out=i+(m.validEnd?`*`:` `)+` `;for(let i=0;i<m.next.length;i++)out+=(i?`, `:``)+m.next[i].type.name+`->`+seen.indexOf(m.next[i].next);return out}).join(`
2
- `)}};ContentMatch.empty=new ContentMatch(!0);var TokenStream=class{constructor(string,nodeTypes){this.string=string,this.nodeTypes=nodeTypes,this.inline=null,this.pos=0,this.tokens=string.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(tok){return this.next==tok&&(this.pos++||!0)}err(str){throw SyntaxError(str+` (in content expression '`+this.string+`')`)}};function parseExpr(stream){let exprs=[];do exprs.push(parseExprSeq(stream));while(stream.eat(`|`));return exprs.length==1?exprs[0]:{type:`choice`,exprs}}function parseExprSeq(stream){let exprs=[];do exprs.push(parseExprSubscript(stream));while(stream.next&&stream.next!=`)`&&stream.next!=`|`);return exprs.length==1?exprs[0]:{type:`seq`,exprs}}function parseExprSubscript(stream){let expr=parseExprAtom(stream);for(;;)if(stream.eat(`+`))expr={type:`plus`,expr};else if(stream.eat(`*`))expr={type:`star`,expr};else if(stream.eat(`?`))expr={type:`opt`,expr};else if(stream.eat(`{`))expr=parseExprRange(stream,expr);else break;return expr}function parseNum(stream){/\D/.test(stream.next)&&stream.err(`Expected number, got '`+stream.next+`'`);let result=Number(stream.next);return stream.pos++,result}function parseExprRange(stream,expr){let min=parseNum(stream),max=min;return stream.eat(`,`)&&(max=stream.next==`}`?-1:parseNum(stream)),stream.eat(`}`)||stream.err(`Unclosed braced range`),{type:`range`,min,max,expr}}function resolveName(stream,name){let types=stream.nodeTypes,type=types[name];if(type)return[type];let result=[];for(let typeName in types){let type=types[typeName];type.isInGroup(name)&&result.push(type)}return result.length==0&&stream.err(`No node type or group '`+name+`' found`),result}function parseExprAtom(stream){if(stream.eat(`(`)){let expr=parseExpr(stream);return stream.eat(`)`)||stream.err(`Missing closing paren`),expr}else if(/\W/.test(stream.next))stream.err(`Unexpected token '`+stream.next+`'`);else{let exprs=resolveName(stream,stream.next).map(type=>(stream.inline==null?stream.inline=type.isInline:stream.inline!=type.isInline&&stream.err(`Mixing inline and block content`),{type:`name`,value:type}));return stream.pos++,exprs.length==1?exprs[0]:{type:`choice`,exprs}}}function nfa(expr){let nfa=[[]];return connect(compile(expr,0),node()),nfa;function node(){return nfa.push([])-1}function edge(from,to,term){let edge={term,to};return nfa[from].push(edge),edge}function connect(edges,to){edges.forEach(edge=>edge.to=to)}function compile(expr,from){if(expr.type==`choice`)return expr.exprs.reduce((out,expr)=>out.concat(compile(expr,from)),[]);if(expr.type==`seq`)for(let i=0;;i++){let next=compile(expr.exprs[i],from);if(i==expr.exprs.length-1)return next;connect(next,from=node())}else if(expr.type==`star`){let loop=node();return edge(from,loop),connect(compile(expr.expr,loop),loop),[edge(loop)]}else if(expr.type==`plus`){let loop=node();return connect(compile(expr.expr,from),loop),connect(compile(expr.expr,loop),loop),[edge(loop)]}else if(expr.type==`opt`)return[edge(from)].concat(compile(expr.expr,from));else if(expr.type==`range`){let cur=from;for(let i=0;i<expr.min;i++){let next=node();connect(compile(expr.expr,cur),next),cur=next}if(expr.max==-1)connect(compile(expr.expr,cur),cur);else for(let i=expr.min;i<expr.max;i++){let next=node();edge(cur,next),connect(compile(expr.expr,cur),next),cur=next}return[edge(cur)]}else if(expr.type==`name`)return[edge(from,void 0,expr.value)];else throw Error(`Unknown expr type`)}}function cmp(a,b){return b-a}function nullFrom(nfa,node){let result=[];return scan(node),result.sort(cmp);function scan(node){let edges=nfa[node];if(edges.length==1&&!edges[0].term)return scan(edges[0].to);result.push(node);for(let i=0;i<edges.length;i++){let{term,to}=edges[i];!term&&result.indexOf(to)==-1&&scan(to)}}}function dfa(nfa){let labeled=Object.create(null);return explore(nullFrom(nfa,0));function explore(states){let out=[];states.forEach(node=>{nfa[node].forEach(({term,to})=>{if(!term)return;let set;for(let i=0;i<out.length;i++)out[i][0]==term&&(set=out[i][1]);nullFrom(nfa,to).forEach(node=>{set||out.push([term,set=[]]),set.indexOf(node)==-1&&set.push(node)})})});let state=labeled[states.join(`,`)]=new ContentMatch(states.indexOf(nfa.length-1)>-1);for(let i=0;i<out.length;i++){let states=out[i][1].sort(cmp);state.next.push({type:out[i][0],next:labeled[states.join(`,`)]||explore(states)})}return state}}function checkForDeadEnds(match,stream){for(let i=0,work=[match];i<work.length;i++){let state=work[i],dead=!state.validEnd,nodes=[];for(let j=0;j<state.next.length;j++){let{type,next}=state.next[j];nodes.push(type.name),dead&&!(type.isText||type.hasRequiredAttrs())&&(dead=!1),work.indexOf(next)==-1&&work.push(next)}dead&&stream.err(`Only non-generatable nodes (`+nodes.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}var lower16=65535,factor16=2**16;function makeRecover(index,offset){return index+offset*factor16}function recoverIndex(value){return value&lower16}function recoverOffset(value){return(value-(value&lower16))/factor16}var DEL_BEFORE=1,DEL_AFTER=2,DEL_ACROSS=4,DEL_SIDE=8,MapResult=class{constructor(pos,delInfo,recover){this.pos=pos,this.delInfo=delInfo,this.recover=recover}get deleted(){return(this.delInfo&DEL_SIDE)>0}get deletedBefore(){return(this.delInfo&5)>0}get deletedAfter(){return(this.delInfo&6)>0}get deletedAcross(){return(this.delInfo&DEL_ACROSS)>0}},StepMap=class StepMap{constructor(ranges,inverted=!1){if(this.ranges=ranges,this.inverted=inverted,!ranges.length&&StepMap.empty)return StepMap.empty}recover(value){let diff=0,index=recoverIndex(value);if(!this.inverted)for(let i=0;i<index;i++)diff+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[index*3]+diff+recoverOffset(value)}mapResult(pos,assoc=1){return this._map(pos,assoc,!1)}map(pos,assoc=1){return this._map(pos,assoc,!0)}_map(pos,assoc,simple){let diff=0,oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let start=this.ranges[i]-(this.inverted?diff:0);if(start>pos)break;let oldSize=this.ranges[i+oldIndex],newSize=this.ranges[i+newIndex],end=start+oldSize;if(pos<=end){let side=oldSize?pos==start?-1:pos==end?1:assoc:assoc,result=start+diff+(side<0?0:newSize);if(simple)return result;let recover=pos==(assoc<0?start:end)?null:makeRecover(i/3,pos-start),del=pos==start?DEL_AFTER:pos==end?DEL_BEFORE:DEL_ACROSS;return(assoc<0?pos!=start:pos!=end)&&(del|=DEL_SIDE),new MapResult(result,del,recover)}diff+=newSize-oldSize}return simple?pos+diff:new MapResult(pos+diff,0,null)}touches(pos,recover){let diff=0,index=recoverIndex(recover),oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let start=this.ranges[i]-(this.inverted?diff:0);if(start>pos)break;let oldSize=this.ranges[i+oldIndex];if(pos<=start+oldSize&&i==index*3)return!0;diff+=this.ranges[i+newIndex]-oldSize}return!1}forEach(f){let oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0,diff=0;i<this.ranges.length;i+=3){let start=this.ranges[i],oldStart=start-(this.inverted?diff:0),newStart=start+(this.inverted?0:diff),oldSize=this.ranges[i+oldIndex],newSize=this.ranges[i+newIndex];f(oldStart,oldStart+oldSize,newStart,newStart+newSize),diff+=newSize-oldSize}}invert(){return new StepMap(this.ranges,!this.inverted)}toString(){return(this.inverted?`-`:``)+JSON.stringify(this.ranges)}static offset(n){return n==0?StepMap.empty:new StepMap(n<0?[0,-n,0]:[0,0,n])}};StepMap.empty=new StepMap([]);var stepsByID=Object.create(null),Step=class{getMap(){return StepMap.empty}merge(other){return null}static fromJSON(schema,json){if(!json||!json.stepType)throw RangeError(`Invalid input for Step.fromJSON`);let type=stepsByID[json.stepType];if(!type)throw RangeError(`No step type ${json.stepType} defined`);return type.fromJSON(schema,json)}static jsonID(id,stepClass){if(id in stepsByID)throw RangeError(`Duplicate use of step JSON ID `+id);return stepsByID[id]=stepClass,stepClass.prototype.jsonID=id,stepClass}},StepResult=class StepResult{constructor(doc,failed){this.doc=doc,this.failed=failed}static ok(doc){return new StepResult(doc,null)}static fail(message){return new StepResult(null,message)}static fromReplace(doc,from,to,slice){try{return StepResult.ok(doc.replace(from,to,slice))}catch(e){if(e instanceof ReplaceError)return StepResult.fail(e.message);throw e}}};function mapFragment(fragment,f,parent){let mapped=[];for(let i=0;i<fragment.childCount;i++){let child=fragment.child(i);child.content.size&&(child=child.copy(mapFragment(child.content,f,child))),child.isInline&&(child=f(child,parent,i)),mapped.push(child)}return Fragment.fromArray(mapped)}var AddMarkStep=class AddMarkStep extends Step{constructor(from,to,mark){super(),this.from=from,this.to=to,this.mark=mark}apply(doc){let oldSlice=doc.slice(this.from,this.to),$from=doc.resolve(this.from),parent=$from.node($from.sharedDepth(this.to)),slice=new Slice(mapFragment(oldSlice.content,(node,parent)=>!node.isAtom||!parent.type.allowsMarkType(this.mark.type)?node:node.mark(this.mark.addToSet(node.marks)),parent),oldSlice.openStart,oldSlice.openEnd);return StepResult.fromReplace(doc,this.from,this.to,slice)}invert(){return new RemoveMarkStep(this.from,this.to,this.mark)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1);return from.deleted&&to.deleted||from.pos>=to.pos?null:new AddMarkStep(from.pos,to.pos,this.mark)}merge(other){return other instanceof AddMarkStep&&other.mark.eq(this.mark)&&this.from<=other.to&&this.to>=other.from?new AddMarkStep(Math.min(this.from,other.from),Math.max(this.to,other.to),this.mark):null}toJSON(){return{stepType:`addMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for AddMarkStep.fromJSON`);return new AddMarkStep(json.from,json.to,schema.markFromJSON(json.mark))}};Step.jsonID(`addMark`,AddMarkStep);var RemoveMarkStep=class RemoveMarkStep extends Step{constructor(from,to,mark){super(),this.from=from,this.to=to,this.mark=mark}apply(doc){let oldSlice=doc.slice(this.from,this.to),slice=new Slice(mapFragment(oldSlice.content,node=>node.mark(this.mark.removeFromSet(node.marks)),doc),oldSlice.openStart,oldSlice.openEnd);return StepResult.fromReplace(doc,this.from,this.to,slice)}invert(){return new AddMarkStep(this.from,this.to,this.mark)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1);return from.deleted&&to.deleted||from.pos>=to.pos?null:new RemoveMarkStep(from.pos,to.pos,this.mark)}merge(other){return other instanceof RemoveMarkStep&&other.mark.eq(this.mark)&&this.from<=other.to&&this.to>=other.from?new RemoveMarkStep(Math.min(this.from,other.from),Math.max(this.to,other.to),this.mark):null}toJSON(){return{stepType:`removeMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for RemoveMarkStep.fromJSON`);return new RemoveMarkStep(json.from,json.to,schema.markFromJSON(json.mark))}};Step.jsonID(`removeMark`,RemoveMarkStep);var AddNodeMarkStep=class AddNodeMarkStep extends Step{constructor(pos,mark){super(),this.pos=pos,this.mark=mark}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at mark step's position`);let updated=node.type.create(node.attrs,null,this.mark.addToSet(node.marks));return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}invert(doc){let node=doc.nodeAt(this.pos);if(node){let newSet=this.mark.addToSet(node.marks);if(newSet.length==node.marks.length){for(let i=0;i<node.marks.length;i++)if(!node.marks[i].isInSet(newSet))return new AddNodeMarkStep(this.pos,node.marks[i]);return new AddNodeMarkStep(this.pos,this.mark)}}return new RemoveNodeMarkStep(this.pos,this.mark)}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new AddNodeMarkStep(pos.pos,this.mark)}toJSON(){return{stepType:`addNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(schema,json){if(typeof json.pos!=`number`)throw RangeError(`Invalid input for AddNodeMarkStep.fromJSON`);return new AddNodeMarkStep(json.pos,schema.markFromJSON(json.mark))}};Step.jsonID(`addNodeMark`,AddNodeMarkStep);var RemoveNodeMarkStep=class RemoveNodeMarkStep extends Step{constructor(pos,mark){super(),this.pos=pos,this.mark=mark}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at mark step's position`);let updated=node.type.create(node.attrs,null,this.mark.removeFromSet(node.marks));return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}invert(doc){let node=doc.nodeAt(this.pos);return!node||!this.mark.isInSet(node.marks)?this:new AddNodeMarkStep(this.pos,this.mark)}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new RemoveNodeMarkStep(pos.pos,this.mark)}toJSON(){return{stepType:`removeNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(schema,json){if(typeof json.pos!=`number`)throw RangeError(`Invalid input for RemoveNodeMarkStep.fromJSON`);return new RemoveNodeMarkStep(json.pos,schema.markFromJSON(json.mark))}};Step.jsonID(`removeNodeMark`,RemoveNodeMarkStep);var ReplaceStep=class ReplaceStep extends Step{constructor(from,to,slice,structure=!1){super(),this.from=from,this.to=to,this.slice=slice,this.structure=structure}apply(doc){return this.structure&&contentBetween(doc,this.from,this.to)?StepResult.fail(`Structure replace would overwrite content`):StepResult.fromReplace(doc,this.from,this.to,this.slice)}getMap(){return new StepMap([this.from,this.to-this.from,this.slice.size])}invert(doc){return new ReplaceStep(this.from,this.from+this.slice.size,doc.slice(this.from,this.to))}map(mapping){let to=mapping.mapResult(this.to,-1),from=this.from==this.to&&ReplaceStep.MAP_BIAS<0?to:mapping.mapResult(this.from,1);return from.deletedAcross&&to.deletedAcross?null:new ReplaceStep(from.pos,Math.max(from.pos,to.pos),this.slice,this.structure)}merge(other){if(!(other instanceof ReplaceStep)||other.structure||this.structure)return null;if(this.from+this.slice.size==other.from&&!this.slice.openEnd&&!other.slice.openStart){let slice=this.slice.size+other.slice.size==0?Slice.empty:new Slice(this.slice.content.append(other.slice.content),this.slice.openStart,other.slice.openEnd);return new ReplaceStep(this.from,this.to+(other.to-other.from),slice,this.structure)}else if(other.to==this.from&&!this.slice.openStart&&!other.slice.openEnd){let slice=this.slice.size+other.slice.size==0?Slice.empty:new Slice(other.slice.content.append(this.slice.content),other.slice.openStart,this.slice.openEnd);return new ReplaceStep(other.from,this.to,slice,this.structure)}else return null}toJSON(){let json={stepType:`replace`,from:this.from,to:this.to};return this.slice.size&&(json.slice=this.slice.toJSON()),this.structure&&(json.structure=!0),json}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for ReplaceStep.fromJSON`);return new ReplaceStep(json.from,json.to,Slice.fromJSON(schema,json.slice),!!json.structure)}};ReplaceStep.MAP_BIAS=1,Step.jsonID(`replace`,ReplaceStep);var ReplaceAroundStep=class ReplaceAroundStep extends Step{constructor(from,to,gapFrom,gapTo,slice,insert,structure=!1){super(),this.from=from,this.to=to,this.gapFrom=gapFrom,this.gapTo=gapTo,this.slice=slice,this.insert=insert,this.structure=structure}apply(doc){if(this.structure&&(contentBetween(doc,this.from,this.gapFrom)||contentBetween(doc,this.gapTo,this.to)))return StepResult.fail(`Structure gap-replace would overwrite content`);let gap=doc.slice(this.gapFrom,this.gapTo);if(gap.openStart||gap.openEnd)return StepResult.fail(`Gap is not a flat range`);let inserted=this.slice.insertAt(this.insert,gap.content);return inserted?StepResult.fromReplace(doc,this.from,this.to,inserted):StepResult.fail(`Content does not fit in gap`)}getMap(){return new StepMap([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(doc){let gap=this.gapTo-this.gapFrom;return new ReplaceAroundStep(this.from,this.from+this.slice.size+gap,this.from+this.insert,this.from+this.insert+gap,doc.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1),gapFrom=this.from==this.gapFrom?from.pos:mapping.map(this.gapFrom,-1),gapTo=this.to==this.gapTo?to.pos:mapping.map(this.gapTo,1);return from.deletedAcross&&to.deletedAcross||gapFrom<from.pos||gapTo>to.pos?null:new ReplaceAroundStep(from.pos,to.pos,gapFrom,gapTo,this.slice,this.insert,this.structure)}toJSON(){let json={stepType:`replaceAround`,from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(json.slice=this.slice.toJSON()),this.structure&&(json.structure=!0),json}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`||typeof json.gapFrom!=`number`||typeof json.gapTo!=`number`||typeof json.insert!=`number`)throw RangeError(`Invalid input for ReplaceAroundStep.fromJSON`);return new ReplaceAroundStep(json.from,json.to,json.gapFrom,json.gapTo,Slice.fromJSON(schema,json.slice),json.insert,!!json.structure)}};Step.jsonID(`replaceAround`,ReplaceAroundStep);function contentBetween(doc,from,to){let $from=doc.resolve(from),dist=to-from,depth=$from.depth;for(;dist>0&&depth>0&&$from.indexAfter(depth)==$from.node(depth).childCount;)depth--,dist--;if(dist>0){let next=$from.node(depth).maybeChild($from.indexAfter(depth));for(;dist>0;){if(!next||next.isLeaf)return!0;next=next.firstChild,dist--}}return!1}var AttrStep=class AttrStep extends Step{constructor(pos,attr,value){super(),this.pos=pos,this.attr=attr,this.value=value}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at attribute step's position`);let attrs=Object.create(null);for(let name in node.attrs)attrs[name]=node.attrs[name];attrs[this.attr]=this.value;let updated=node.type.create(attrs,null,node.marks);return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}getMap(){return StepMap.empty}invert(doc){return new AttrStep(this.pos,this.attr,doc.nodeAt(this.pos).attrs[this.attr])}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new AttrStep(pos.pos,this.attr,this.value)}toJSON(){return{stepType:`attr`,pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(schema,json){if(typeof json.pos!=`number`||typeof json.attr!=`string`)throw RangeError(`Invalid input for AttrStep.fromJSON`);return new AttrStep(json.pos,json.attr,json.value)}};Step.jsonID(`attr`,AttrStep);var DocAttrStep=class DocAttrStep extends Step{constructor(attr,value){super(),this.attr=attr,this.value=value}apply(doc){let attrs=Object.create(null);for(let name in doc.attrs)attrs[name]=doc.attrs[name];attrs[this.attr]=this.value;let updated=doc.type.create(attrs,doc.content,doc.marks);return StepResult.ok(updated)}getMap(){return StepMap.empty}invert(doc){return new DocAttrStep(this.attr,doc.attrs[this.attr])}map(mapping){return this}toJSON(){return{stepType:`docAttr`,attr:this.attr,value:this.value}}static fromJSON(schema,json){if(typeof json.attr!=`string`)throw RangeError(`Invalid input for DocAttrStep.fromJSON`);return new DocAttrStep(json.attr,json.value)}};Step.jsonID(`docAttr`,DocAttrStep);var TransformError=class extends Error{};TransformError=function TransformError(message){let err=Error.call(this,message);return err.__proto__=TransformError.prototype,err},TransformError.prototype=Object.create(Error.prototype),TransformError.prototype.constructor=TransformError,TransformError.prototype.name=`TransformError`;var classesById=Object.create(null),Selection=class{constructor($anchor,$head,ranges){this.$anchor=$anchor,this.$head=$head,this.ranges=ranges||[new SelectionRange($anchor.min($head),$anchor.max($head))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let ranges=this.ranges;for(let i=0;i<ranges.length;i++)if(ranges[i].$from.pos!=ranges[i].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(tr,content=Slice.empty){let lastNode=content.content.lastChild,lastParent=null;for(let i=0;i<content.openEnd;i++)lastParent=lastNode,lastNode=lastNode.lastChild;let mapFrom=tr.steps.length,ranges=this.ranges;for(let i=0;i<ranges.length;i++){let{$from,$to}=ranges[i],mapping=tr.mapping.slice(mapFrom);tr.replaceRange(mapping.map($from.pos),mapping.map($to.pos),i?Slice.empty:content),i==0&&selectionToInsertionEnd(tr,mapFrom,(lastNode?lastNode.isInline:lastParent&&lastParent.isTextblock)?-1:1)}}replaceWith(tr,node){let mapFrom=tr.steps.length,ranges=this.ranges;for(let i=0;i<ranges.length;i++){let{$from,$to}=ranges[i],mapping=tr.mapping.slice(mapFrom),from=mapping.map($from.pos),to=mapping.map($to.pos);i?tr.deleteRange(from,to):(tr.replaceRangeWith(from,to,node),selectionToInsertionEnd(tr,mapFrom,node.isInline?-1:1))}}static findFrom($pos,dir,textOnly=!1){let inner=$pos.parent.inlineContent?new TextSelection($pos):findSelectionIn($pos.node(0),$pos.parent,$pos.pos,$pos.index(),dir,textOnly);if(inner)return inner;for(let depth=$pos.depth-1;depth>=0;depth--){let found=dir<0?findSelectionIn($pos.node(0),$pos.node(depth),$pos.before(depth+1),$pos.index(depth),dir,textOnly):findSelectionIn($pos.node(0),$pos.node(depth),$pos.after(depth+1),$pos.index(depth)+1,dir,textOnly);if(found)return found}return null}static near($pos,bias=1){return this.findFrom($pos,bias)||this.findFrom($pos,-bias)||new AllSelection($pos.node(0))}static atStart(doc){return findSelectionIn(doc,doc,0,0,1)||new AllSelection(doc)}static atEnd(doc){return findSelectionIn(doc,doc,doc.content.size,doc.childCount,-1)||new AllSelection(doc)}static fromJSON(doc,json){if(!json||!json.type)throw RangeError(`Invalid input for Selection.fromJSON`);let cls=classesById[json.type];if(!cls)throw RangeError(`No selection type ${json.type} defined`);return cls.fromJSON(doc,json)}static jsonID(id,selectionClass){if(id in classesById)throw RangeError(`Duplicate use of selection JSON ID `+id);return classesById[id]=selectionClass,selectionClass.prototype.jsonID=id,selectionClass}getBookmark(){return TextSelection.between(this.$anchor,this.$head).getBookmark()}};Selection.prototype.visible=!0;var SelectionRange=class{constructor($from,$to){this.$from=$from,this.$to=$to}},warnedAboutTextSelection=!1;function checkTextSelection($pos){!warnedAboutTextSelection&&!$pos.parent.inlineContent&&(warnedAboutTextSelection=!0,console.warn(`TextSelection endpoint not pointing into a node with inline content (`+$pos.parent.type.name+`)`))}var TextSelection=class TextSelection extends Selection{constructor($anchor,$head=$anchor){checkTextSelection($anchor),checkTextSelection($head),super($anchor,$head)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(doc,mapping){let $head=doc.resolve(mapping.map(this.head));if(!$head.parent.inlineContent)return Selection.near($head);let $anchor=doc.resolve(mapping.map(this.anchor));return new TextSelection($anchor.parent.inlineContent?$anchor:$head,$head)}replace(tr,content=Slice.empty){if(super.replace(tr,content),content==Slice.empty){let marks=this.$from.marksAcross(this.$to);marks&&tr.ensureMarks(marks)}}eq(other){return other instanceof TextSelection&&other.anchor==this.anchor&&other.head==this.head}getBookmark(){return new TextBookmark(this.anchor,this.head)}toJSON(){return{type:`text`,anchor:this.anchor,head:this.head}}static fromJSON(doc,json){if(typeof json.anchor!=`number`||typeof json.head!=`number`)throw RangeError(`Invalid input for TextSelection.fromJSON`);return new TextSelection(doc.resolve(json.anchor),doc.resolve(json.head))}static create(doc,anchor,head=anchor){let $anchor=doc.resolve(anchor);return new this($anchor,head==anchor?$anchor:doc.resolve(head))}static between($anchor,$head,bias){let dPos=$anchor.pos-$head.pos;if((!bias||dPos)&&(bias=dPos>=0?1:-1),!$head.parent.inlineContent){let found=Selection.findFrom($head,bias,!0)||Selection.findFrom($head,-bias,!0);if(found)$head=found.$head;else return Selection.near($head,bias)}return $anchor.parent.inlineContent||(dPos==0?$anchor=$head:($anchor=(Selection.findFrom($anchor,-bias,!0)||Selection.findFrom($anchor,bias,!0)).$anchor,$anchor.pos<$head.pos!=dPos<0&&($anchor=$head))),new TextSelection($anchor,$head)}};Selection.jsonID(`text`,TextSelection);var TextBookmark=class TextBookmark{constructor(anchor,head){this.anchor=anchor,this.head=head}map(mapping){return new TextBookmark(mapping.map(this.anchor),mapping.map(this.head))}resolve(doc){return TextSelection.between(doc.resolve(this.anchor),doc.resolve(this.head))}},NodeSelection=class NodeSelection extends Selection{constructor($pos){let node=$pos.nodeAfter,$end=$pos.node(0).resolve($pos.pos+node.nodeSize);super($pos,$end),this.node=node}map(doc,mapping){let{deleted,pos}=mapping.mapResult(this.anchor),$pos=doc.resolve(pos);return deleted?Selection.near($pos):new NodeSelection($pos)}content(){return new Slice(Fragment.from(this.node),0,0)}eq(other){return other instanceof NodeSelection&&other.anchor==this.anchor}toJSON(){return{type:`node`,anchor:this.anchor}}getBookmark(){return new NodeBookmark(this.anchor)}static fromJSON(doc,json){if(typeof json.anchor!=`number`)throw RangeError(`Invalid input for NodeSelection.fromJSON`);return new NodeSelection(doc.resolve(json.anchor))}static create(doc,from){return new NodeSelection(doc.resolve(from))}static isSelectable(node){return!node.isText&&node.type.spec.selectable!==!1}};NodeSelection.prototype.visible=!1,Selection.jsonID(`node`,NodeSelection);var NodeBookmark=class NodeBookmark{constructor(anchor){this.anchor=anchor}map(mapping){let{deleted,pos}=mapping.mapResult(this.anchor);return deleted?new TextBookmark(pos,pos):new NodeBookmark(pos)}resolve(doc){let $pos=doc.resolve(this.anchor),node=$pos.nodeAfter;return node&&NodeSelection.isSelectable(node)?new NodeSelection($pos):Selection.near($pos)}},AllSelection=class AllSelection extends Selection{constructor(doc){super(doc.resolve(0),doc.resolve(doc.content.size))}replace(tr,content=Slice.empty){if(content==Slice.empty){tr.delete(0,tr.doc.content.size);let sel=Selection.atStart(tr.doc);sel.eq(tr.selection)||tr.setSelection(sel)}else super.replace(tr,content)}toJSON(){return{type:`all`}}static fromJSON(doc){return new AllSelection(doc)}map(doc){return new AllSelection(doc)}eq(other){return other instanceof AllSelection}getBookmark(){return AllBookmark}};Selection.jsonID(`all`,AllSelection);var AllBookmark={map(){return this},resolve(doc){return new AllSelection(doc)}};function findSelectionIn(doc,node,pos,index,dir,text=!1){if(node.inlineContent)return TextSelection.create(doc,pos);for(let i=index-(dir>0?0:1);dir>0?i<node.childCount:i>=0;i+=dir){let child=node.child(i);if(!child.isAtom){let inner=findSelectionIn(doc,child,pos+dir,dir<0?child.childCount:0,dir,text);if(inner)return inner}else if(!text&&NodeSelection.isSelectable(child))return NodeSelection.create(doc,pos-(dir<0?child.nodeSize:0));pos+=child.nodeSize*dir}return null}function selectionToInsertionEnd(tr,startLen,bias){let last=tr.steps.length-1;if(last<startLen)return;let step=tr.steps[last];if(!(step instanceof ReplaceStep||step instanceof ReplaceAroundStep))return;let map=tr.mapping.maps[last],end;map.forEach((_from,_to,_newFrom,newTo)=>{end??=newTo}),tr.setSelection(Selection.near(tr.doc.resolve(end),bias))}function bind(f,self){return!self||!f?f:f.bind(self)}var FieldDesc=class{constructor(name,desc,self){this.name=name,this.init=bind(desc.init,self),this.apply=bind(desc.apply,self)}};new FieldDesc(`doc`,{init(config){return config.doc||config.schema.topNodeType.createAndFill()},apply(tr){return tr.doc}}),new FieldDesc(`selection`,{init(config,instance){return config.selection||Selection.atStart(instance.doc)},apply(tr){return tr.selection}}),new FieldDesc(`storedMarks`,{init(config){return config.storedMarks||null},apply(tr,_marks,_old,state){return state.selection.$cursor?tr.storedMarks:null}}),new FieldDesc(`scrollToSelection`,{init(){return 0},apply(tr,prev){return tr.scrolledIntoView?prev+1:prev}});function bindProps(obj,self,target){for(let prop in obj){let val=obj[prop];val instanceof Function?val=val.bind(self):prop==`handleDOMEvents`&&(val=bindProps(val,self,{})),target[prop]=val}return target}var Plugin=class{constructor(spec){this.spec=spec,this.props={},spec.props&&bindProps(spec.props,this,this.props),this.key=spec.key?spec.key.key:createKey(`plugin`)}getState(state){return state[this.key]}},keys=Object.create(null);function createKey(name){return name in keys?name+`$`+ ++keys[name]:(keys[name]=0,name+`$`)}var PluginKey=class{constructor(name=`key`){this.key=createKey(name)}get(state){return state.config.pluginsByKey[this.key]}getState(state){return state[this.key]}};export{TextSelection as a,PluginKey as i,NodeSelection as n,Plugin as r,AllSelection as t};
2
+ `)}};ContentMatch.empty=new ContentMatch(!0);var TokenStream=class{constructor(string,nodeTypes){this.string=string,this.nodeTypes=nodeTypes,this.inline=null,this.pos=0,this.tokens=string.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(tok){return this.next==tok&&(this.pos++||!0)}err(str){throw SyntaxError(str+` (in content expression '`+this.string+`')`)}};function parseExpr(stream){let exprs=[];do exprs.push(parseExprSeq(stream));while(stream.eat(`|`));return exprs.length==1?exprs[0]:{type:`choice`,exprs}}function parseExprSeq(stream){let exprs=[];do exprs.push(parseExprSubscript(stream));while(stream.next&&stream.next!=`)`&&stream.next!=`|`);return exprs.length==1?exprs[0]:{type:`seq`,exprs}}function parseExprSubscript(stream){let expr=parseExprAtom(stream);for(;;)if(stream.eat(`+`))expr={type:`plus`,expr};else if(stream.eat(`*`))expr={type:`star`,expr};else if(stream.eat(`?`))expr={type:`opt`,expr};else if(stream.eat(`{`))expr=parseExprRange(stream,expr);else break;return expr}function parseNum(stream){/\D/.test(stream.next)&&stream.err(`Expected number, got '`+stream.next+`'`);let result=Number(stream.next);return stream.pos++,result}function parseExprRange(stream,expr){let min=parseNum(stream),max=min;return stream.eat(`,`)&&(max=stream.next==`}`?-1:parseNum(stream)),stream.eat(`}`)||stream.err(`Unclosed braced range`),{type:`range`,min,max,expr}}function resolveName(stream,name){let types=stream.nodeTypes,type=types[name];if(type)return[type];let result=[];for(let typeName in types){let type=types[typeName];type.isInGroup(name)&&result.push(type)}return result.length==0&&stream.err(`No node type or group '`+name+`' found`),result}function parseExprAtom(stream){if(stream.eat(`(`)){let expr=parseExpr(stream);return stream.eat(`)`)||stream.err(`Missing closing paren`),expr}else if(/\W/.test(stream.next))stream.err(`Unexpected token '`+stream.next+`'`);else{let exprs=resolveName(stream,stream.next).map(type=>(stream.inline==null?stream.inline=type.isInline:stream.inline!=type.isInline&&stream.err(`Mixing inline and block content`),{type:`name`,value:type}));return stream.pos++,exprs.length==1?exprs[0]:{type:`choice`,exprs}}}function nfa(expr){let nfa=[[]];return connect(compile(expr,0),node()),nfa;function node(){return nfa.push([])-1}function edge(from,to,term){let edge={term,to};return nfa[from].push(edge),edge}function connect(edges,to){edges.forEach(edge=>edge.to=to)}function compile(expr,from){if(expr.type==`choice`)return expr.exprs.reduce((out,expr)=>out.concat(compile(expr,from)),[]);if(expr.type==`seq`)for(let i=0;;i++){let next=compile(expr.exprs[i],from);if(i==expr.exprs.length-1)return next;connect(next,from=node())}else if(expr.type==`star`){let loop=node();return edge(from,loop),connect(compile(expr.expr,loop),loop),[edge(loop)]}else if(expr.type==`plus`){let loop=node();return connect(compile(expr.expr,from),loop),connect(compile(expr.expr,loop),loop),[edge(loop)]}else if(expr.type==`opt`)return[edge(from)].concat(compile(expr.expr,from));else if(expr.type==`range`){let cur=from;for(let i=0;i<expr.min;i++){let next=node();connect(compile(expr.expr,cur),next),cur=next}if(expr.max==-1)connect(compile(expr.expr,cur),cur);else for(let i=expr.min;i<expr.max;i++){let next=node();edge(cur,next),connect(compile(expr.expr,cur),next),cur=next}return[edge(cur)]}else if(expr.type==`name`)return[edge(from,void 0,expr.value)];else throw Error(`Unknown expr type`)}}function cmp(a,b){return b-a}function nullFrom(nfa,node){let result=[];return scan(node),result.sort(cmp);function scan(node){let edges=nfa[node];if(edges.length==1&&!edges[0].term)return scan(edges[0].to);result.push(node);for(let i=0;i<edges.length;i++){let{term,to}=edges[i];!term&&result.indexOf(to)==-1&&scan(to)}}}function dfa(nfa){let labeled=Object.create(null);return explore(nullFrom(nfa,0));function explore(states){let out=[];states.forEach(node=>{nfa[node].forEach(({term,to})=>{if(!term)return;let set;for(let i=0;i<out.length;i++)out[i][0]==term&&(set=out[i][1]);nullFrom(nfa,to).forEach(node=>{set||out.push([term,set=[]]),set.indexOf(node)==-1&&set.push(node)})})});let state=labeled[states.join(`,`)]=new ContentMatch(states.indexOf(nfa.length-1)>-1);for(let i=0;i<out.length;i++){let states=out[i][1].sort(cmp);state.next.push({type:out[i][0],next:labeled[states.join(`,`)]||explore(states)})}return state}}function checkForDeadEnds(match,stream){for(let i=0,work=[match];i<work.length;i++){let state=work[i],dead=!state.validEnd,nodes=[];for(let j=0;j<state.next.length;j++){let{type,next}=state.next[j];nodes.push(type.name),dead&&!(type.isText||type.hasRequiredAttrs())&&(dead=!1),work.indexOf(next)==-1&&work.push(next)}dead&&stream.err(`Only non-generatable nodes (`+nodes.join(`, `)+`) in a required position (see https://prosemirror.net/docs/guide/#generatable)`)}}var lower16=65535,factor16=2**16;function makeRecover(index,offset){return index+offset*factor16}function recoverIndex(value){return value&lower16}function recoverOffset(value){return(value-(value&lower16))/factor16}var DEL_BEFORE=1,DEL_AFTER=2,DEL_ACROSS=4,DEL_SIDE=8,MapResult=class{constructor(pos,delInfo,recover){this.pos=pos,this.delInfo=delInfo,this.recover=recover}get deleted(){return(this.delInfo&DEL_SIDE)>0}get deletedBefore(){return(this.delInfo&5)>0}get deletedAfter(){return(this.delInfo&6)>0}get deletedAcross(){return(this.delInfo&DEL_ACROSS)>0}},StepMap=class StepMap{constructor(ranges,inverted=!1){if(this.ranges=ranges,this.inverted=inverted,!ranges.length&&StepMap.empty)return StepMap.empty}recover(value){let diff=0,index=recoverIndex(value);if(!this.inverted)for(let i=0;i<index;i++)diff+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[index*3]+diff+recoverOffset(value)}mapResult(pos,assoc=1){return this._map(pos,assoc,!1)}map(pos,assoc=1){return this._map(pos,assoc,!0)}_map(pos,assoc,simple){let diff=0,oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let start=this.ranges[i]-(this.inverted?diff:0);if(start>pos)break;let oldSize=this.ranges[i+oldIndex],newSize=this.ranges[i+newIndex],end=start+oldSize;if(pos<=end){let side=oldSize?pos==start?-1:pos==end?1:assoc:assoc,result=start+diff+(side<0?0:newSize);if(simple)return result;let recover=pos==(assoc<0?start:end)?null:makeRecover(i/3,pos-start),del=pos==start?DEL_AFTER:pos==end?DEL_BEFORE:DEL_ACROSS;return(assoc<0?pos!=start:pos!=end)&&(del|=DEL_SIDE),new MapResult(result,del,recover)}diff+=newSize-oldSize}return simple?pos+diff:new MapResult(pos+diff,0,null)}touches(pos,recover){let diff=0,index=recoverIndex(recover),oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0;i<this.ranges.length;i+=3){let start=this.ranges[i]-(this.inverted?diff:0);if(start>pos)break;let oldSize=this.ranges[i+oldIndex];if(pos<=start+oldSize&&i==index*3)return!0;diff+=this.ranges[i+newIndex]-oldSize}return!1}forEach(f){let oldIndex=this.inverted?2:1,newIndex=this.inverted?1:2;for(let i=0,diff=0;i<this.ranges.length;i+=3){let start=this.ranges[i],oldStart=start-(this.inverted?diff:0),newStart=start+(this.inverted?0:diff),oldSize=this.ranges[i+oldIndex],newSize=this.ranges[i+newIndex];f(oldStart,oldStart+oldSize,newStart,newStart+newSize),diff+=newSize-oldSize}}invert(){return new StepMap(this.ranges,!this.inverted)}toString(){return(this.inverted?`-`:``)+JSON.stringify(this.ranges)}static offset(n){return n==0?StepMap.empty:new StepMap(n<0?[0,-n,0]:[0,0,n])}};StepMap.empty=new StepMap([]);var stepsByID=Object.create(null),Step=class{getMap(){return StepMap.empty}merge(other){return null}static fromJSON(schema,json){if(!json||!json.stepType)throw RangeError(`Invalid input for Step.fromJSON`);let type=stepsByID[json.stepType];if(!type)throw RangeError(`No step type ${json.stepType} defined`);return type.fromJSON(schema,json)}static jsonID(id,stepClass){if(id in stepsByID)throw RangeError(`Duplicate use of step JSON ID `+id);return stepsByID[id]=stepClass,stepClass.prototype.jsonID=id,stepClass}},StepResult=class StepResult{constructor(doc,failed){this.doc=doc,this.failed=failed}static ok(doc){return new StepResult(doc,null)}static fail(message){return new StepResult(null,message)}static fromReplace(doc,from,to,slice){try{return StepResult.ok(doc.replace(from,to,slice))}catch(e){if(e instanceof ReplaceError)return StepResult.fail(e.message);throw e}}};function mapFragment(fragment,f,parent){let mapped=[];for(let i=0;i<fragment.childCount;i++){let child=fragment.child(i);child.content.size&&(child=child.copy(mapFragment(child.content,f,child))),child.isInline&&(child=f(child,parent,i)),mapped.push(child)}return Fragment.fromArray(mapped)}var AddMarkStep=class AddMarkStep extends Step{constructor(from,to,mark){super(),this.from=from,this.to=to,this.mark=mark}apply(doc){let oldSlice=doc.slice(this.from,this.to),$from=doc.resolve(this.from),parent=$from.node($from.sharedDepth(this.to)),slice=new Slice(mapFragment(oldSlice.content,(node,parent)=>!node.isAtom||!parent.type.allowsMarkType(this.mark.type)?node:node.mark(this.mark.addToSet(node.marks)),parent),oldSlice.openStart,oldSlice.openEnd);return StepResult.fromReplace(doc,this.from,this.to,slice)}invert(){return new RemoveMarkStep(this.from,this.to,this.mark)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1);return from.deleted&&to.deleted||from.pos>=to.pos?null:new AddMarkStep(from.pos,to.pos,this.mark)}merge(other){return other instanceof AddMarkStep&&other.mark.eq(this.mark)&&this.from<=other.to&&this.to>=other.from?new AddMarkStep(Math.min(this.from,other.from),Math.max(this.to,other.to),this.mark):null}toJSON(){return{stepType:`addMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for AddMarkStep.fromJSON`);return new AddMarkStep(json.from,json.to,schema.markFromJSON(json.mark))}};Step.jsonID(`addMark`,AddMarkStep);var RemoveMarkStep=class RemoveMarkStep extends Step{constructor(from,to,mark){super(),this.from=from,this.to=to,this.mark=mark}apply(doc){let oldSlice=doc.slice(this.from,this.to),slice=new Slice(mapFragment(oldSlice.content,node=>node.mark(this.mark.removeFromSet(node.marks)),doc),oldSlice.openStart,oldSlice.openEnd);return StepResult.fromReplace(doc,this.from,this.to,slice)}invert(){return new AddMarkStep(this.from,this.to,this.mark)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1);return from.deleted&&to.deleted||from.pos>=to.pos?null:new RemoveMarkStep(from.pos,to.pos,this.mark)}merge(other){return other instanceof RemoveMarkStep&&other.mark.eq(this.mark)&&this.from<=other.to&&this.to>=other.from?new RemoveMarkStep(Math.min(this.from,other.from),Math.max(this.to,other.to),this.mark):null}toJSON(){return{stepType:`removeMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for RemoveMarkStep.fromJSON`);return new RemoveMarkStep(json.from,json.to,schema.markFromJSON(json.mark))}};Step.jsonID(`removeMark`,RemoveMarkStep);var AddNodeMarkStep=class AddNodeMarkStep extends Step{constructor(pos,mark){super(),this.pos=pos,this.mark=mark}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at mark step's position`);let updated=node.type.create(node.attrs,null,this.mark.addToSet(node.marks));return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}invert(doc){let node=doc.nodeAt(this.pos);if(node){let newSet=this.mark.addToSet(node.marks);if(newSet.length==node.marks.length){for(let i=0;i<node.marks.length;i++)if(!node.marks[i].isInSet(newSet))return new AddNodeMarkStep(this.pos,node.marks[i]);return new AddNodeMarkStep(this.pos,this.mark)}}return new RemoveNodeMarkStep(this.pos,this.mark)}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new AddNodeMarkStep(pos.pos,this.mark)}toJSON(){return{stepType:`addNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(schema,json){if(typeof json.pos!=`number`)throw RangeError(`Invalid input for AddNodeMarkStep.fromJSON`);return new AddNodeMarkStep(json.pos,schema.markFromJSON(json.mark))}};Step.jsonID(`addNodeMark`,AddNodeMarkStep);var RemoveNodeMarkStep=class RemoveNodeMarkStep extends Step{constructor(pos,mark){super(),this.pos=pos,this.mark=mark}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at mark step's position`);let updated=node.type.create(node.attrs,null,this.mark.removeFromSet(node.marks));return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}invert(doc){let node=doc.nodeAt(this.pos);return!node||!this.mark.isInSet(node.marks)?this:new AddNodeMarkStep(this.pos,this.mark)}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new RemoveNodeMarkStep(pos.pos,this.mark)}toJSON(){return{stepType:`removeNodeMark`,pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(schema,json){if(typeof json.pos!=`number`)throw RangeError(`Invalid input for RemoveNodeMarkStep.fromJSON`);return new RemoveNodeMarkStep(json.pos,schema.markFromJSON(json.mark))}};Step.jsonID(`removeNodeMark`,RemoveNodeMarkStep);var ReplaceStep=class ReplaceStep extends Step{constructor(from,to,slice,structure=!1){super(),this.from=from,this.to=to,this.slice=slice,this.structure=structure}apply(doc){return this.structure&&contentBetween(doc,this.from,this.to)?StepResult.fail(`Structure replace would overwrite content`):StepResult.fromReplace(doc,this.from,this.to,this.slice)}getMap(){return new StepMap([this.from,this.to-this.from,this.slice.size])}invert(doc){return new ReplaceStep(this.from,this.from+this.slice.size,doc.slice(this.from,this.to))}map(mapping){let to=mapping.mapResult(this.to,-1),from=this.from==this.to&&ReplaceStep.MAP_BIAS<0?to:mapping.mapResult(this.from,1);return from.deletedAcross&&to.deletedAcross?null:new ReplaceStep(from.pos,Math.max(from.pos,to.pos),this.slice,this.structure)}merge(other){if(!(other instanceof ReplaceStep)||other.structure||this.structure)return null;if(this.from+this.slice.size==other.from&&!this.slice.openEnd&&!other.slice.openStart){let slice=this.slice.size+other.slice.size==0?Slice.empty:new Slice(this.slice.content.append(other.slice.content),this.slice.openStart,other.slice.openEnd);return new ReplaceStep(this.from,this.to+(other.to-other.from),slice,this.structure)}else if(other.to==this.from&&!this.slice.openStart&&!other.slice.openEnd){let slice=this.slice.size+other.slice.size==0?Slice.empty:new Slice(other.slice.content.append(this.slice.content),other.slice.openStart,this.slice.openEnd);return new ReplaceStep(other.from,this.to,slice,this.structure)}else return null}toJSON(){let json={stepType:`replace`,from:this.from,to:this.to};return this.slice.size&&(json.slice=this.slice.toJSON()),this.structure&&(json.structure=!0),json}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`)throw RangeError(`Invalid input for ReplaceStep.fromJSON`);return new ReplaceStep(json.from,json.to,Slice.fromJSON(schema,json.slice),!!json.structure)}};ReplaceStep.MAP_BIAS=1,Step.jsonID(`replace`,ReplaceStep);var ReplaceAroundStep=class ReplaceAroundStep extends Step{constructor(from,to,gapFrom,gapTo,slice,insert,structure=!1){super(),this.from=from,this.to=to,this.gapFrom=gapFrom,this.gapTo=gapTo,this.slice=slice,this.insert=insert,this.structure=structure}apply(doc){if(this.structure&&(contentBetween(doc,this.from,this.gapFrom)||contentBetween(doc,this.gapTo,this.to)))return StepResult.fail(`Structure gap-replace would overwrite content`);let gap=doc.slice(this.gapFrom,this.gapTo);if(gap.openStart||gap.openEnd)return StepResult.fail(`Gap is not a flat range`);let inserted=this.slice.insertAt(this.insert,gap.content);return inserted?StepResult.fromReplace(doc,this.from,this.to,inserted):StepResult.fail(`Content does not fit in gap`)}getMap(){return new StepMap([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(doc){let gap=this.gapTo-this.gapFrom;return new ReplaceAroundStep(this.from,this.from+this.slice.size+gap,this.from+this.insert,this.from+this.insert+gap,doc.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(mapping){let from=mapping.mapResult(this.from,1),to=mapping.mapResult(this.to,-1),gapFrom=this.from==this.gapFrom?from.pos:mapping.map(this.gapFrom,-1),gapTo=this.to==this.gapTo?to.pos:mapping.map(this.gapTo,1);return from.deletedAcross&&to.deletedAcross||gapFrom<from.pos||gapTo>to.pos?null:new ReplaceAroundStep(from.pos,to.pos,gapFrom,gapTo,this.slice,this.insert,this.structure)}toJSON(){let json={stepType:`replaceAround`,from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(json.slice=this.slice.toJSON()),this.structure&&(json.structure=!0),json}static fromJSON(schema,json){if(typeof json.from!=`number`||typeof json.to!=`number`||typeof json.gapFrom!=`number`||typeof json.gapTo!=`number`||typeof json.insert!=`number`)throw RangeError(`Invalid input for ReplaceAroundStep.fromJSON`);return new ReplaceAroundStep(json.from,json.to,json.gapFrom,json.gapTo,Slice.fromJSON(schema,json.slice),json.insert,!!json.structure)}};Step.jsonID(`replaceAround`,ReplaceAroundStep);function contentBetween(doc,from,to){let $from=doc.resolve(from),dist=to-from,depth=$from.depth;for(;dist>0&&depth>0&&$from.indexAfter(depth)==$from.node(depth).childCount;)depth--,dist--;if(dist>0){let next=$from.node(depth).maybeChild($from.indexAfter(depth));for(;dist>0;){if(!next||next.isLeaf)return!0;next=next.firstChild,dist--}}return!1}var AttrStep=class AttrStep extends Step{constructor(pos,attr,value){super(),this.pos=pos,this.attr=attr,this.value=value}apply(doc){let node=doc.nodeAt(this.pos);if(!node)return StepResult.fail(`No node at attribute step's position`);let attrs=Object.create(null);for(let name in node.attrs)attrs[name]=node.attrs[name];attrs[this.attr]=this.value;let updated=node.type.create(attrs,null,node.marks);return StepResult.fromReplace(doc,this.pos,this.pos+1,new Slice(Fragment.from(updated),0,+!node.isLeaf))}getMap(){return StepMap.empty}invert(doc){return new AttrStep(this.pos,this.attr,doc.nodeAt(this.pos).attrs[this.attr])}map(mapping){let pos=mapping.mapResult(this.pos,1);return pos.deletedAfter?null:new AttrStep(pos.pos,this.attr,this.value)}toJSON(){return{stepType:`attr`,pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(schema,json){if(typeof json.pos!=`number`||typeof json.attr!=`string`)throw RangeError(`Invalid input for AttrStep.fromJSON`);return new AttrStep(json.pos,json.attr,json.value)}};Step.jsonID(`attr`,AttrStep);var DocAttrStep=class DocAttrStep extends Step{constructor(attr,value){super(),this.attr=attr,this.value=value}apply(doc){let attrs=Object.create(null);for(let name in doc.attrs)attrs[name]=doc.attrs[name];attrs[this.attr]=this.value;let updated=doc.type.create(attrs,doc.content,doc.marks);return StepResult.ok(updated)}getMap(){return StepMap.empty}invert(doc){return new DocAttrStep(this.attr,doc.attrs[this.attr])}map(mapping){return this}toJSON(){return{stepType:`docAttr`,attr:this.attr,value:this.value}}static fromJSON(schema,json){if(typeof json.attr!=`string`)throw RangeError(`Invalid input for DocAttrStep.fromJSON`);return new DocAttrStep(json.attr,json.value)}};Step.jsonID(`docAttr`,DocAttrStep);var TransformError=class extends Error{};TransformError=function TransformError(message){let err=Error.call(this,message);return err.__proto__=TransformError.prototype,err},TransformError.prototype=Object.create(Error.prototype),TransformError.prototype.constructor=TransformError,TransformError.prototype.name=`TransformError`;var classesById=Object.create(null),Selection=class{constructor($anchor,$head,ranges){this.$anchor=$anchor,this.$head=$head,this.ranges=ranges||[new SelectionRange($anchor.min($head),$anchor.max($head))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let ranges=this.ranges;for(let i=0;i<ranges.length;i++)if(ranges[i].$from.pos!=ranges[i].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(tr,content=Slice.empty){let lastNode=content.content.lastChild,lastParent=null;for(let i=0;i<content.openEnd;i++)lastParent=lastNode,lastNode=lastNode.lastChild;let mapFrom=tr.steps.length,ranges=this.ranges;for(let i=0;i<ranges.length;i++){let{$from,$to}=ranges[i],mapping=tr.mapping.slice(mapFrom);tr.replaceRange(mapping.map($from.pos),mapping.map($to.pos),i?Slice.empty:content),i==0&&selectionToInsertionEnd(tr,mapFrom,(lastNode?lastNode.isInline:lastParent&&lastParent.isTextblock)?-1:1)}}replaceWith(tr,node){let mapFrom=tr.steps.length,ranges=this.ranges;for(let i=0;i<ranges.length;i++){let{$from,$to}=ranges[i],mapping=tr.mapping.slice(mapFrom),from=mapping.map($from.pos),to=mapping.map($to.pos);i?tr.deleteRange(from,to):(tr.replaceRangeWith(from,to,node),selectionToInsertionEnd(tr,mapFrom,node.isInline?-1:1))}}static findFrom($pos,dir,textOnly=!1){let inner=$pos.parent.inlineContent?new TextSelection($pos):findSelectionIn($pos.node(0),$pos.parent,$pos.pos,$pos.index(),dir,textOnly);if(inner)return inner;for(let depth=$pos.depth-1;depth>=0;depth--){let found=dir<0?findSelectionIn($pos.node(0),$pos.node(depth),$pos.before(depth+1),$pos.index(depth),dir,textOnly):findSelectionIn($pos.node(0),$pos.node(depth),$pos.after(depth+1),$pos.index(depth)+1,dir,textOnly);if(found)return found}return null}static near($pos,bias=1){return this.findFrom($pos,bias)||this.findFrom($pos,-bias)||new AllSelection($pos.node(0))}static atStart(doc){return findSelectionIn(doc,doc,0,0,1)||new AllSelection(doc)}static atEnd(doc){return findSelectionIn(doc,doc,doc.content.size,doc.childCount,-1)||new AllSelection(doc)}static fromJSON(doc,json){if(!json||!json.type)throw RangeError(`Invalid input for Selection.fromJSON`);let cls=classesById[json.type];if(!cls)throw RangeError(`No selection type ${json.type} defined`);return cls.fromJSON(doc,json)}static jsonID(id,selectionClass){if(id in classesById)throw RangeError(`Duplicate use of selection JSON ID `+id);return classesById[id]=selectionClass,selectionClass.prototype.jsonID=id,selectionClass}getBookmark(){return TextSelection.between(this.$anchor,this.$head).getBookmark()}};Selection.prototype.visible=!0;var SelectionRange=class{constructor($from,$to){this.$from=$from,this.$to=$to}},warnedAboutTextSelection=!1;function checkTextSelection($pos){!warnedAboutTextSelection&&!$pos.parent.inlineContent&&(warnedAboutTextSelection=!0,console.warn(`TextSelection endpoint not pointing into a node with inline content (`+$pos.parent.type.name+`)`))}var TextSelection=class TextSelection extends Selection{constructor($anchor,$head=$anchor){checkTextSelection($anchor),checkTextSelection($head),super($anchor,$head)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(doc,mapping){let $head=doc.resolve(mapping.map(this.head));if(!$head.parent.inlineContent)return Selection.near($head);let $anchor=doc.resolve(mapping.map(this.anchor));return new TextSelection($anchor.parent.inlineContent?$anchor:$head,$head)}replace(tr,content=Slice.empty){if(super.replace(tr,content),content==Slice.empty){let marks=this.$from.marksAcross(this.$to);marks&&tr.ensureMarks(marks)}}eq(other){return other instanceof TextSelection&&other.anchor==this.anchor&&other.head==this.head}getBookmark(){return new TextBookmark(this.anchor,this.head)}toJSON(){return{type:`text`,anchor:this.anchor,head:this.head}}static fromJSON(doc,json){if(typeof json.anchor!=`number`||typeof json.head!=`number`)throw RangeError(`Invalid input for TextSelection.fromJSON`);return new TextSelection(doc.resolve(json.anchor),doc.resolve(json.head))}static create(doc,anchor,head=anchor){let $anchor=doc.resolve(anchor);return new this($anchor,head==anchor?$anchor:doc.resolve(head))}static between($anchor,$head,bias){let dPos=$anchor.pos-$head.pos;if((!bias||dPos)&&(bias=dPos>=0?1:-1),!$head.parent.inlineContent){let found=Selection.findFrom($head,bias,!0)||Selection.findFrom($head,-bias,!0);if(found)$head=found.$head;else return Selection.near($head,bias)}return $anchor.parent.inlineContent||(dPos==0?$anchor=$head:($anchor=(Selection.findFrom($anchor,-bias,!0)||Selection.findFrom($anchor,bias,!0)).$anchor,$anchor.pos<$head.pos!=dPos<0&&($anchor=$head))),new TextSelection($anchor,$head)}};Selection.jsonID(`text`,TextSelection);var TextBookmark=class TextBookmark{constructor(anchor,head){this.anchor=anchor,this.head=head}map(mapping){return new TextBookmark(mapping.map(this.anchor),mapping.map(this.head))}resolve(doc){return TextSelection.between(doc.resolve(this.anchor),doc.resolve(this.head))}},NodeSelection=class NodeSelection extends Selection{constructor($pos){let node=$pos.nodeAfter,$end=$pos.node(0).resolve($pos.pos+node.nodeSize);super($pos,$end),this.node=node}map(doc,mapping){let{deleted,pos}=mapping.mapResult(this.anchor),$pos=doc.resolve(pos);return deleted?Selection.near($pos):new NodeSelection($pos)}content(){return new Slice(Fragment.from(this.node),0,0)}eq(other){return other instanceof NodeSelection&&other.anchor==this.anchor}toJSON(){return{type:`node`,anchor:this.anchor}}getBookmark(){return new NodeBookmark(this.anchor)}static fromJSON(doc,json){if(typeof json.anchor!=`number`)throw RangeError(`Invalid input for NodeSelection.fromJSON`);return new NodeSelection(doc.resolve(json.anchor))}static create(doc,from){return new NodeSelection(doc.resolve(from))}static isSelectable(node){return!node.isText&&node.type.spec.selectable!==!1}};NodeSelection.prototype.visible=!1,Selection.jsonID(`node`,NodeSelection);var NodeBookmark=class NodeBookmark{constructor(anchor){this.anchor=anchor}map(mapping){let{deleted,pos}=mapping.mapResult(this.anchor);return deleted?new TextBookmark(pos,pos):new NodeBookmark(pos)}resolve(doc){let $pos=doc.resolve(this.anchor),node=$pos.nodeAfter;return node&&NodeSelection.isSelectable(node)?new NodeSelection($pos):Selection.near($pos)}},AllSelection=class AllSelection extends Selection{constructor(doc){super(doc.resolve(0),doc.resolve(doc.content.size))}replace(tr,content=Slice.empty){if(content==Slice.empty){tr.delete(0,tr.doc.content.size);let sel=Selection.atStart(tr.doc);sel.eq(tr.selection)||tr.setSelection(sel)}else super.replace(tr,content)}toJSON(){return{type:`all`}}static fromJSON(doc){return new AllSelection(doc)}map(doc){return new AllSelection(doc)}eq(other){return other instanceof AllSelection}getBookmark(){return AllBookmark}};Selection.jsonID(`all`,AllSelection);var AllBookmark={map(){return this},resolve(doc){return new AllSelection(doc)}};function findSelectionIn(doc,node,pos,index,dir,text=!1){if(node.inlineContent)return TextSelection.create(doc,pos);for(let i=index-(dir>0?0:1);dir>0?i<node.childCount:i>=0;i+=dir){let child=node.child(i);if(!child.isAtom){let inner=findSelectionIn(doc,child,pos+dir,dir<0?child.childCount:0,dir,text);if(inner)return inner}else if(!text&&NodeSelection.isSelectable(child))return NodeSelection.create(doc,pos-(dir<0?child.nodeSize:0));pos+=child.nodeSize*dir}return null}function selectionToInsertionEnd(tr,startLen,bias){let last=tr.steps.length-1;if(last<startLen)return;let step=tr.steps[last];if(!(step instanceof ReplaceStep||step instanceof ReplaceAroundStep))return;let map=tr.mapping.maps[last],end;map.forEach((_from,_to,_newFrom,newTo)=>{end??=newTo}),tr.setSelection(Selection.near(tr.doc.resolve(end),bias))}function bind(f,self){return!self||!f?f:f.bind(self)}var FieldDesc=class{constructor(name,desc,self){this.name=name,this.init=bind(desc.init,self),this.apply=bind(desc.apply,self)}};new FieldDesc(`doc`,{init(config){return config.doc||config.schema.topNodeType.createAndFill()},apply(tr){return tr.doc}}),new FieldDesc(`selection`,{init(config,instance){return config.selection||Selection.atStart(instance.doc)},apply(tr){return tr.selection}}),new FieldDesc(`storedMarks`,{init(config){return config.storedMarks||null},apply(tr,_marks,_old,state){return state.selection.$cursor?tr.storedMarks:null}}),new FieldDesc(`scrollToSelection`,{init(){return 0},apply(tr,prev){return tr.scrolledIntoView?prev+1:prev}});function bindProps(obj,self,target){for(let prop in obj){let val=obj[prop];val instanceof Function?val=val.bind(self):prop==`handleDOMEvents`&&(val=bindProps(val,self,{})),target[prop]=val}return target}var Plugin=class{constructor(spec){this.spec=spec,this.props={},spec.props&&bindProps(spec.props,this,this.props),this.key=spec.key?spec.key.key:createKey(`plugin`)}getState(state){return state[this.key]}},keys=Object.create(null);function createKey(name){return name in keys?name+`$`+ ++keys[name]:(keys[name]=0,name+`$`)}var PluginKey=class{constructor(name=`key`){this.key=createKey(name)}get(state){return state.config.pluginsByKey[this.key]}getState(state){return state[this.key]}};export{Selection as a,Fragment as c,PluginKey as i,Slice as l,NodeSelection as n,SelectionRange as o,Plugin as r,TextSelection as s,AllSelection as t};
@@ -0,0 +1 @@
1
+ import{THREADED_ANNOTATIONS_PORTAL}from"../esm/lib/v2/constants.js";import{a as Selection,c as Fragment$1,i as PluginKey,l as Slice,n as NodeSelection,o as SelectionRange,r as Plugin,s as TextSelection}from"./dist.js";import messages from"../esm/lib/components/v2/message-editor/messages.js";import{Toolbar}from"@box/blueprint-web";import React,{memo,useCallback,useEffect,useLayoutEffect,useRef,useState}from"react";import{useIntl}from"react-intl";import{jsx,jsxs}from"react/jsx-runtime";import{Bold,BulletList,Italic,NumberList,Underline}from"@box/blueprint-web-assets/icons/Medium";import{useCurrentEditor,useEditorState}from"@tiptap/react";import{Extension,getText,getTextSerializersFromSchema,isTextSelection,posToDOMRect}from"@tiptap/core";import{arrow,autoPlacement,computePosition,flip,hide,inline,offset,shift,size}from"@floating-ui/dom";import{createPortal}from"react-dom";import '../styles/message-editor-bubble-menu.css';for(var base={8:`Backspace`,9:`Tab`,10:`Enter`,12:`NumLock`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,44:`PrintScreen`,45:`Insert`,46:`Delete`,59:`;`,61:`=`,91:`Meta`,92:`Meta`,106:`*`,107:`+`,108:`,`,109:`-`,110:`.`,111:`/`,144:`NumLock`,145:`ScrollLock`,160:`Shift`,161:`Shift`,162:`Control`,163:`Control`,164:`Alt`,165:`Alt`,173:`-`,186:`;`,187:`=`,188:`,`,189:`-`,190:`.`,191:`/`,192:"`",219:`[`,220:`\\`,221:`]`,222:`'`},shift$1={48:`)`,49:`!`,50:`@`,51:`#`,52:`$`,53:`%`,54:`^`,55:`&`,56:`*`,57:`(`,59:`:`,61:`+`,173:`_`,186:`:`,187:`+`,188:`<`,189:`_`,190:`>`,191:`?`,192:`~`,219:`{`,220:`|`,221:`}`,222:`"`},mac$1=typeof navigator<`u`&&/Mac/.test(navigator.platform),ie=typeof navigator<`u`&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),i=0;i<10;i++)base[48+i]=base[96+i]=String(i);for(var i=1;i<=24;i++)base[i+111]=`F`+i;for(var i=65;i<=90;i++)base[i]=String.fromCharCode(i+32),shift$1[i]=String.fromCharCode(i);for(var code in base)shift$1.hasOwnProperty(code)||(shift$1[code]=base[code]);function keyName(event){var name=!(mac$1&&event.metaKey&&event.shiftKey&&!event.ctrlKey&&!event.altKey||ie&&event.shiftKey&&event.key&&event.key.length==1||event.key==`Unidentified`)&&event.key||(event.shiftKey?shift$1:base)[event.keyCode]||event.key||`Unidentified`;return name==`Esc`&&(name=`Escape`),name==`Del`&&(name=`Delete`),name==`Left`&&(name=`ArrowLeft`),name==`Up`&&(name=`ArrowUp`),name==`Right`&&(name=`ArrowRight`),name==`Down`&&(name=`ArrowDown`),name}var mac=typeof navigator<`u`&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),windows=typeof navigator<`u`&&/Win/.test(navigator.platform);function normalizeKeyName(name){let parts=name.split(/-(?!$)/),result=parts[parts.length-1];result==`Space`&&(result=` `);let alt,ctrl,shift,meta;for(let i=0;i<parts.length-1;i++){let mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))meta=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else if(/^s(hift)?$/i.test(mod))shift=!0;else if(/^mod$/i.test(mod))mac?meta=!0:ctrl=!0;else throw Error(`Unrecognized modifier name: `+mod)}return alt&&(result=`Alt-`+result),ctrl&&(result=`Ctrl-`+result),meta&&(result=`Meta-`+result),shift&&(result=`Shift-`+result),result}function normalize(map){let copy=Object.create(null);for(let prop in map)copy[normalizeKeyName(prop)]=map[prop];return copy}function modifiers(name,event,shift=!0){return event.altKey&&(name=`Alt-`+name),event.ctrlKey&&(name=`Ctrl-`+name),event.metaKey&&(name=`Meta-`+name),shift&&event.shiftKey&&(name=`Shift-`+name),name}function keydownHandler(bindings){let map=normalize(bindings);return function(view,event){let name=keyName(event),baseName,direct=map[modifiers(name,event)];if(direct&&direct(view.state,view.dispatch,view))return!0;if(name.length==1&&name!=` `){if(event.shiftKey){let noShift=map[modifiers(name,event,!1)];if(noShift&&noShift(view.state,view.dispatch,view))return!0}if((event.altKey||event.metaKey||event.ctrlKey)&&!(windows&&event.ctrlKey&&event.altKey)&&(baseName=base[event.keyCode])&&baseName!=name){let fromCode=map[modifiers(baseName,event)];if(fromCode&&fromCode(view.state,view.dispatch,view))return!0}}return!1}}var readFromCache,addToCache;if(typeof WeakMap<`u`){let cache=new WeakMap;readFromCache=key=>cache.get(key),addToCache=(key,value)=>(cache.set(key,value),value)}else{let cache=[],cachePos=0;readFromCache=key=>{for(let i=0;i<cache.length;i+=2)if(cache[i]==key)return cache[i+1]},addToCache=(key,value)=>(cachePos==10&&(cachePos=0),cache[cachePos++]=key,cache[cachePos++]=value)}var TableMap=class{constructor(width,height,map,problems){this.width=width,this.height=height,this.map=map,this.problems=problems}findCell(pos){for(let i=0;i<this.map.length;i++){let curPos=this.map[i];if(curPos!=pos)continue;let left=i%this.width,top=i/this.width|0,right=left+1,bottom=top+1;for(let j=1;right<this.width&&this.map[i+j]==curPos;j++)right++;for(let j=1;bottom<this.height&&this.map[i+this.width*j]==curPos;j++)bottom++;return{left,top,right,bottom}}throw RangeError(`No cell with offset ${pos} found`)}colCount(pos){for(let i=0;i<this.map.length;i++)if(this.map[i]==pos)return i%this.width;throw RangeError(`No cell with offset ${pos} found`)}nextCell(pos,axis,dir){let{left,right,top,bottom}=this.findCell(pos);return axis==`horiz`?(dir<0?left==0:right==this.width)?null:this.map[top*this.width+(dir<0?left-1:right)]:(dir<0?top==0:bottom==this.height)?null:this.map[left+this.width*(dir<0?top-1:bottom)]}rectBetween(a,b){let{left:leftA,right:rightA,top:topA,bottom:bottomA}=this.findCell(a),{left:leftB,right:rightB,top:topB,bottom:bottomB}=this.findCell(b);return{left:Math.min(leftA,leftB),top:Math.min(topA,topB),right:Math.max(rightA,rightB),bottom:Math.max(bottomA,bottomB)}}cellsInRect(rect){let result=[],seen={};for(let row=rect.top;row<rect.bottom;row++)for(let col=rect.left;col<rect.right;col++){let index=row*this.width+col,pos=this.map[index];seen[pos]||(seen[pos]=!0,!(col==rect.left&&col&&this.map[index-1]==pos||row==rect.top&&row&&this.map[index-this.width]==pos)&&result.push(pos))}return result}positionAt(row,col,table){for(let i=0,rowStart=0;;i++){let rowEnd=rowStart+table.child(i).nodeSize;if(i==row){let index=col+row*this.width,rowEndIndex=(row+1)*this.width;for(;index<rowEndIndex&&this.map[index]<rowStart;)index++;return index==rowEndIndex?rowEnd-1:this.map[index]}rowStart=rowEnd}}static get(table){return readFromCache(table)||addToCache(table,computeMap(table))}};function computeMap(table){if(table.type.spec.tableRole!=`table`)throw RangeError(`Not a table node: `+table.type.name);let width=findWidth(table),height=table.childCount,map=[],mapPos=0,problems=null,colWidths=[];for(let i=0,e=width*height;i<e;i++)map[i]=0;for(let row=0,pos=0;row<height;row++){let rowNode=table.child(row);pos++;for(let i=0;;i++){for(;mapPos<map.length&&map[mapPos]!=0;)mapPos++;if(i==rowNode.childCount)break;let cellNode=rowNode.child(i),{colspan,rowspan,colwidth}=cellNode.attrs;for(let h=0;h<rowspan;h++){if(h+row>=height){(problems||=[]).push({type:`overlong_rowspan`,pos,n:rowspan-h});break}let start=mapPos+h*width;for(let w=0;w<colspan;w++){map[start+w]==0?map[start+w]=pos:(problems||=[]).push({type:`collision`,row,pos,n:colspan-w});let colW=colwidth&&colwidth[w];if(colW){let widthIndex=(start+w)%width*2,prev=colWidths[widthIndex];prev==null||prev!=colW&&colWidths[widthIndex+1]==1?(colWidths[widthIndex]=colW,colWidths[widthIndex+1]=1):prev==colW&&colWidths[widthIndex+1]++}}}mapPos+=colspan,pos+=cellNode.nodeSize}let expectedPos=(row+1)*width,missing=0;for(;mapPos<expectedPos;)map[mapPos++]==0&&missing++;missing&&(problems||=[]).push({type:`missing`,row,n:missing}),pos++}(width===0||height===0)&&(problems||=[]).push({type:`zero_sized`});let tableMap=new TableMap(width,height,map,problems),badWidths=!1;for(let i=0;!badWidths&&i<colWidths.length;i+=2)colWidths[i]!=null&&colWidths[i+1]<height&&(badWidths=!0);return badWidths&&findBadColWidths(tableMap,colWidths,table),tableMap}function findWidth(table){let width=-1,hasRowSpan=!1;for(let row=0;row<table.childCount;row++){let rowNode=table.child(row),rowWidth=0;if(hasRowSpan)for(let j=0;j<row;j++){let prevRow=table.child(j);for(let i=0;i<prevRow.childCount;i++){let cell=prevRow.child(i);j+cell.attrs.rowspan>row&&(rowWidth+=cell.attrs.colspan)}}for(let i=0;i<rowNode.childCount;i++){let cell=rowNode.child(i);rowWidth+=cell.attrs.colspan,cell.attrs.rowspan>1&&(hasRowSpan=!0)}width==-1?width=rowWidth:width!=rowWidth&&(width=Math.max(width,rowWidth))}return width}function findBadColWidths(map,colWidths,table){map.problems||=[];let seen={};for(let i=0;i<map.map.length;i++){let pos=map.map[i];if(seen[pos])continue;seen[pos]=!0;let node=table.nodeAt(pos);if(!node)throw RangeError(`No cell with offset ${pos} found`);let updated=null,attrs=node.attrs;for(let j=0;j<attrs.colspan;j++){let colWidth=colWidths[(i+j)%map.width*2];colWidth!=null&&(!attrs.colwidth||attrs.colwidth[j]!=colWidth)&&((updated||=freshColWidth(attrs))[j]=colWidth)}updated&&map.problems.unshift({type:`colwidth mismatch`,pos,colwidth:updated})}}function freshColWidth(attrs){if(attrs.colwidth)return attrs.colwidth.slice();let result=[];for(let i=0;i<attrs.colspan;i++)result.push(0);return result}function tableNodeTypes(schema){let result=schema.cached.tableNodeTypes;if(!result){result=schema.cached.tableNodeTypes={};for(let name in schema.nodes){let type=schema.nodes[name],role=type.spec.tableRole;role&&(result[role]=type)}}return result}new PluginKey(`selectingCells`);function cellAround($pos){for(let d=$pos.depth-1;d>0;d--)if($pos.node(d).type.spec.tableRole==`row`)return $pos.node(0).resolve($pos.before(d+1));return null}function isInTable(state){let $head=state.selection.$head;for(let d=$head.depth;d>0;d--)if($head.node(d).type.spec.tableRole==`row`)return!0;return!1}function selectionCell(state){let sel=state.selection;if(`$anchorCell`in sel&&sel.$anchorCell)return sel.$anchorCell.pos>sel.$headCell.pos?sel.$anchorCell:sel.$headCell;if(`node`in sel&&sel.node&&sel.node.type.spec.tableRole==`cell`)return sel.$anchor;let $cell=cellAround(sel.$head)||cellNear(sel.$head);if($cell)return $cell;throw RangeError(`No cell found around position ${sel.head}`)}function cellNear($pos){for(let after=$pos.nodeAfter,pos=$pos.pos;after;after=after.firstChild,pos++){let role=after.type.spec.tableRole;if(role==`cell`||role==`header_cell`)return $pos.doc.resolve(pos)}for(let before=$pos.nodeBefore,pos=$pos.pos;before;before=before.lastChild,pos--){let role=before.type.spec.tableRole;if(role==`cell`||role==`header_cell`)return $pos.doc.resolve(pos-before.nodeSize)}}function pointsAtCell($pos){return $pos.parent.type.spec.tableRole==`row`&&!!$pos.nodeAfter}function inSameTable($cellA,$cellB){return $cellA.depth==$cellB.depth&&$cellA.pos>=$cellB.start(-1)&&$cellA.pos<=$cellB.end(-1)}function nextCell($pos,axis,dir){let table=$pos.node(-1),map=TableMap.get(table),tableStart=$pos.start(-1),moved=map.nextCell($pos.pos-tableStart,axis,dir);return moved==null?null:$pos.node(0).resolve(tableStart+moved)}function removeColSpan(attrs,pos,n=1){let result={...attrs,colspan:attrs.colspan-n};return result.colwidth&&(result.colwidth=result.colwidth.slice(),result.colwidth.splice(pos,n),result.colwidth.some(w=>w>0)||(result.colwidth=null)),result}var CellSelection=class CellSelection extends Selection{constructor($anchorCell,$headCell=$anchorCell){let table=$anchorCell.node(-1),map=TableMap.get(table),tableStart=$anchorCell.start(-1),rect=map.rectBetween($anchorCell.pos-tableStart,$headCell.pos-tableStart),doc=$anchorCell.node(0),cells=map.cellsInRect(rect).filter(p=>p!=$headCell.pos-tableStart);cells.unshift($headCell.pos-tableStart);let ranges=cells.map(pos=>{let cell=table.nodeAt(pos);if(!cell)throw RangeError(`No cell with offset ${pos} found`);let from=tableStart+pos+1;return new SelectionRange(doc.resolve(from),doc.resolve(from+cell.content.size))});super(ranges[0].$from,ranges[0].$to,ranges),this.$anchorCell=$anchorCell,this.$headCell=$headCell}map(doc,mapping){let $anchorCell=doc.resolve(mapping.map(this.$anchorCell.pos)),$headCell=doc.resolve(mapping.map(this.$headCell.pos));if(pointsAtCell($anchorCell)&&pointsAtCell($headCell)&&inSameTable($anchorCell,$headCell)){let tableChanged=this.$anchorCell.node(-1)!=$anchorCell.node(-1);return tableChanged&&this.isRowSelection()?CellSelection.rowSelection($anchorCell,$headCell):tableChanged&&this.isColSelection()?CellSelection.colSelection($anchorCell,$headCell):new CellSelection($anchorCell,$headCell)}return TextSelection.between($anchorCell,$headCell)}content(){let table=this.$anchorCell.node(-1),map=TableMap.get(table),tableStart=this.$anchorCell.start(-1),rect=map.rectBetween(this.$anchorCell.pos-tableStart,this.$headCell.pos-tableStart),seen={},rows=[];for(let row=rect.top;row<rect.bottom;row++){let rowContent=[];for(let index=row*map.width+rect.left,col=rect.left;col<rect.right;col++,index++){let pos=map.map[index];if(seen[pos])continue;seen[pos]=!0;let cellRect=map.findCell(pos),cell=table.nodeAt(pos);if(!cell)throw RangeError(`No cell with offset ${pos} found`);let extraLeft=rect.left-cellRect.left,extraRight=cellRect.right-rect.right;if(extraLeft>0||extraRight>0){let attrs=cell.attrs;if(extraLeft>0&&(attrs=removeColSpan(attrs,0,extraLeft)),extraRight>0&&(attrs=removeColSpan(attrs,attrs.colspan-extraRight,extraRight)),cellRect.left<rect.left){if(cell=cell.type.createAndFill(attrs),!cell)throw RangeError(`Could not create cell with attrs ${JSON.stringify(attrs)}`)}else cell=cell.type.create(attrs,cell.content)}if(cellRect.top<rect.top||cellRect.bottom>rect.bottom){let attrs={...cell.attrs,rowspan:Math.min(cellRect.bottom,rect.bottom)-Math.max(cellRect.top,rect.top)};cell=cellRect.top<rect.top?cell.type.createAndFill(attrs):cell.type.create(attrs,cell.content)}rowContent.push(cell)}rows.push(table.child(row).copy(Fragment$1.from(rowContent)))}let fragment=this.isColSelection()&&this.isRowSelection()?table:rows;return new Slice(Fragment$1.from(fragment),1,1)}replace(tr,content=Slice.empty){let mapFrom=tr.steps.length,ranges=this.ranges;for(let i=0;i<ranges.length;i++){let{$from,$to}=ranges[i],mapping=tr.mapping.slice(mapFrom);tr.replace(mapping.map($from.pos),mapping.map($to.pos),i?Slice.empty:content)}let sel=Selection.findFrom(tr.doc.resolve(tr.mapping.slice(mapFrom).map(this.to)),-1);sel&&tr.setSelection(sel)}replaceWith(tr,node){this.replace(tr,new Slice(Fragment$1.from(node),0,0))}forEachCell(f){let table=this.$anchorCell.node(-1),map=TableMap.get(table),tableStart=this.$anchorCell.start(-1),cells=map.cellsInRect(map.rectBetween(this.$anchorCell.pos-tableStart,this.$headCell.pos-tableStart));for(let i=0;i<cells.length;i++)f(table.nodeAt(cells[i]),tableStart+cells[i])}isColSelection(){let anchorTop=this.$anchorCell.index(-1),headTop=this.$headCell.index(-1);if(Math.min(anchorTop,headTop)>0)return!1;let anchorBottom=anchorTop+this.$anchorCell.nodeAfter.attrs.rowspan,headBottom=headTop+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(anchorBottom,headBottom)==this.$headCell.node(-1).childCount}static colSelection($anchorCell,$headCell=$anchorCell){let table=$anchorCell.node(-1),map=TableMap.get(table),tableStart=$anchorCell.start(-1),anchorRect=map.findCell($anchorCell.pos-tableStart),headRect=map.findCell($headCell.pos-tableStart),doc=$anchorCell.node(0);return anchorRect.top<=headRect.top?(anchorRect.top>0&&($anchorCell=doc.resolve(tableStart+map.map[anchorRect.left])),headRect.bottom<map.height&&($headCell=doc.resolve(tableStart+map.map[map.width*(map.height-1)+headRect.right-1]))):(headRect.top>0&&($headCell=doc.resolve(tableStart+map.map[headRect.left])),anchorRect.bottom<map.height&&($anchorCell=doc.resolve(tableStart+map.map[map.width*(map.height-1)+anchorRect.right-1]))),new CellSelection($anchorCell,$headCell)}isRowSelection(){let table=this.$anchorCell.node(-1),map=TableMap.get(table),tableStart=this.$anchorCell.start(-1),anchorLeft=map.colCount(this.$anchorCell.pos-tableStart),headLeft=map.colCount(this.$headCell.pos-tableStart);if(Math.min(anchorLeft,headLeft)>0)return!1;let anchorRight=anchorLeft+this.$anchorCell.nodeAfter.attrs.colspan,headRight=headLeft+this.$headCell.nodeAfter.attrs.colspan;return Math.max(anchorRight,headRight)==map.width}eq(other){return other instanceof CellSelection&&other.$anchorCell.pos==this.$anchorCell.pos&&other.$headCell.pos==this.$headCell.pos}static rowSelection($anchorCell,$headCell=$anchorCell){let table=$anchorCell.node(-1),map=TableMap.get(table),tableStart=$anchorCell.start(-1),anchorRect=map.findCell($anchorCell.pos-tableStart),headRect=map.findCell($headCell.pos-tableStart),doc=$anchorCell.node(0);return anchorRect.left<=headRect.left?(anchorRect.left>0&&($anchorCell=doc.resolve(tableStart+map.map[anchorRect.top*map.width])),headRect.right<map.width&&($headCell=doc.resolve(tableStart+map.map[map.width*(headRect.top+1)-1]))):(headRect.left>0&&($headCell=doc.resolve(tableStart+map.map[headRect.top*map.width])),anchorRect.right<map.width&&($anchorCell=doc.resolve(tableStart+map.map[map.width*(anchorRect.top+1)-1]))),new CellSelection($anchorCell,$headCell)}toJSON(){return{type:`cell`,anchor:this.$anchorCell.pos,head:this.$headCell.pos}}static fromJSON(doc,json){return new CellSelection(doc.resolve(json.anchor),doc.resolve(json.head))}static create(doc,anchorCell,headCell=anchorCell){return new CellSelection(doc.resolve(anchorCell),doc.resolve(headCell))}getBookmark(){return new CellBookmark(this.$anchorCell.pos,this.$headCell.pos)}};CellSelection.prototype.visible=!1,Selection.jsonID(`cell`,CellSelection);var CellBookmark=class CellBookmark{constructor(anchor,head){this.anchor=anchor,this.head=head}map(mapping){return new CellBookmark(mapping.map(this.anchor),mapping.map(this.head))}resolve(doc){let $anchorCell=doc.resolve(this.anchor),$headCell=doc.resolve(this.head);return $anchorCell.parent.type.spec.tableRole==`row`&&$headCell.parent.type.spec.tableRole==`row`&&$anchorCell.index()<$anchorCell.parent.childCount&&$headCell.index()<$headCell.parent.childCount&&inSameTable($anchorCell,$headCell)?new CellSelection($anchorCell,$headCell):Selection.near($headCell,1)}};new PluginKey(`fix-tables`);function selectedRect(state){let sel=state.selection,$pos=selectionCell(state),table=$pos.node(-1),tableStart=$pos.start(-1),map=TableMap.get(table);return{...sel instanceof CellSelection?map.rectBetween(sel.$anchorCell.pos-tableStart,sel.$headCell.pos-tableStart):map.findCell($pos.pos-tableStart),tableStart,map,table}}function deprecated_toggleHeader(type){return function(state,dispatch){if(!isInTable(state))return!1;if(dispatch){let types=tableNodeTypes(state.schema),rect=selectedRect(state),tr=state.tr,cells=rect.map.cellsInRect(type==`column`?{left:rect.left,top:0,right:rect.right,bottom:rect.map.height}:type==`row`?{left:0,top:rect.top,right:rect.map.width,bottom:rect.bottom}:rect),nodes=cells.map(pos=>rect.table.nodeAt(pos));for(let i=0;i<cells.length;i++)nodes[i].type==types.header_cell&&tr.setNodeMarkup(rect.tableStart+cells[i],types.cell,nodes[i].attrs);if(tr.steps.length===0)for(let i=0;i<cells.length;i++)tr.setNodeMarkup(rect.tableStart+cells[i],types.header_cell,nodes[i].attrs);dispatch(tr)}return!0}}function isHeaderEnabledByType(type,rect,types){let cellPositions=rect.map.cellsInRect({left:0,top:0,right:type==`row`?rect.map.width:1,bottom:type==`column`?rect.map.height:1});for(let i=0;i<cellPositions.length;i++){let cell=rect.table.nodeAt(cellPositions[i]);if(cell&&cell.type!==types.header_cell)return!1}return!0}function toggleHeader(type,options){return options||={useDeprecatedLogic:!1},options.useDeprecatedLogic?deprecated_toggleHeader(type):function(state,dispatch){if(!isInTable(state))return!1;if(dispatch){let types=tableNodeTypes(state.schema),rect=selectedRect(state),tr=state.tr,isHeaderRowEnabled=isHeaderEnabledByType(`row`,rect,types),isHeaderColumnEnabled=isHeaderEnabledByType(`column`,rect,types),selectionStartsAt=(type===`column`?isHeaderRowEnabled:type===`row`&&isHeaderColumnEnabled)?1:0,cellsRect=type==`column`?{left:0,top:selectionStartsAt,right:1,bottom:rect.map.height}:type==`row`?{left:selectionStartsAt,top:0,right:rect.map.width,bottom:1}:rect,newType=type==`column`?isHeaderColumnEnabled?types.cell:types.header_cell:type==`row`?isHeaderRowEnabled?types.cell:types.header_cell:types.cell;rect.map.cellsInRect(cellsRect).forEach(relativeCellPos=>{let cellPos=relativeCellPos+rect.tableStart,cell=tr.doc.nodeAt(cellPos);cell&&tr.setNodeMarkup(cellPos,newType,cell.attrs)}),dispatch(tr)}return!0}}toggleHeader(`row`,{useDeprecatedLogic:!0}),toggleHeader(`column`,{useDeprecatedLogic:!0}),toggleHeader(`cell`,{useDeprecatedLogic:!0});function deleteCellSelection(state,dispatch){let sel=state.selection;if(!(sel instanceof CellSelection))return!1;if(dispatch){let tr=state.tr,baseContent=tableNodeTypes(state.schema).cell.createAndFill().content;sel.forEachCell((cell,pos)=>{cell.content.eq(baseContent)||tr.replace(tr.mapping.map(pos+1),tr.mapping.map(pos+cell.nodeSize-1),new Slice(baseContent,0,0))}),tr.docChanged&&dispatch(tr)}return!0}keydownHandler({ArrowLeft:arrow$1(`horiz`,-1),ArrowRight:arrow$1(`horiz`,1),ArrowUp:arrow$1(`vert`,-1),ArrowDown:arrow$1(`vert`,1),"Shift-ArrowLeft":shiftArrow(`horiz`,-1),"Shift-ArrowRight":shiftArrow(`horiz`,1),"Shift-ArrowUp":shiftArrow(`vert`,-1),"Shift-ArrowDown":shiftArrow(`vert`,1),Backspace:deleteCellSelection,"Mod-Backspace":deleteCellSelection,Delete:deleteCellSelection,"Mod-Delete":deleteCellSelection});function maybeSetSelection(state,dispatch,selection){return selection.eq(state.selection)?!1:(dispatch&&dispatch(state.tr.setSelection(selection).scrollIntoView()),!0)}function arrow$1(axis,dir){return(state,dispatch,view)=>{if(!view)return!1;let sel=state.selection;if(sel instanceof CellSelection)return maybeSetSelection(state,dispatch,Selection.near(sel.$headCell,dir));if(axis!=`horiz`&&!sel.empty)return!1;let end=atEndOfCell(view,axis,dir);if(end==null)return!1;if(axis==`horiz`)return maybeSetSelection(state,dispatch,Selection.near(state.doc.resolve(sel.head+dir),dir));{let $cell=state.doc.resolve(end),$next=nextCell($cell,axis,dir),newSel;return newSel=$next?Selection.near($next,1):dir<0?Selection.near(state.doc.resolve($cell.before(-1)),-1):Selection.near(state.doc.resolve($cell.after(-1)),1),maybeSetSelection(state,dispatch,newSel)}}}function shiftArrow(axis,dir){return(state,dispatch,view)=>{if(!view)return!1;let sel=state.selection,cellSel;if(sel instanceof CellSelection)cellSel=sel;else{let end=atEndOfCell(view,axis,dir);if(end==null)return!1;cellSel=new CellSelection(state.doc.resolve(end))}let $head=nextCell(cellSel.$headCell,axis,dir);return $head?maybeSetSelection(state,dispatch,new CellSelection(cellSel.$anchorCell,$head)):!1}}function atEndOfCell(view,axis,dir){if(!(view.state.selection instanceof TextSelection))return null;let{$head}=view.state.selection;for(let d=$head.depth-1;d>=0;d--){let parent=$head.node(d);if((dir<0?$head.index(d):$head.indexAfter(d))!=(dir<0?0:parent.childCount))return null;if(parent.type.spec.tableRole==`cell`||parent.type.spec.tableRole==`header_cell`){let cellPos=$head.before(d),dirStr=axis==`vert`?dir>0?`down`:`up`:dir>0?`right`:`left`;return view.endOfTextblock(dirStr)?cellPos:null}}return null}new PluginKey(`tableColumnResizing`);function combineDOMRects(rect1,rect2){let top=Math.min(rect1.top,rect2.top),bottom=Math.max(rect1.bottom,rect2.bottom),left=Math.min(rect1.left,rect2.left),width=Math.max(rect1.right,rect2.right)-left,height=bottom-top;return new DOMRect(left,top,width,height)}var BubbleMenuView=class{constructor({editor,element,view,pluginKey=`bubbleMenu`,updateDelay=250,resizeDelay=60,shouldShow,appendTo,getReferencedVirtualElement,options}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.floatingUIOptions={strategy:`absolute`,placement:`top`,offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1,onShow:void 0,onHide:void 0,onUpdate:void 0,onDestroy:void 0},this.shouldShow=({view,state,from,to})=>{let{doc,selection}=state,{empty}=selection,isEmptyTextBlock=!doc.textBetween(from,to).length&&isTextSelection(state.selection),isChildOfMenu=this.element.contains(document.activeElement);return!(!(view.hasFocus()||isChildOfMenu)||empty||isEmptyTextBlock||!this.editor.isEditable)},this.mousedownHandler=()=>{this.preventHide=!0},this.dragstartHandler=()=>{this.hide()},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event})=>{if(this.editor.isDestroyed){this.destroy();return}if(this.preventHide){this.preventHide=!1;return}event?.relatedTarget&&this.element.parentNode?.contains(event.relatedTarget)||event?.relatedTarget!==this.editor.view.dom&&this.hide()},this.handleDebouncedUpdate=(view,oldState)=>{let selectionChanged=!oldState?.selection.eq(view.state.selection),docChanged=!oldState?.doc.eq(view.state.doc);!selectionChanged&&!docChanged||(this.updateDebounceTimer&&clearTimeout(this.updateDebounceTimer),this.updateDebounceTimer=window.setTimeout(()=>{this.updateHandler(view,selectionChanged,docChanged,oldState)},this.updateDelay))},this.updateHandler=(view,selectionChanged,docChanged,oldState)=>{let{composing}=view;if(!(composing||!selectionChanged&&!docChanged)){if(!this.getShouldShow(oldState)){this.hide();return}this.show(),this.updatePosition()}},this.transactionHandler=({transaction:tr})=>{let meta=tr.getMeta(this.pluginKey);meta===`updatePosition`?this.updatePosition():meta&&typeof meta==`object`&&meta.type===`updateOptions`?this.updateOptions(meta.options):meta===`hide`?this.hide():meta===`show`&&(this.updatePosition(),this.show())},this.editor=editor,this.element=element,this.view=view,this.pluginKey=pluginKey,this.updateDelay=updateDelay,this.resizeDelay=resizeDelay,this.appendTo=appendTo,this.scrollTarget=options?.scrollTarget??window,this.getReferencedVirtualElement=getReferencedVirtualElement,this.floatingUIOptions={...this.floatingUIOptions,...options},this.element.tabIndex=0,shouldShow&&(this.shouldShow=shouldShow),this.element.addEventListener(`mousedown`,this.mousedownHandler,{capture:!0}),this.view.dom.addEventListener(`dragstart`,this.dragstartHandler),this.editor.on(`focus`,this.focusHandler),this.editor.on(`blur`,this.blurHandler),this.editor.on(`transaction`,this.transactionHandler),window.addEventListener(`resize`,this.resizeHandler),this.scrollTarget.addEventListener(`scroll`,this.resizeHandler),this.update(view,view.state),this.getShouldShow()&&(this.show(),this.updatePosition())}get middlewares(){let middlewares=[];return this.floatingUIOptions.flip&&middlewares.push(flip(typeof this.floatingUIOptions.flip==`boolean`?void 0:this.floatingUIOptions.flip)),this.floatingUIOptions.shift&&middlewares.push(shift(typeof this.floatingUIOptions.shift==`boolean`?void 0:this.floatingUIOptions.shift)),this.floatingUIOptions.offset&&middlewares.push(offset(typeof this.floatingUIOptions.offset==`boolean`?void 0:this.floatingUIOptions.offset)),this.floatingUIOptions.arrow&&middlewares.push(arrow(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&middlewares.push(size(typeof this.floatingUIOptions.size==`boolean`?void 0:this.floatingUIOptions.size)),this.floatingUIOptions.autoPlacement&&middlewares.push(autoPlacement(typeof this.floatingUIOptions.autoPlacement==`boolean`?void 0:this.floatingUIOptions.autoPlacement)),this.floatingUIOptions.hide&&middlewares.push(hide(typeof this.floatingUIOptions.hide==`boolean`?void 0:this.floatingUIOptions.hide)),this.floatingUIOptions.inline&&middlewares.push(inline(typeof this.floatingUIOptions.inline==`boolean`?void 0:this.floatingUIOptions.inline)),middlewares}get virtualElement(){let{selection}=this.editor.state,referencedVirtualElement=this.getReferencedVirtualElement?.call(this);if(referencedVirtualElement)return referencedVirtualElement;if(!this.view?.dom?.parentNode)return;let domRect=posToDOMRect(this.view,selection.from,selection.to),virtualElement={getBoundingClientRect:()=>domRect,getClientRects:()=>[domRect]};if(selection instanceof NodeSelection){let node=this.view.nodeDOM(selection.from),nodeViewWrapper=node.dataset.nodeViewWrapper?node:node.querySelector(`[data-node-view-wrapper]`);nodeViewWrapper&&(node=nodeViewWrapper),node&&(virtualElement={getBoundingClientRect:()=>node.getBoundingClientRect(),getClientRects:()=>[node.getBoundingClientRect()]})}if(selection instanceof CellSelection){let{$anchorCell,$headCell}=selection,from=$anchorCell?$anchorCell.pos:$headCell.pos,to=$headCell?$headCell.pos:$anchorCell.pos,fromDOM=this.view.nodeDOM(from),toDOM=this.view.nodeDOM(to);if(!fromDOM||!toDOM)return;let clientRect=fromDOM===toDOM?fromDOM.getBoundingClientRect():combineDOMRects(fromDOM.getBoundingClientRect(),toDOM.getBoundingClientRect());virtualElement={getBoundingClientRect:()=>clientRect,getClientRects:()=>[clientRect]}}return virtualElement}updatePosition(){if(!this.isVisible)return;let virtualElement=this.virtualElement;virtualElement&&computePosition(virtualElement,this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x,y,strategy,middlewareData})=>{if(!(!this.isVisible||this.editor.isDestroyed||!this.element.isConnected)){if(middlewareData.hide?.referenceHidden||middlewareData.hide?.escaped){this.element.style.visibility=`hidden`;return}this.element.style.visibility=`visible`,this.element.style.width=`max-content`,this.element.style.position=strategy,this.element.style.left=`${x}px`,this.element.style.top=`${y}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()}})}update(view,oldState){let{state}=view,hasValidSelection=state.selection.from!==state.selection.to;if(this.updateDelay>0&&hasValidSelection){this.handleDebouncedUpdate(view,oldState);return}let selectionChanged=!oldState?.selection.eq(view.state.selection),docChanged=!oldState?.doc.eq(view.state.doc);this.updateHandler(view,selectionChanged,docChanged,oldState)}getShouldShow(oldState){let{state}=this.view,{selection}=state,{ranges}=selection,from=Math.min(...ranges.map(range=>range.$from.pos)),to=Math.max(...ranges.map(range=>range.$to.pos));return this.shouldShow?.call(this,{editor:this.editor,element:this.element,view:this.view,state,oldState,from,to})||!1}show(){var _a;this.isVisible||(this.element.style.visibility=`visible`,this.element.style.opacity=`1`,(_a=(typeof this.appendTo==`function`?this.appendTo():this.appendTo)??this.view.dom.parentElement)==null||_a.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0)}hide(){this.isVisible&&=(this.element.style.visibility=`hidden`,this.element.style.opacity=`0`,this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),!1)}updateOptions(newProps){if(newProps.updateDelay!==void 0&&(this.updateDelay=newProps.updateDelay),newProps.resizeDelay!==void 0&&(this.resizeDelay=newProps.resizeDelay),newProps.appendTo!==void 0&&(this.appendTo=newProps.appendTo),newProps.getReferencedVirtualElement!==void 0&&(this.getReferencedVirtualElement=newProps.getReferencedVirtualElement),newProps.shouldShow!==void 0&&newProps.shouldShow&&(this.shouldShow=newProps.shouldShow),newProps.options!==void 0){let newScrollTarget=newProps.options.scrollTarget??window;newScrollTarget!==this.scrollTarget&&(this.scrollTarget.removeEventListener(`scroll`,this.resizeHandler),this.scrollTarget=newScrollTarget,this.scrollTarget.addEventListener(`scroll`,this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...newProps.options}}}destroy(){this.hide(),this.element.removeEventListener(`mousedown`,this.mousedownHandler,{capture:!0}),this.view.dom.removeEventListener(`dragstart`,this.dragstartHandler),window.removeEventListener(`resize`,this.resizeHandler),this.scrollTarget.removeEventListener(`scroll`,this.resizeHandler),this.editor.off(`focus`,this.focusHandler),this.editor.off(`blur`,this.blurHandler),this.editor.off(`transaction`,this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},BubbleMenuPlugin=options=>new Plugin({key:typeof options.pluginKey==`string`?new PluginKey(options.pluginKey):options.pluginKey,view:view=>new BubbleMenuView({view,...options})});Extension.create({name:`bubbleMenu`,addOptions(){return{element:null,pluginKey:`bubbleMenu`,updateDelay:void 0,appendTo:void 0,shouldShow:null}},addProseMirrorPlugins(){return this.options.element?[BubbleMenuPlugin({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,options:this.options.options,appendTo:this.options.appendTo,getReferencedVirtualElement:this.options.getReferencedVirtualElement,shouldShow:this.options.shouldShow})]:[]}});var FloatingMenuView=class{constructor({editor,element,view,pluginKey=`floatingMenu`,updateDelay=250,resizeDelay=60,options,appendTo,shouldShow}){this.preventHide=!1,this.isVisible=!1,this.scrollTarget=window,this.shouldShow=({view,state})=>{let{selection}=state,{$anchor,empty}=selection,isRootDepth=$anchor.depth===1,isEmptyTextBlock=$anchor.parent.isTextblock&&!$anchor.parent.type.spec.code&&!$anchor.parent.textContent&&$anchor.parent.childCount===0&&!this.getTextContent($anchor.parent);return!(!view.hasFocus()||!empty||!isRootDepth||!isEmptyTextBlock||!this.editor.isEditable)},this.floatingUIOptions={strategy:`absolute`,placement:`right`,offset:8,flip:{},shift:{},arrow:!1,size:!1,autoPlacement:!1,hide:!1,inline:!1},this.updateHandler=(view,selectionChanged,docChanged,oldState)=>{let{composing}=view;if(!(composing||!selectionChanged&&!docChanged)){if(!this.getShouldShow(oldState)){this.hide();return}this.updatePosition(),this.show()}},this.mousedownHandler=()=>{this.preventHide=!0},this.focusHandler=()=>{setTimeout(()=>this.update(this.editor.view))},this.blurHandler=({event})=>{if(this.preventHide){this.preventHide=!1;return}event?.relatedTarget&&this.element.parentNode?.contains(event.relatedTarget)||event?.relatedTarget!==this.editor.view.dom&&this.hide()},this.transactionHandler=({transaction:tr})=>{let meta=tr.getMeta(this.pluginKey);meta===`updatePosition`?this.updatePosition():meta&&typeof meta==`object`&&meta.type===`updateOptions`?this.updateOptions(meta.options):meta===`hide`?this.hide():meta===`show`&&(this.updatePosition(),this.show())},this.resizeHandler=()=>{this.resizeDebounceTimer&&clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=window.setTimeout(()=>{this.updatePosition()},this.resizeDelay)},this.editor=editor,this.element=element,this.view=view,this.pluginKey=pluginKey,this.updateDelay=updateDelay,this.resizeDelay=resizeDelay,this.appendTo=appendTo,this.scrollTarget=options?.scrollTarget??window,this.floatingUIOptions={...this.floatingUIOptions,...options},this.element.tabIndex=0,shouldShow&&(this.shouldShow=shouldShow),this.element.addEventListener(`mousedown`,this.mousedownHandler,{capture:!0}),this.editor.on(`focus`,this.focusHandler),this.editor.on(`blur`,this.blurHandler),this.editor.on(`transaction`,this.transactionHandler),window.addEventListener(`resize`,this.resizeHandler),this.scrollTarget.addEventListener(`scroll`,this.resizeHandler),this.update(view,view.state),this.getShouldShow()&&(this.show(),this.updatePosition())}getTextContent(node){return getText(node,{textSerializers:getTextSerializersFromSchema(this.editor.schema)})}get middlewares(){let middlewares=[];return this.floatingUIOptions.flip&&middlewares.push(flip(typeof this.floatingUIOptions.flip==`boolean`?void 0:this.floatingUIOptions.flip)),this.floatingUIOptions.shift&&middlewares.push(shift(typeof this.floatingUIOptions.shift==`boolean`?void 0:this.floatingUIOptions.shift)),this.floatingUIOptions.offset&&middlewares.push(offset(typeof this.floatingUIOptions.offset==`boolean`?void 0:this.floatingUIOptions.offset)),this.floatingUIOptions.arrow&&middlewares.push(arrow(this.floatingUIOptions.arrow)),this.floatingUIOptions.size&&middlewares.push(size(typeof this.floatingUIOptions.size==`boolean`?void 0:this.floatingUIOptions.size)),this.floatingUIOptions.autoPlacement&&middlewares.push(autoPlacement(typeof this.floatingUIOptions.autoPlacement==`boolean`?void 0:this.floatingUIOptions.autoPlacement)),this.floatingUIOptions.hide&&middlewares.push(hide(typeof this.floatingUIOptions.hide==`boolean`?void 0:this.floatingUIOptions.hide)),this.floatingUIOptions.inline&&middlewares.push(inline(typeof this.floatingUIOptions.inline==`boolean`?void 0:this.floatingUIOptions.inline)),middlewares}getShouldShow(oldState){let{state}=this.view,{selection}=state,{ranges}=selection,from=Math.min(...ranges.map(range=>range.$from.pos)),to=Math.max(...ranges.map(range=>range.$to.pos));return this.shouldShow?.call(this,{editor:this.editor,view:this.view,state,oldState,from,to})}updateOptions(newProps){if(newProps.updateDelay!==void 0&&(this.updateDelay=newProps.updateDelay),newProps.resizeDelay!==void 0&&(this.resizeDelay=newProps.resizeDelay),newProps.appendTo!==void 0&&(this.appendTo=newProps.appendTo),newProps.shouldShow!==void 0&&newProps.shouldShow&&(this.shouldShow=newProps.shouldShow),newProps.options!==void 0){let newScrollTarget=newProps.options.scrollTarget??window;newScrollTarget!==this.scrollTarget&&(this.scrollTarget.removeEventListener(`scroll`,this.resizeHandler),this.scrollTarget=newScrollTarget,this.scrollTarget.addEventListener(`scroll`,this.resizeHandler)),this.floatingUIOptions={...this.floatingUIOptions,...newProps.options}}}updatePosition(){if(!this.view?.dom?.parentNode)return;let{selection}=this.editor.state,domRect=posToDOMRect(this.view,selection.from,selection.to);computePosition({getBoundingClientRect:()=>domRect,getClientRects:()=>[domRect]},this.element,{placement:this.floatingUIOptions.placement,strategy:this.floatingUIOptions.strategy,middleware:this.middlewares}).then(({x,y,strategy,middlewareData})=>{if(middlewareData.hide?.referenceHidden||middlewareData.hide?.escaped){this.element.style.visibility=`hidden`;return}this.element.style.visibility=`visible`,this.element.style.width=`max-content`,this.element.style.position=strategy,this.element.style.left=`${x}px`,this.element.style.top=`${y}px`,this.isVisible&&this.floatingUIOptions.onUpdate&&this.floatingUIOptions.onUpdate()})}update(view,oldState){let selectionChanged=!oldState?.selection.eq(view.state.selection),docChanged=!oldState?.doc.eq(view.state.doc);this.updateHandler(view,selectionChanged,docChanged,oldState)}show(){var _a;this.isVisible||(this.element.style.visibility=`visible`,this.element.style.opacity=`1`,(_a=(typeof this.appendTo==`function`?this.appendTo():this.appendTo)??this.view.dom.parentElement)==null||_a.appendChild(this.element),this.floatingUIOptions.onShow&&this.floatingUIOptions.onShow(),this.isVisible=!0)}hide(){this.isVisible&&=(this.element.style.visibility=`hidden`,this.element.style.opacity=`0`,this.element.remove(),this.floatingUIOptions.onHide&&this.floatingUIOptions.onHide(),!1)}destroy(){this.hide(),this.element.removeEventListener(`mousedown`,this.mousedownHandler,{capture:!0}),window.removeEventListener(`resize`,this.resizeHandler),this.scrollTarget.removeEventListener(`scroll`,this.resizeHandler),this.editor.off(`focus`,this.focusHandler),this.editor.off(`blur`,this.blurHandler),this.editor.off(`transaction`,this.transactionHandler),this.floatingUIOptions.onDestroy&&this.floatingUIOptions.onDestroy()}},FloatingMenuPlugin=options=>new Plugin({key:typeof options.pluginKey==`string`?new PluginKey(options.pluginKey):options.pluginKey,view:view=>new FloatingMenuView({view,...options})});Extension.create({name:`floatingMenu`,addOptions(){return{element:null,options:{},pluginKey:`floatingMenu`,updateDelay:void 0,resizeDelay:void 0,appendTo:void 0,shouldShow:null}},addCommands(){return{updateFloatingMenuPosition:()=>({tr,dispatch})=>(dispatch&&tr.setMeta(this.options.pluginKey,`updatePosition`),!0)}},addProseMirrorPlugins(){return this.options.element?[FloatingMenuPlugin({pluginKey:this.options.pluginKey,editor:this.editor,element:this.options.element,updateDelay:this.options.updateDelay,resizeDelay:this.options.resizeDelay,options:this.options.options,appendTo:this.options.appendTo,shouldShow:this.options.shouldShow})]:[]}});function getAutoPluginKey(pluginKey,defaultName){return pluginKey??new PluginKey(defaultName)}var useIsomorphicLayoutEffect=typeof window<`u`?useLayoutEffect:useEffect,PLUGIN_MANAGED_STYLE_PROPERTIES=new Set([`left`,`opacity`,`position`,`top`,`visibility`,`width`]),UNITLESS_STYLE_PROPERTIES=new Set(`animationIterationCount.aspectRatio.borderImageOutset.borderImageSlice.borderImageWidth.columnCount.columns.fillOpacity.flex.flexGrow.flexShrink.fontWeight.gridArea.gridColumn.gridColumnEnd.gridColumnStart.gridRow.gridRowEnd.gridRowStart.lineClamp.lineHeight.opacity.order.orphans.scale.stopOpacity.strokeDasharray.strokeDashoffset.strokeMiterlimit.strokeOpacity.strokeWidth.tabSize.widows.zIndex.zoom`.split(`.`)),ATTRIBUTE_EXCLUSIONS=new Set([`children`,`className`,`style`]),DIRECT_PROPERTY_KEYS=new Set([`tabIndex`]),FORWARDED_ATTRIBUTE_KEYS=new Set([`accessKey`,`autoCapitalize`,`contentEditable`,`contextMenu`,`dir`,`draggable`,`enterKeyHint`,`hidden`,`id`,`lang`,`nonce`,`role`,`slot`,`spellCheck`,`tabIndex`,`title`,`translate`]),SPECIAL_EVENT_NAMES={Blur:`focusout`,DoubleClick:`dblclick`,Focus:`focusin`,MouseEnter:`mouseenter`,MouseLeave:`mouseleave`};function isEventProp(key,value){return/^on[A-Z]/.test(key)&&typeof value==`function`}function toAttributeName(key){return key.startsWith(`aria-`)||key.startsWith(`data-`),key}function isForwardedAttributeKey(key){return key.startsWith(`aria-`)||key.startsWith(`data-`)||FORWARDED_ATTRIBUTE_KEYS.has(key)}function toStylePropertyName(key){return key.startsWith(`--`)?key:key.replace(/[A-Z]/g,match=>`-${match.toLowerCase()}`)}function toEventConfig(key){let useCapture=key.endsWith(`Capture`),reactEventName=(useCapture?key.slice(0,-7):key).slice(2);return{eventName:SPECIAL_EVENT_NAMES[reactEventName]??reactEventName.toLowerCase(),options:useCapture?{capture:!0}:void 0}}function createSyntheticEvent(element,nativeEvent){let defaultPrevented=nativeEvent.defaultPrevented,propagationStopped=!1,syntheticEvent=Object.create(nativeEvent);return Object.defineProperties(syntheticEvent,{nativeEvent:{value:nativeEvent},currentTarget:{value:element},target:{value:nativeEvent.target},persist:{value:()=>void 0},isDefaultPrevented:{value:()=>defaultPrevented},isPropagationStopped:{value:()=>propagationStopped},preventDefault:{value:()=>{defaultPrevented=!0,nativeEvent.preventDefault()}},stopPropagation:{value:()=>{propagationStopped=!0,nativeEvent.stopPropagation()}}}),syntheticEvent}function isDirectPropertyKey(key){return DIRECT_PROPERTY_KEYS.has(key)}function setDirectProperty(element,key,value){if(key===`tabIndex`){element.tabIndex=Number(value);return}element[key]=value}function clearDirectProperty(element,key){if(key===`tabIndex`){element.removeAttribute(`tabindex`);return}let propertyValue=element[key];if(typeof propertyValue==`boolean`){element[key]=!1;return}if(typeof propertyValue==`number`){element[key]=0;return}element[key]=``}function toStyleValue(styleName,value){return typeof value!=`number`||value===0||styleName.startsWith(`--`)||UNITLESS_STYLE_PROPERTIES.has(styleName)?String(value):`${value}px`}function removeStyleProperty(element,styleName){PLUGIN_MANAGED_STYLE_PROPERTIES.has(styleName)||element.style.removeProperty(toStylePropertyName(styleName))}function applyStyleProperty(element,styleName,value){PLUGIN_MANAGED_STYLE_PROPERTIES.has(styleName)||element.style.setProperty(toStylePropertyName(styleName),toStyleValue(styleName,value))}function syncAttributes(element,prevProps,nextProps){new Set([...Object.keys(prevProps),...Object.keys(nextProps)]).forEach(key=>{if(ATTRIBUTE_EXCLUSIONS.has(key)||!isForwardedAttributeKey(key)||isEventProp(key,prevProps[key])||isEventProp(key,nextProps[key]))return;let prevValue=prevProps[key],nextValue=nextProps[key];if(prevValue===nextValue)return;let attributeName=toAttributeName(key);if(nextValue==null||nextValue===!1){isDirectPropertyKey(key)&&clearDirectProperty(element,key),element.removeAttribute(attributeName);return}if(nextValue===!0){isDirectPropertyKey(key)&&setDirectProperty(element,key,!0),element.setAttribute(attributeName,``);return}if(isDirectPropertyKey(key)){setDirectProperty(element,key,nextValue);return}element.setAttribute(attributeName,String(nextValue))})}function syncClassName(element,prevClassName,nextClassName){if(prevClassName!==nextClassName){if(nextClassName){element.className=nextClassName;return}element.removeAttribute(`class`)}}function syncStyles(element,prevStyle,nextStyle){let previousStyle=prevStyle??{},currentStyle=nextStyle??{};new Set([...Object.keys(previousStyle),...Object.keys(currentStyle)]).forEach(styleName=>{let prevValue=previousStyle[styleName],nextValue=currentStyle[styleName];if(prevValue!==nextValue){if(nextValue==null){removeStyleProperty(element,styleName);return}applyStyleProperty(element,styleName,nextValue)}})}function syncEventListeners(element,prevListeners,nextProps){prevListeners.forEach(({eventName,listener,options})=>{element.removeEventListener(eventName,listener,options)});let nextListeners=[];return Object.entries(nextProps).forEach(([key,value])=>{if(!isEventProp(key,value))return;let{eventName,options}=toEventConfig(key),listener=event=>{value(createSyntheticEvent(element,event))};element.addEventListener(eventName,listener,options),nextListeners.push({eventName,listener,options})}),nextListeners}function useMenuElementProps(element,props){let previousPropsRef=useRef({}),listenersRef=useRef([]);useIsomorphicLayoutEffect(()=>{let previousProps=previousPropsRef.current;return syncClassName(element,previousProps.className,props.className),syncStyles(element,previousProps.style,props.style),syncAttributes(element,previousProps,props),listenersRef.current=syncEventListeners(element,listenersRef.current,props),previousPropsRef.current=props,()=>{listenersRef.current.forEach(({eventName,listener,options})=>{element.removeEventListener(eventName,listener,options)}),listenersRef.current=[]}},[element,props])}var BubbleMenu=React.forwardRef(({pluginKey,editor,updateDelay,resizeDelay,appendTo,shouldShow=null,getReferencedVirtualElement,options,children,...restProps},ref)=>{let menuEl=useRef(document.createElement(`div`)),resolvedPluginKey=useRef(getAutoPluginKey(pluginKey,`bubbleMenu`)).current;useMenuElementProps(menuEl.current,restProps),typeof ref==`function`?ref(menuEl.current):ref&&(ref.current=menuEl.current);let{editor:currentEditor}=useCurrentEditor(),pluginEditor=editor||currentEditor,bubbleMenuPluginProps={updateDelay,resizeDelay,appendTo,pluginKey:resolvedPluginKey,shouldShow,getReferencedVirtualElement,options},bubbleMenuPluginPropsRef=useRef(bubbleMenuPluginProps);bubbleMenuPluginPropsRef.current=bubbleMenuPluginProps;let[pluginInitialized,setPluginInitialized]=useState(!1),skipFirstUpdateRef=useRef(!0);return useEffect(()=>{if(pluginEditor?.isDestroyed)return;if(!pluginEditor){console.warn(`BubbleMenu component is not rendered inside of an editor component or does not have editor prop.`);return}let bubbleMenuElement=menuEl.current;bubbleMenuElement.style.visibility=`hidden`,bubbleMenuElement.style.position=`absolute`;let plugin=BubbleMenuPlugin({...bubbleMenuPluginPropsRef.current,editor:pluginEditor,element:bubbleMenuElement});pluginEditor.registerPlugin(plugin);let createdPluginKey=bubbleMenuPluginPropsRef.current.pluginKey;return skipFirstUpdateRef.current=!0,setPluginInitialized(!0),()=>{setPluginInitialized(!1),pluginEditor.unregisterPlugin(createdPluginKey),window.requestAnimationFrame(()=>{bubbleMenuElement.parentNode&&bubbleMenuElement.parentNode.removeChild(bubbleMenuElement)})}},[pluginEditor]),useEffect(()=>{if(!(!pluginInitialized||!pluginEditor||pluginEditor.isDestroyed)){if(skipFirstUpdateRef.current){skipFirstUpdateRef.current=!1;return}pluginEditor.view.dispatch(pluginEditor.state.tr.setMeta(resolvedPluginKey,{type:`updateOptions`,options:bubbleMenuPluginPropsRef.current}))}},[pluginInitialized,pluginEditor,updateDelay,resizeDelay,shouldShow,options,appendTo,getReferencedVirtualElement,resolvedPluginKey]),createPortal(children,menuEl.current)});React.forwardRef(({pluginKey,editor,updateDelay,resizeDelay,appendTo,shouldShow=null,options,children,...restProps},ref)=>{let menuEl=useRef(document.createElement(`div`)),resolvedPluginKey=useRef(getAutoPluginKey(pluginKey,`floatingMenu`)).current;useMenuElementProps(menuEl.current,restProps),typeof ref==`function`?ref(menuEl.current):ref&&(ref.current=menuEl.current);let{editor:currentEditor}=useCurrentEditor(),pluginEditor=editor||currentEditor,floatingMenuPluginProps={updateDelay,resizeDelay,appendTo,pluginKey:resolvedPluginKey,shouldShow,options},floatingMenuPluginPropsRef=useRef(floatingMenuPluginProps);floatingMenuPluginPropsRef.current=floatingMenuPluginProps;let[pluginInitialized,setPluginInitialized]=useState(!1),skipFirstUpdateRef=useRef(!0);return useEffect(()=>{if(pluginEditor?.isDestroyed)return;if(!pluginEditor){console.warn(`FloatingMenu component is not rendered inside of an editor component or does not have editor prop.`);return}let floatingMenuElement=menuEl.current;floatingMenuElement.style.visibility=`hidden`,floatingMenuElement.style.position=`absolute`;let plugin=FloatingMenuPlugin({...floatingMenuPluginPropsRef.current,editor:pluginEditor,element:floatingMenuElement});pluginEditor.registerPlugin(plugin);let createdPluginKey=floatingMenuPluginPropsRef.current.pluginKey;return skipFirstUpdateRef.current=!0,setPluginInitialized(!0),()=>{setPluginInitialized(!1),pluginEditor.unregisterPlugin(createdPluginKey),window.requestAnimationFrame(()=>{floatingMenuElement.parentNode&&floatingMenuElement.parentNode.removeChild(floatingMenuElement)})}},[pluginEditor]),useEffect(()=>{if(!(!pluginInitialized||!pluginEditor||pluginEditor.isDestroyed)){if(skipFirstUpdateRef.current){skipFirstUpdateRef.current=!1;return}pluginEditor.view.dispatch(pluginEditor.state.tr.setMeta(resolvedPluginKey,{type:`updateOptions`,options:floatingMenuPluginPropsRef.current}))}},[pluginInitialized,pluginEditor,updateDelay,resizeDelay,shouldShow,options,appendTo,resolvedPluginKey]),createPortal(children,menuEl.current)});var message_editor_bubble_menu_module_default={bubbleMenu:`_bubbleMenu_lm6yy_1`},shouldShowBubbleMenu=({editor,state,from,to})=>{let{doc,selection}=state,{empty}=selection;return!editor.isEditable||empty||!(doc.textBetween(from,to).length>0)?!1:editor.isFocused},BUBBLE_MENU_OPTIONS={placement:`top`},toggleCommands={bold:editor=>editor.chain().focus().toggleBold().run(),bulletList:editor=>editor.chain().focus().toggleBulletList().run(),italic:editor=>editor.chain().focus().toggleItalic().run(),orderedList:editor=>editor.chain().focus().toggleOrderedList().run(),underline:editor=>editor.chain().focus().toggleUnderline().run()},MARK_ITEMS=[{format:`bold`,icon:Bold,message:messages.formatBold},{format:`italic`,icon:Italic,message:messages.formatItalic},{format:`underline`,icon:Underline,message:messages.formatUnderline}],LIST_ITEMS=[{format:`bulletList`,icon:BulletList,message:messages.formatBulletList},{format:`orderedList`,icon:NumberList,message:messages.formatNumberedList}],MessageEditorBubbleMenuComponent=({editor,menuAnchorRef,onFormatToggle})=>{let intl=useIntl(),activeFormats=useEditorState({editor,selector:({editor:editorInstance})=>({bold:editorInstance.isActive(`bold`),bulletList:editorInstance.isActive(`bulletList`),italic:editorInstance.isActive(`italic`),orderedList:editorInstance.isActive(`orderedList`),underline:editorInstance.isActive(`underline`)})}),appendToAnchor=useCallback(()=>menuAnchorRef.current??document.body,[menuAnchorRef]),handleToggle=useCallback(format=>{toggleCommands[format](editor),onFormatToggle?.(format,editor.isActive(format))},[editor,onFormatToggle]),handleToolbarKeyDown=useCallback(event=>{event.key===`Escape`&&(event.preventDefault(),event.stopPropagation(),editor.chain().focus().setTextSelection(editor.state.selection.to).run())},[editor]),renderToggleItem=({format,icon,message})=>jsx(Toolbar.ToggleItem,{"aria-label":intl.formatMessage(message),icon,onClick:()=>handleToggle(format),onMouseDown:event=>{event.preventDefault()},value:format},format);return jsx(BubbleMenu,{appendTo:appendToAnchor,className:message_editor_bubble_menu_module_default.bubbleMenu,editor,options:BUBBLE_MENU_OPTIONS,shouldShow:shouldShowBubbleMenu,updateDelay:0,...THREADED_ANNOTATIONS_PORTAL,children:jsxs(Toolbar.Root,{onKeyDown:handleToolbarKeyDown,children:[jsx(Toolbar.ToggleGroup,{type:`multiple`,value:MARK_ITEMS.filter(({format})=>activeFormats[format]).map(({format})=>format),children:MARK_ITEMS.map(renderToggleItem)}),jsx(Toolbar.Separator,{}),jsx(Toolbar.ToggleGroup,{type:`multiple`,value:LIST_ITEMS.filter(({format})=>activeFormats[format]).map(({format})=>format),children:LIST_ITEMS.map(renderToggleItem)})]})})},MessageEditorBubbleMenu=memo(({editor,menuAnchorRef,onFormatToggle})=>editor?jsx(MessageEditorBubbleMenuComponent,{editor,menuAnchorRef,onFormatToggle}):null);MessageEditorBubbleMenu.displayName=`MessageEditorBubbleMenu`;export{MessageEditorBubbleMenu as t};
@@ -1 +1 @@
1
- import messages from"../../messages.js";import{t as MentionComponent}from"../../../../chunks/mention-component.js";import{Text}from"@box/blueprint-web";import{useIntl}from"react-intl";import{jsx}from"react/jsx-runtime";var renderMentionNode=({node,index,paragraphIndex})=>{let key=`mention-${node.attrs.mentionedUserId}-${paragraphIndex}-${index}`;return jsx(MentionComponent,{authorId:node.attrs.authorId,mentionedUserEmail:node.attrs.mentionedUserEmail,mentionedUserId:node.attrs.mentionedUserId,mentionedUserName:node.attrs.mentionedUserName,mentionId:node.attrs.mentionId},key)},renderTextNode=({node,index,paragraphIndex,intl})=>{let key=`text-${node.text.substring(0,20)}-${paragraphIndex}-${index}`;return jsx(Text,{"aria-label":intl.formatMessage(messages.textMessageAriaLabel),as:`span`,color:`textOnLightDefault`,variant:`bodyDefault`,children:node.text},key)},renderParagraphContent=({content,paragraphIndex,intl})=>content.map((node,index)=>{switch(node.type){case`mention`:return renderMentionNode({node,index,paragraphIndex});case`text`:return renderTextNode({node,index,paragraphIndex,intl});default:return[]}}),renderParagraphNode=({paragraph,index,intl})=>{let content=paragraph.content||[],key=`paragraph-${index}`;return jsx(Text,{as:`p`,variant:`bodyDefault`,children:content.length>0?renderParagraphContent({content,paragraphIndex:index,intl}):jsx(`br`,{})},key)},MessageRenderer=({messageObject})=>{let intl=useIntl(),{content}=messageObject;return!content&&content.length===0?null:content.map((paragraph,index)=>renderParagraphNode({paragraph,index,intl}))};export{MessageRenderer};
1
+ import messages from"../../messages.js";import{t as MentionComponent}from"../../../../chunks/mention-component.js";import{Text}from"@box/blueprint-web";import"react";import{useIntl}from"react-intl";import{jsx}from"react/jsx-runtime";var renderMentionNode=({node,index,paragraphIndex})=>{let key=`mention-${node.attrs.mentionedUserId}-${paragraphIndex}-${index}`;return jsx(MentionComponent,{authorId:node.attrs.authorId,mentionedUserEmail:node.attrs.mentionedUserEmail,mentionedUserId:node.attrs.mentionedUserId,mentionedUserName:node.attrs.mentionedUserName,mentionId:node.attrs.mentionId},key)},renderTextNode=({node,index,paragraphIndex,intl})=>{let key=`text-${node.text.substring(0,20)}-${paragraphIndex}-${index}`;return jsx(Text,{"aria-label":intl.formatMessage(messages.textMessageAriaLabel),as:`span`,color:`textOnLightDefault`,variant:`bodyDefault`,children:node.text},key)},renderParagraphContent=({content,paragraphIndex,intl})=>content.map((node,index)=>{switch(node.type){case`mention`:return renderMentionNode({node,index,paragraphIndex});case`text`:return renderTextNode({node,index,paragraphIndex,intl});default:return[]}}),renderParagraphNode=({paragraph,index,intl})=>{let content=paragraph.content||[],key=`paragraph-${index}`;return jsx(Text,{as:`p`,variant:`bodyDefault`,children:content.length>0?renderParagraphContent({content,paragraphIndex:index,intl}):jsx(`br`,{})},key)},MessageRenderer=({messageObject})=>{let intl=useIntl(),{content}=messageObject;return!content&&content.length===0?null:content.map((paragraph,index)=>renderParagraphNode({paragraph,index,intl}))};export{MessageRenderer};
@@ -1 +1 @@
1
- import{a as TextSelection,i as PluginKey,n as NodeSelection,r as Plugin,t as AllSelection}from"../../../../../../chunks/dist.js";import{Extension}from"@tiptap/core";var NormalizeEmptyNodeSelection=Extension.create({name:`normalizeEmptyNodeSelection`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`normalizeEmptyNodeSelection`),appendTransaction:(_transactions,_oldState,newState)=>{let{doc,selection}=newState;return selection instanceof NodeSelection&&selection.node.isTextblock&&selection.node.content.size===0?newState.tr.setSelection(TextSelection.create(doc,selection.from+1)):selection instanceof AllSelection&&doc.childCount===1&&doc.firstChild?.isTextblock&&doc.firstChild.content.size===0?newState.tr.setSelection(TextSelection.create(doc,1)):null}})]}});export{NormalizeEmptyNodeSelection};
1
+ import{i as PluginKey,n as NodeSelection,r as Plugin,s as TextSelection,t as AllSelection}from"../../../../../../chunks/dist.js";import{Extension}from"@tiptap/core";var NormalizeEmptyNodeSelection=Extension.create({name:`normalizeEmptyNodeSelection`,addProseMirrorPlugins(){return[new Plugin({key:new PluginKey(`normalizeEmptyNodeSelection`),appendTransaction:(_transactions,_oldState,newState)=>{let{doc,selection}=newState;return selection instanceof NodeSelection&&selection.node.isTextblock&&selection.node.content.size===0?newState.tr.setSelection(TextSelection.create(doc,selection.from+1)):selection instanceof AllSelection&&doc.childCount===1&&doc.firstChild?.isTextblock&&doc.firstChild.content.size===0?newState.tr.setSelection(TextSelection.create(doc,1)):null}})]}});export{NormalizeEmptyNodeSelection};
@@ -1 +1 @@
1
- import{THREADED_ANNOTATIONS_PORTAL}from"../../../v2/constants.js";import{useMentionContext}from"../../mention-component/mention-context.js";import{createSuggestionOptions}from"./editor-extensions/custom-mention/custom-mention-suggestions.js";import{MENTION_PLUGIN_KEY,normalizeMentionPastedText,normalizeMentionTextInput}from"./editor-extensions/custom-mention/mention-trigger-normalization.js";import{useMentionState}from"./editor-extensions/custom-mention/useMentionState.js";import{createMessageEditorExtensions}from"./editor-extensions/create-message-editor-extensions.js";import{useCharacterLimit}from"./hooks/useCharacterLimit.js";import{useEditorContainerState}from"./hooks/useEditorContainerState.js";import{useMentionUserSelection}from"./hooks/useMentionUserSelection.js";import{MessageEditorProvider,useMessageEditorContext}from"./message-editor-context.js";import messages from"./messages.js";import{t as message_editor_module_default}from"../../../../../chunks/message-editor2.module.js";import{CharacterLimitCounter}from"./subcomponents/character-limit-counter.js";import{EditButtons}from"./subcomponents/edit-buttons.js";import{ErrorMessage}from"./subcomponents/error-message.js";import{PostButton}from"./subcomponents/post-button.js";import{t as TimestampToggle}from"../../../../../chunks/timestamp-toggle.js";import{MessageEditorVariant}from"./message-editor.types.js";import{VisuallyHidden}from"@box/blueprint-web";import clsx from"clsx";import{useEffect,useMemo,useRef}from"react";import{useIntl}from"react-intl";import{Fragment,jsx,jsxs}from"react/jsx-runtime";import{UserSelectorHeadless}from"@box/user-selector";import{EditorContent,useEditor}from"@tiptap/react";var IS_APPLE_DEVICE=typeof navigator<`u`&&/Mac|iP(hone|ad|od)/.test(navigator.platform),getShortcutFormat=event=>{if(!(IS_APPLE_DEVICE?event.metaKey:event.ctrlKey))return null;if(event.shiftKey)return event.code===`Digit8`?`bulletList`:event.code===`Digit7`?`orderedList`:null;switch(event.key.toLowerCase()){case`b`:return`bold`;case`i`:return`italic`;case`u`:return`underline`;default:return null}},MessageEditorContent=props=>{let{autoFocus=!0,disableComponent=!1,initialContent,isFirstAnnotation=!1,isReply=!1,isRichTextEnabled=!1,maxCharacterCount,onFormatToggle,userSelectorProps,videoTimestamp}=props,userSelectorRef=useRef(null),editorContainerRef=useRef(null),editorRef=useRef(null),editorInstanceRef=useRef(null),onFormatToggleRef=useRef(onFormatToggle);onFormatToggleRef.current=onFormatToggle;let intl=useIntl(),{errorMessage,isLoading}=useMessageEditorContext(),{close:closeMentionDropdown,isActive,query,command,suggestionCallbacks}=useMentionState(userSelectorRef),{closeAllPopovers}=useMentionContext(),placeholderText=intl.formatMessage(isReply?messages.placeholderReply:messages.placeholderAddComment),isEditVariant=props.variant===MessageEditorVariant.EDIT_MESSAGE,editor=useEditor({shouldRerenderOnTransaction:!0,extensions:createMessageEditorExtensions({isRichTextEnabled,mentionSuggestion:createSuggestionOptions(MENTION_PLUGIN_KEY,`@`,suggestionCallbacks),placeholder:placeholderText}),autofocus:autoFocus,content:initialContent,editorProps:{attributes:{class:message_editor_module_default.editor},handleKeyDown:(view,event)=>{if(isRichTextEnabled){let format=getShortcutFormat(event),editorInstance=editorInstanceRef.current;if(format&&editorInstance?.isEditable){let wasActive=editorInstance.isActive(format);queueMicrotask(()=>{if(editorInstance.isDestroyed)return;let isFormatActive=editorInstance.isActive(format);isFormatActive!==wasActive&&onFormatToggleRef.current?.(format,isFormatActive)})}}return!1},handleTextInput:normalizeMentionTextInput,transformPastedText:normalizeMentionPastedText},onCreate:({editor:editorInstance})=>{editorInstanceRef.current=editorInstance,editorRef.current=editorInstance.view.dom,autoFocus&&editorInstance.commands.focus(`end`)},onUpdate:()=>{closeAllPopovers?.()}},[placeholderText,isRichTextEnabled]),{onUserSelected}=useMentionUserSelection(useMemo(()=>command&&editor&&!editor.isDestroyed?{command,editor}:null,[command,editor])),{exceedsSingleLine,hasScroll,isAtBottom}=useEditorContainerState(editorContainerRef,editor),characterLimitState=useCharacterLimit(editor,initialContent,maxCharacterCount),shouldApplyEditorFullWidth=isEditVariant||!isFirstAnnotation||isFirstAnnotation&&exceedsSingleLine,isEditorEmpty=!editor||editor?.isEmpty,disableEditor=disableComponent||isLoading,isCharacterLimitExceeded=(characterLimitState?.excess??0)>0,isPostDisabled=isEditorEmpty||disableEditor||isCharacterLimitExceeded,showCharacterLimitCounter=characterLimitState&&characterLimitState.excess>0&&shouldApplyEditorFullWidth;useEffect(()=>{editor&&editor.setEditable(!disableEditor)},[editor,disableEditor]),useEffect(()=>{if(!isCharacterLimitExceeded||!editorContainerRef.current||!initialContent)return;let innerFrameId=0,outerFrameId=requestAnimationFrame(()=>{innerFrameId=requestAnimationFrame(()=>{editorContainerRef.current?.scrollTo({top:editorContainerRef.current.scrollHeight})})});return()=>{cancelAnimationFrame(outerFrameId),cancelAnimationFrame(innerFrameId)}},[isCharacterLimitExceeded]),useEffect(()=>{!editor||initialContent===void 0||queueMicrotask(()=>{editor.isDestroyed||(editor.commands.setContent(initialContent??``,{emitUpdate:!1}),autoFocus&&editor.commands.focus(`end`))})},[initialContent]),useEffect(()=>{if(!isActive)return;let portalSelector=`[${Object.keys(THREADED_ANNOTATIONS_PORTAL)[0]}]`,isInsideEditorOrPortal=target=>{if(editorContainerRef.current?.contains(target))return!0;let portals=document.querySelectorAll(portalSelector);for(let portal of portals)if(portal.contains(target))return!0;return!1},handleClose=e=>{let target=e.target;!target||isInsideEditorOrPortal(target)||closeMentionDropdown()},frameId=requestAnimationFrame(()=>{document.addEventListener(`mousedown`,handleClose),document.addEventListener(`focusin`,handleClose)});return()=>{cancelAnimationFrame(frameId),document.removeEventListener(`mousedown`,handleClose),document.removeEventListener(`focusin`,handleClose)}},[closeMentionDropdown,isActive]);let anchorElement=jsx(`div`,{className:message_editor_module_default.anchorElement});return jsx(`div`,{"data-no-expand":!0,className:message_editor_module_default.messageEditorWrapper,children:jsxs(`div`,{className:clsx(message_editor_module_default.messageEditor,{[message_editor_module_default.editorHasScroll]:hasScroll,[message_editor_module_default.editorEditMode]:isEditVariant,[message_editor_module_default.editorError]:errorMessage||isCharacterLimitExceeded,[message_editor_module_default.editorFirstAnnotation]:!isEditVariant&&isFirstAnnotation,[message_editor_module_default.editorCharacterLimitExceeded]:isCharacterLimitExceeded}),children:[jsxs(`div`,{className:clsx(message_editor_module_default.editorViewport,{[message_editor_module_default.editorFullWidth]:shouldApplyEditorFullWidth}),children:[jsxs(`div`,{ref:editorContainerRef,className:message_editor_module_default.editorContainer,"aria-label":intl.formatMessage(messages.scrollContainerAriaLabel),children:[jsx(EditorContent,{"aria-label":intl.formatMessage(messages.editorContentAriaLabel),editor}),jsx(UserSelectorHeadless,{ref:userSelectorRef,inputElementRef:editorRef,onSelectedUserChange:onUserSelected,open:isActive,rootElement:anchorElement,value:query,...userSelectorProps,popoverContentContainerProps:{...userSelectorProps.popoverContentContainerProps,...THREADED_ANNOTATIONS_PORTAL,avoidCollisions:!0}})]}),hasScroll&&jsx(`div`,{className:clsx(message_editor_module_default.editorFade,{[message_editor_module_default.editorFadeHidden]:isAtBottom}),"aria-hidden":`true`})]}),jsx(`div`,{className:clsx(message_editor_module_default.actionsWrapper,{[message_editor_module_default.withTimestampToggle]:!!videoTimestamp}),children:jsxs(`div`,{className:clsx(message_editor_module_default.actionsWrapperInner,{[message_editor_module_default.scrolledToBottom]:isAtBottom,[message_editor_module_default.characterLimitExceeded]:isCharacterLimitExceeded}),children:[errorMessage&&jsx(ErrorMessage,{errorMessage}),characterLimitState&&characterLimitState.excess>0&&!shouldApplyEditorFullWidth&&jsx(VisuallyHidden,{role:`alert`,children:intl.formatMessage(messages.characterLimitExceeded,{excess:characterLimitState.excess})}),videoTimestamp&&jsx(TimestampToggle,{className:message_editor_module_default.timestampToggle,disabled:disableEditor,formattedTimestamp:videoTimestamp.formattedTimestamp,isPressed:videoTimestamp.isPressed,onChange:videoTimestamp.onPressedChange}),isEditVariant?jsxs(`div`,{className:message_editor_module_default.editActionsColumn,children:[showCharacterLimitCounter&&jsx(CharacterLimitCounter,{count:characterLimitState.count,excess:characterLimitState.excess,maxCount:characterLimitState.maxCount}),jsx(`div`,{className:message_editor_module_default.editActionsRow,children:jsx(EditButtons,{disabled:isPostDisabled,getEditorJsonContent:()=>editor?.getJSON(),onCancel:props.onEditCancel,onEditSuccess:props.onEditSuccess,onSave:props.onSave,onSaveError:props.onSaveError})})]}):jsxs(Fragment,{children:[showCharacterLimitCounter&&jsx(CharacterLimitCounter,{count:characterLimitState.count,excess:characterLimitState.excess,maxCount:characterLimitState.maxCount}),jsx(PostButton,{cleanEditor:()=>editor?.commands.setContent(``,{emitUpdate:!1}),disabled:isPostDisabled,getEditorJsonContent:()=>editor?.getJSON(),onPost:props.onPost,onPostError:props.onPostError,onPostSuccess:props.onPostSuccess})]})]})})]})})},MessageEditor=props=>jsx(MessageEditorProvider,{children:jsx(MessageEditorContent,{...props})});export{MessageEditor,MessageEditorVariant};
1
+ import{THREADED_ANNOTATIONS_PORTAL}from"../../../v2/constants.js";import{useMentionContext}from"../../mention-component/mention-context.js";import{createSuggestionOptions}from"./editor-extensions/custom-mention/custom-mention-suggestions.js";import{MENTION_PLUGIN_KEY,normalizeMentionPastedText,normalizeMentionTextInput}from"./editor-extensions/custom-mention/mention-trigger-normalization.js";import{useMentionState}from"./editor-extensions/custom-mention/useMentionState.js";import{createMessageEditorExtensions}from"./editor-extensions/create-message-editor-extensions.js";import{useCharacterLimit}from"./hooks/useCharacterLimit.js";import{useEditorContainerState}from"./hooks/useEditorContainerState.js";import{useMentionUserSelection}from"./hooks/useMentionUserSelection.js";import{MessageEditorProvider,useMessageEditorContext}from"./message-editor-context.js";import messages from"./messages.js";import{t as message_editor_module_default}from"../../../../../chunks/message-editor2.module.js";import{CharacterLimitCounter}from"./subcomponents/character-limit-counter.js";import{EditButtons}from"./subcomponents/edit-buttons.js";import{ErrorMessage}from"./subcomponents/error-message.js";import{t as MessageEditorBubbleMenu}from"../../../../../chunks/message-editor-bubble-menu.js";import{PostButton}from"./subcomponents/post-button.js";import{t as TimestampToggle}from"../../../../../chunks/timestamp-toggle.js";import{MessageEditorVariant}from"./message-editor.types.js";import{VisuallyHidden}from"@box/blueprint-web";import clsx from"clsx";import{useCallback,useEffect,useMemo,useRef}from"react";import{useIntl}from"react-intl";import{Fragment,jsx,jsxs}from"react/jsx-runtime";import{UserSelectorHeadless}from"@box/user-selector";import{EditorContent,useEditor}from"@tiptap/react";var IS_APPLE_DEVICE=typeof navigator<`u`&&/Mac|iP(hone|ad|od)/.test(navigator.platform),getShortcutFormat=event=>{if(!(IS_APPLE_DEVICE?event.metaKey:event.ctrlKey))return null;if(event.shiftKey)return event.code===`Digit8`?`bulletList`:event.code===`Digit7`?`orderedList`:null;switch(event.key.toLowerCase()){case`b`:return`bold`;case`i`:return`italic`;case`u`:return`underline`;default:return null}},MessageEditorContent=props=>{let{autoFocus=!0,disableComponent=!1,initialContent,isFirstAnnotation=!1,isReply=!1,isRichTextEnabled=!1,maxCharacterCount,onFormatToggle,userSelectorProps,videoTimestamp}=props,userSelectorRef=useRef(null),editorContainerRef=useRef(null),editorViewportRef=useRef(null),editorRef=useRef(null),editorInstanceRef=useRef(null),onFormatToggleRef=useRef(onFormatToggle);onFormatToggleRef.current=onFormatToggle;let intl=useIntl(),{errorMessage,isLoading}=useMessageEditorContext(),{close:closeMentionDropdown,isActive,query,command,suggestionCallbacks}=useMentionState(userSelectorRef),{closeAllPopovers}=useMentionContext(),placeholderText=intl.formatMessage(isReply?messages.placeholderReply:messages.placeholderAddComment),isEditVariant=props.variant===MessageEditorVariant.EDIT_MESSAGE,editor=useEditor({shouldRerenderOnTransaction:!0,extensions:createMessageEditorExtensions({isRichTextEnabled,mentionSuggestion:createSuggestionOptions(MENTION_PLUGIN_KEY,`@`,suggestionCallbacks),placeholder:placeholderText}),autofocus:autoFocus,content:initialContent,editorProps:{attributes:{class:message_editor_module_default.editor},handleKeyDown:(view,event)=>{if(isRichTextEnabled){let format=getShortcutFormat(event),editorInstance=editorInstanceRef.current;if(format&&editorInstance?.isEditable){let wasActive=editorInstance.isActive(format);queueMicrotask(()=>{if(editorInstance.isDestroyed)return;let isFormatActive=editorInstance.isActive(format);isFormatActive!==wasActive&&onFormatToggleRef.current?.(format,isFormatActive)})}}return!1},handleTextInput:normalizeMentionTextInput,transformPastedText:normalizeMentionPastedText},onCreate:({editor:editorInstance})=>{editorInstanceRef.current=editorInstance,editorRef.current=editorInstance.view.dom,autoFocus&&editorInstance.commands.focus(`end`)},onUpdate:()=>{closeAllPopovers?.()}},[placeholderText,isRichTextEnabled]),{onUserSelected}=useMentionUserSelection(useMemo(()=>command&&editor&&!editor.isDestroyed?{command,editor}:null,[command,editor])),{exceedsSingleLine,hasScroll,isAtBottom}=useEditorContainerState(editorContainerRef,editor),characterLimitState=useCharacterLimit(editor,initialContent,maxCharacterCount),shouldApplyEditorFullWidth=isEditVariant||!isFirstAnnotation||isFirstAnnotation&&exceedsSingleLine,isEditorEmpty=!editor||editor?.isEmpty,disableEditor=disableComponent||isLoading,isCharacterLimitExceeded=(characterLimitState?.excess??0)>0,isPostDisabled=isEditorEmpty||disableEditor||isCharacterLimitExceeded,showCharacterLimitCounter=characterLimitState&&characterLimitState.excess>0&&shouldApplyEditorFullWidth;useEffect(()=>{editor&&editor.setEditable(!disableEditor)},[editor,disableEditor]),useEffect(()=>{if(!isCharacterLimitExceeded||!editorContainerRef.current||!initialContent)return;let innerFrameId=0,outerFrameId=requestAnimationFrame(()=>{innerFrameId=requestAnimationFrame(()=>{editorContainerRef.current?.scrollTo({top:editorContainerRef.current.scrollHeight})})});return()=>{cancelAnimationFrame(outerFrameId),cancelAnimationFrame(innerFrameId)}},[isCharacterLimitExceeded]),useEffect(()=>{!editor||initialContent===void 0||queueMicrotask(()=>{editor.isDestroyed||(editor.commands.setContent(initialContent??``,{emitUpdate:!1}),autoFocus&&editor.commands.focus(`end`))})},[initialContent]),useEffect(()=>{if(!isActive)return;let portalSelector=`[${Object.keys(THREADED_ANNOTATIONS_PORTAL)[0]}]`,isInsideEditorOrPortal=target=>{if(editorContainerRef.current?.contains(target))return!0;let portals=document.querySelectorAll(portalSelector);for(let portal of portals)if(portal.contains(target))return!0;return!1},handleClose=e=>{let target=e.target;!target||isInsideEditorOrPortal(target)||closeMentionDropdown()},frameId=requestAnimationFrame(()=>{document.addEventListener(`mousedown`,handleClose),document.addEventListener(`focusin`,handleClose)});return()=>{cancelAnimationFrame(frameId),document.removeEventListener(`mousedown`,handleClose),document.removeEventListener(`focusin`,handleClose)}},[closeMentionDropdown,isActive]);let handleFormatToggle=useCallback((format,isFormatActive)=>onFormatToggleRef.current?.(format,isFormatActive),[]),anchorElement=jsx(`div`,{className:message_editor_module_default.anchorElement});return jsx(`div`,{"data-no-expand":!0,className:message_editor_module_default.messageEditorWrapper,children:jsxs(`div`,{className:clsx(message_editor_module_default.messageEditor,{[message_editor_module_default.editorHasScroll]:hasScroll,[message_editor_module_default.editorEditMode]:isEditVariant,[message_editor_module_default.editorError]:errorMessage||isCharacterLimitExceeded,[message_editor_module_default.editorFirstAnnotation]:!isEditVariant&&isFirstAnnotation,[message_editor_module_default.editorCharacterLimitExceeded]:isCharacterLimitExceeded}),children:[jsxs(`div`,{ref:editorViewportRef,className:clsx(message_editor_module_default.editorViewport,{[message_editor_module_default.editorFullWidth]:shouldApplyEditorFullWidth}),children:[isRichTextEnabled&&jsx(MessageEditorBubbleMenu,{editor,menuAnchorRef:editorViewportRef,onFormatToggle:handleFormatToggle}),jsxs(`div`,{ref:editorContainerRef,className:message_editor_module_default.editorContainer,"aria-label":intl.formatMessage(messages.scrollContainerAriaLabel),children:[jsx(EditorContent,{"aria-label":intl.formatMessage(messages.editorContentAriaLabel),editor}),jsx(UserSelectorHeadless,{ref:userSelectorRef,inputElementRef:editorRef,onSelectedUserChange:onUserSelected,open:isActive,rootElement:anchorElement,value:query,...userSelectorProps,popoverContentContainerProps:{...userSelectorProps.popoverContentContainerProps,...THREADED_ANNOTATIONS_PORTAL,avoidCollisions:!0}})]}),hasScroll&&jsx(`div`,{className:clsx(message_editor_module_default.editorFade,{[message_editor_module_default.editorFadeHidden]:isAtBottom}),"aria-hidden":`true`})]}),jsx(`div`,{className:clsx(message_editor_module_default.actionsWrapper,{[message_editor_module_default.withTimestampToggle]:!!videoTimestamp}),children:jsxs(`div`,{className:clsx(message_editor_module_default.actionsWrapperInner,{[message_editor_module_default.scrolledToBottom]:isAtBottom,[message_editor_module_default.characterLimitExceeded]:isCharacterLimitExceeded}),children:[errorMessage&&jsx(ErrorMessage,{errorMessage}),characterLimitState&&characterLimitState.excess>0&&!shouldApplyEditorFullWidth&&jsx(VisuallyHidden,{role:`alert`,children:intl.formatMessage(messages.characterLimitExceeded,{excess:characterLimitState.excess})}),videoTimestamp&&jsx(TimestampToggle,{className:message_editor_module_default.timestampToggle,disabled:disableEditor,formattedTimestamp:videoTimestamp.formattedTimestamp,isPressed:videoTimestamp.isPressed,onChange:videoTimestamp.onPressedChange}),isEditVariant?jsxs(`div`,{className:message_editor_module_default.editActionsColumn,children:[showCharacterLimitCounter&&jsx(CharacterLimitCounter,{count:characterLimitState.count,excess:characterLimitState.excess,maxCount:characterLimitState.maxCount}),jsx(`div`,{className:message_editor_module_default.editActionsRow,children:jsx(EditButtons,{disabled:isPostDisabled,getEditorJsonContent:()=>editor?.getJSON(),onCancel:props.onEditCancel,onEditSuccess:props.onEditSuccess,onSave:props.onSave,onSaveError:props.onSaveError})})]}):jsxs(Fragment,{children:[showCharacterLimitCounter&&jsx(CharacterLimitCounter,{count:characterLimitState.count,excess:characterLimitState.excess,maxCount:characterLimitState.maxCount}),jsx(PostButton,{cleanEditor:()=>editor?.commands.setContent(``,{emitUpdate:!1}),disabled:isPostDisabled,getEditorJsonContent:()=>editor?.getJSON(),onPost:props.onPost,onPostError:props.onPostError,onPostSuccess:props.onPostSuccess})]})]})})]})})},MessageEditor=props=>jsx(MessageEditorProvider,{children:jsx(MessageEditorContent,{...props})});export{MessageEditor,MessageEditorVariant};
@@ -1 +1 @@
1
- import{defineMessages}from"react-intl";var messages=defineMessages({cancel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.cancel`,defaultMessage:`Cancel`},characterCount:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.characterCount`,defaultMessage:`{count}/{maxCount}`},characterLimitExceeded:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.characterLimitExceeded`,defaultMessage:`Your comment is {excess, plural, one {# character} other {# characters}} too long`},editorContentAriaLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.editorContentAriaLabel`,defaultMessage:`Message editor`},placeholderAddComment:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.placeholderAddComment`,defaultMessage:`Add a comment, @ to mention`},placeholderReply:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.placeholderReply`,defaultMessage:`Reply, @ to mention`},post:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.post`,defaultMessage:`Post`},postLoading:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.postLoading`,defaultMessage:`Loading...`},save:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.save`,defaultMessage:`Save`},saveLoading:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.saveLoading`,defaultMessage:`Saving...`},scrollContainerAriaLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.scrollContainerAriaLabel`,defaultMessage:`Message editor scroll container`},timestampToggleLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.timestampToggleLabel`,defaultMessage:`Comment with timestamp`}});export{messages as default};
1
+ import{defineMessages}from"react-intl";var messages=defineMessages({cancel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.cancel`,defaultMessage:`Cancel`},characterCount:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.characterCount`,defaultMessage:`{count}/{maxCount}`},characterLimitExceeded:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.characterLimitExceeded`,defaultMessage:`Your comment is {excess, plural, one {# character} other {# characters}} too long`},editorContentAriaLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.editorContentAriaLabel`,defaultMessage:`Message editor`},formatBold:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.formatBold`,defaultMessage:`Bold`},formatBulletList:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.formatBulletList`,defaultMessage:`Bullet list`},formatItalic:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.formatItalic`,defaultMessage:`Italic`},formatNumberedList:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.formatNumberedList`,defaultMessage:`Numbered list`},formatUnderline:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.formatUnderline`,defaultMessage:`Underline`},placeholderAddComment:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.placeholderAddComment`,defaultMessage:`Add a comment, @ to mention`},placeholderReply:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.placeholderReply`,defaultMessage:`Reply, @ to mention`},post:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.post`,defaultMessage:`Post`},postLoading:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.postLoading`,defaultMessage:`Loading...`},save:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.save`,defaultMessage:`Save`},saveLoading:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.saveLoading`,defaultMessage:`Saving...`},scrollContainerAriaLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.scrollContainerAriaLabel`,defaultMessage:`Message editor scroll container`},timestampToggleLabel:{id:`groupSharedFeatures.threadedAnnotations.messageEditor.timestampToggleLabel`,defaultMessage:`Comment with timestamp`}});export{messages as default};
@@ -0,0 +1 @@
1
+ import{t as MessageEditorBubbleMenu}from"../../../../../../chunks/message-editor-bubble-menu.js";export{MessageEditorBubbleMenu};
@@ -0,0 +1 @@
1
+ ._bubbleMenu_lm6yy_1{z-index:1}
@@ -39,14 +39,14 @@ interface BaseMessageEditorProps {
39
39
  initialContent?: JSONContent | string | null;
40
40
  /**
41
41
  * When true, enables the rich text experience: bold/italic/underline marks, bullet and numbered
42
- * lists, and their keyboard shortcuts and input rules. Defaults to false. The package has no
43
- * feature-flag mechanism — hosts gate this on their own feature split.
42
+ * lists, the selection formatting bar, and their keyboard shortcuts and input rules. Defaults to
43
+ * false. The package has no feature-flag mechanism — hosts gate this on their own feature split.
44
44
  */
45
45
  isRichTextEnabled?: boolean;
46
46
  /**
47
- * Called when the user toggles a rich text format via a keyboard shortcut. `isActive` is the
48
- * format's state after the toggle. Hosts map this to their own analytics pipelines. Only fires
49
- * when `isRichTextEnabled` is true.
47
+ * Called when the user toggles a rich text format from the formatting bar or a keyboard
48
+ * shortcut. `isActive` is the format's state after the toggle. Hosts map this to their own
49
+ * analytics pipelines. Only fires when `isRichTextEnabled` is true.
50
50
  */
51
51
  onFormatToggle?: (format: RichTextFormat, isActive: boolean) => void;
52
52
  /** Maximum character count. Defaults to 5000. */
@@ -19,6 +19,31 @@ declare const messages: {
19
19
  description: string;
20
20
  id: string;
21
21
  };
22
+ formatBold: {
23
+ defaultMessage: string;
24
+ description: string;
25
+ id: string;
26
+ };
27
+ formatBulletList: {
28
+ defaultMessage: string;
29
+ description: string;
30
+ id: string;
31
+ };
32
+ formatItalic: {
33
+ defaultMessage: string;
34
+ description: string;
35
+ id: string;
36
+ };
37
+ formatNumberedList: {
38
+ defaultMessage: string;
39
+ description: string;
40
+ id: string;
41
+ };
42
+ formatUnderline: {
43
+ defaultMessage: string;
44
+ description: string;
45
+ id: string;
46
+ };
22
47
  placeholderAddComment: {
23
48
  defaultMessage: string;
24
49
  description: string;
@@ -0,0 +1,18 @@
1
+ import { Editor } from '@tiptap/core';
2
+ import { RefObject } from 'react';
3
+ import { RichTextFormat } from '../../../../v2/types';
4
+ interface MessageEditorBubbleMenuProps {
5
+ editor: Editor | null;
6
+ /** Non-scrolling editor viewport wrapper the menu is appended to; avoids clipping when placed above the first line. */
7
+ menuAnchorRef: RefObject<HTMLDivElement | null>;
8
+ /** Called after a format is toggled from the bar. `isActive` is the format's state after the toggle. */
9
+ onFormatToggle?: (format: RichTextFormat, isActive: boolean) => void;
10
+ }
11
+ /**
12
+ * Memoized because the parent MessageEditor re-renders on every TipTap
13
+ * transaction (`shouldRerenderOnTransaction: true`) — an unmemoized menu would
14
+ * re-register the bubble-menu plugin and remount its floating element on every
15
+ * keystroke. Active-format state updates flow through `useEditorState` instead.
16
+ */
17
+ export declare const MessageEditorBubbleMenu: import('react').MemoExoticComponent<({ editor, menuAnchorRef, onFormatToggle }: MessageEditorBubbleMenuProps) => import("react/jsx-runtime").JSX.Element>;
18
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@box/threaded-annotations",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "dependencies": {
6
6
  "@floating-ui/dom": "^1.6.0",