@box/threaded-annotations 4.3.2 → 4.4.1

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.
Files changed (22) hide show
  1. package/dist/chunks/delete-confirmation-popover.js +1 -1
  2. package/dist/chunks/dist.js +1 -1
  3. package/dist/chunks/messages-view.js +1 -1
  4. package/dist/chunks/threaded-annotations2.js +1 -1
  5. package/dist/esm/lib/components/message-editor/editor-extensions/custom-mention/custom-mention-suggestions.js +1 -1
  6. package/dist/esm/lib/components/v2/message-editor/editor-extensions/create-message-editor-extensions.js +1 -0
  7. package/dist/esm/lib/components/v2/message-editor/editor-extensions/custom-mention/custom-mention-suggestions.js +1 -1
  8. package/dist/esm/lib/components/v2/message-editor/editor-extensions/dismiss-selection-on-escape.js +1 -0
  9. package/dist/esm/lib/components/v2/message-editor/editor-extensions/normalize-empty-node-selection.js +1 -0
  10. package/dist/esm/lib/components/v2/message-editor/message-editor.js +1 -1
  11. package/dist/esm/lib/components/v2/text-message/text-message.js +1 -1
  12. package/dist/esm/lib/v2/utils/serialize-mention-markup.js +1 -1
  13. package/dist/types/lib/components/v2/message-editor/editor-extensions/create-message-editor-extensions.d.ts +13 -0
  14. package/dist/types/lib/components/v2/message-editor/editor-extensions/dismiss-selection-on-escape.d.ts +8 -0
  15. package/dist/types/lib/components/v2/message-editor/editor-extensions/normalize-empty-node-selection.d.ts +17 -0
  16. package/dist/types/lib/components/v2/message-editor/message-editor.types.d.ts +14 -2
  17. package/dist/types/lib/components/v2/message-editor/stories/shared.d.ts +3 -0
  18. package/dist/types/lib/components/v2/messages-view/messages-view.d.ts +5 -1
  19. package/dist/types/lib/components/v2/text-message/text-message.d.ts +5 -1
  20. package/dist/types/lib/v2/threaded-annotations.d.ts +11 -0
  21. package/dist/types/lib/v2/utils/serialize-mention-markup.d.ts +6 -0
  22. package/package.json +16 -12
@@ -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}});var 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{PluginKey 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{TextSelection as a,PluginKey as i,NodeSelection as n,Plugin as r,AllSelection as t};
@@ -1 +1 @@
1
- import{ThreadViewState,useThreadedAnnotationsContext}from"../esm/lib/v2/threaded-annotations-context.js";import{t as ResolvedState}from"./resolved-state.js";import{t as ShowRepliesButton}from"./show-replies-button.js";import{TextMessage}from"../esm/lib/components/v2/text-message/text-message.js";import{useAutoScroll}from"../esm/lib/components/v2/messages-view/hooks/useAutoScroll.js";import clsx from"clsx";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/messages-view.css';var messages_view_module_default={messagesViewWrapper:`_messagesViewWrapper_1awp7_29`,overflowing:`_overflowing_1awp7_34`,scrollable:`_scrollable_1awp7_34`,withEditorBelow:`_withEditorBelow_1awp7_37`,messagesView:`_messagesView_1awp7_29`,repliesContainer:`_repliesContainer_1awp7_78`,messagesFade:`_messagesFade_1awp7_84`},MessagesView=({messages,isResolved=!1,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted})=>{let{viewState,dispatch,isAnnotations}=useThreadedAnnotationsContext(),containerRef=useRef(null),isExpanded=viewState!==ThreadViewState.Collapsed,isEditorVisible=viewState===ThreadViewState.Composing,hasHiddenReplies=messages.length>2,repliesHiddenWhileCollapsed=hasHiddenReplies&&!isExpanded,{handleScroll,isOverflowing}=useAutoScroll({messageCount:messages.length,containerRef,enabled:isAnnotations,isExpanded,suppressAutoScroll:repliesHiddenWhileCollapsed}),rootMessage=messages[0],replies=messages.slice(1),hasReplies=replies.length>=1,lastReply=replies[replies.length-1],middleReplies=replies.slice(0,-1),showRepliesButton=hasHiddenReplies&&!isExpanded;if(!rootMessage)return null;let buttonLastUser=middleReplies[middleReplies.length-1]?.author,buttonSecondLastUser=middleReplies.length>=2?middleReplies[middleReplies.length-2].author:void 0,handleShowReplies=()=>dispatch({type:`EXPAND`});return jsxs(`div`,{className:clsx(messages_view_module_default.messagesViewWrapper,isOverflowing&&messages_view_module_default.overflowing,isOverflowing&&isEditorVisible&&messages_view_module_default.withEditorBelow),children:[jsxs(`div`,{ref:containerRef,className:clsx(messages_view_module_default.messagesView,isAnnotations&&messages_view_module_default.scrollable),onScroll:handleScroll,children:[jsx(TextMessage,{...rootMessage,hasReplies,showThreadedIndicator:hasReplies||isResolved,isResolved,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isFirstMessage:!0,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted}),showRepliesButton&&buttonLastUser&&jsx(ShowRepliesButton,{lastUser:buttonLastUser,repliesCount:middleReplies.length,secondLastUser:buttonSecondLastUser,onShowReplies:handleShowReplies}),isExpanded&&middleReplies.length>0&&jsx(`div`,{className:messages_view_module_default.repliesContainer,children:middleReplies.map(reply=>jsx(TextMessage,{...reply,showThreadedIndicator:!0,isResolved,maxCharacterCount,onDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,userSelectorProps},reply.id))}),lastReply&&jsx(TextMessage,{...lastReply,showThreadedIndicator:isResolved,isResolved,maxCharacterCount,onDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,userSelectorProps}),isResolved&&resolvedBy&&resolvedAt&&jsx(ResolvedState,{authorName:resolvedBy,createdAt:resolvedAt})]}),isOverflowing&&jsx(`div`,{className:messages_view_module_default.messagesFade})]})};export{MessagesView as t};
1
+ import{ThreadViewState,useThreadedAnnotationsContext}from"../esm/lib/v2/threaded-annotations-context.js";import{t as ResolvedState}from"./resolved-state.js";import{t as ShowRepliesButton}from"./show-replies-button.js";import{TextMessage}from"../esm/lib/components/v2/text-message/text-message.js";import{useAutoScroll}from"../esm/lib/components/v2/messages-view/hooks/useAutoScroll.js";import clsx from"clsx";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/messages-view.css';var messages_view_module_default={messagesViewWrapper:`_messagesViewWrapper_1awp7_29`,overflowing:`_overflowing_1awp7_34`,scrollable:`_scrollable_1awp7_34`,withEditorBelow:`_withEditorBelow_1awp7_37`,messagesView:`_messagesView_1awp7_29`,repliesContainer:`_repliesContainer_1awp7_78`,messagesFade:`_messagesFade_1awp7_84`},MessagesView=({messages,isResolved=!1,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isRichTextEnabled=!1,onFormatToggle,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted})=>{let{viewState,dispatch,isAnnotations}=useThreadedAnnotationsContext(),containerRef=useRef(null),isExpanded=viewState!==ThreadViewState.Collapsed,isEditorVisible=viewState===ThreadViewState.Composing,hasHiddenReplies=messages.length>2,repliesHiddenWhileCollapsed=hasHiddenReplies&&!isExpanded,{handleScroll,isOverflowing}=useAutoScroll({messageCount:messages.length,containerRef,enabled:isAnnotations,isExpanded,suppressAutoScroll:repliesHiddenWhileCollapsed}),rootMessage=messages[0],replies=messages.slice(1),hasReplies=replies.length>=1,lastReply=replies[replies.length-1],middleReplies=replies.slice(0,-1),showRepliesButton=hasHiddenReplies&&!isExpanded;if(!rootMessage)return null;let buttonLastUser=middleReplies[middleReplies.length-1]?.author,buttonSecondLastUser=middleReplies.length>=2?middleReplies[middleReplies.length-2].author:void 0,handleShowReplies=()=>dispatch({type:`EXPAND`});return jsxs(`div`,{className:clsx(messages_view_module_default.messagesViewWrapper,isOverflowing&&messages_view_module_default.overflowing,isOverflowing&&isEditorVisible&&messages_view_module_default.withEditorBelow),children:[jsxs(`div`,{ref:containerRef,className:clsx(messages_view_module_default.messagesView,isAnnotations&&messages_view_module_default.scrollable),onScroll:handleScroll,children:[jsx(TextMessage,{...rootMessage,hasReplies,showThreadedIndicator:hasReplies||isResolved,isResolved,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isFirstMessage:!0,isRichTextEnabled,onFormatToggle,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted}),showRepliesButton&&buttonLastUser&&jsx(ShowRepliesButton,{lastUser:buttonLastUser,repliesCount:middleReplies.length,secondLastUser:buttonSecondLastUser,onShowReplies:handleShowReplies}),isExpanded&&middleReplies.length>0&&jsx(`div`,{className:messages_view_module_default.repliesContainer,children:middleReplies.map(reply=>jsx(TextMessage,{...reply,showThreadedIndicator:!0,isResolved,maxCharacterCount,onDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isRichTextEnabled,onFormatToggle,userSelectorProps},reply.id))}),lastReply&&jsx(TextMessage,{...lastReply,showThreadedIndicator:isResolved,isResolved,maxCharacterCount,onDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isRichTextEnabled,onFormatToggle,userSelectorProps}),isResolved&&resolvedBy&&resolvedAt&&jsx(ResolvedState,{authorName:resolvedBy,createdAt:resolvedAt})]}),isOverflowing&&jsx(`div`,{className:messages_view_module_default.messagesFade})]})};export{MessagesView as t};
@@ -1 +1 @@
1
- import{THREADED_ANNOTATIONS_PORTAL}from"../esm/lib/v2/constants.js";import{MessageEditor}from"../esm/lib/components/v2/message-editor/message-editor.js";import{ThreadViewState,ThreadedAnnotationsProvider,useThreadedAnnotationsContext}from"../esm/lib/v2/threaded-annotations-context.js";import{t as MessagesView}from"./messages-view.js";import{buildMentionContent}from"../esm/lib/v2/utils/build-mention-content.js";import clsx from"clsx";import{useCallback,useEffect,useMemo,useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/threaded-annotations2.css';var threaded_annotations_module_default={threadedAnnotations:`_threadedAnnotations_16hhz_1`,expandable:`_expandable_16hhz_10`,annotations:`_annotations_16hhz_18`,highlighted:`_highlighted_16hhz_18`},ThreadedAnnotationsContent=({messages:messageList,isResolved=!1,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,onPost,onPostError,userSelectorProps,onEditorOpenChange,annotationTarget,onAnnotationBadgeClick,originalContentDeleted,isHighlighted=!1,autoFocusReplyEditor=!0})=>{let{viewState,dispatch,editingMessageId,replyMention,isReplyDisabled,isAnnotations}=useThreadedAnnotationsContext(),containerRef=useRef(null),isExpanded=viewState!==ThreadViewState.Collapsed,hasHiddenReplies=messageList.length>2,isExpandable=viewState===ThreadViewState.Collapsed&&(hasHiddenReplies||!isReplyDisabled&&!isResolved);useEffect(()=>{editingMessageId&&!messageList.some(message=>message.id===editingMessageId)&&dispatch({type:`CLEAR_EDIT`})},[editingMessageId,messageList,dispatch]),useEffect(()=>{onEditorOpenChange?.(isExpanded)},[isExpanded,onEditorOpenChange]),useEffect(()=>{if(!isExpanded)return;let portalSelector=`[${Object.keys(THREADED_ANNOTATIONS_PORTAL)[0]}]`,handleClickOutside=e=>{let target=e.target;containerRef.current?.contains(target)||document.querySelector(portalSelector)?.contains(target)||dispatch({type:`COLLAPSE`})};return document.addEventListener(`mousedown`,handleClickOutside),()=>document.removeEventListener(`mousedown`,handleClickOutside)},[isExpanded,dispatch]);let hasNoMessages=messageList.length===0,handleClearMention=useCallback(()=>dispatch({type:`CLEAR_MENTION`}),[dispatch]),initialReplyContent=useMemo(()=>replyMention?buildMentionContent(replyMention):null,[replyMention]),handleClick=useCallback(e=>{if(!isExpandable)return;let target=e.target;!e.currentTarget.contains(target)||target.closest(`[data-no-expand]`)||dispatch({type:`EXPAND`})},[isExpandable,dispatch]);return isAnnotations&&hasNoMessages?jsx(MessageEditor,{isFirstAnnotation:!0,maxCharacterCount,onPost,onPostError,onPostSuccess:handleClearMention,userSelectorProps}):jsxs(`div`,{ref:containerRef,className:clsx(threaded_annotations_module_default.threadedAnnotations,isExpandable&&threaded_annotations_module_default.expandable,isAnnotations&&threaded_annotations_module_default.annotations,isHighlighted&&threaded_annotations_module_default.highlighted),"data-thread-expandable":isExpandable?!0:void 0,"data-thread-highlighted":isHighlighted?!0:void 0,onClick:isExpandable?handleClick:void 0,children:[jsx(MessagesView,{messages:messageList,isResolved,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted}),viewState===ThreadViewState.Composing&&jsx(MessageEditor,{autoFocus:autoFocusReplyEditor,initialContent:initialReplyContent,maxCharacterCount,onPost,onPostError,onPostSuccess:handleClearMention,isReply:!0,userSelectorProps})]})},ThreadedAnnotations=props=>jsx(ThreadedAnnotationsProvider,{defaultExpanded:props.defaultExpanded||props.messages.length===0,isReplyDisabled:props.isReplyDisabled||props.isResolved,isEditDisabled:props.isEditDisabled||props.isResolved,isAnnotations:props.isAnnotations,collapsed:props.collapsed,children:jsx(ThreadedAnnotationsContent,{...props})});export{ThreadedAnnotations as t};
1
+ import{THREADED_ANNOTATIONS_PORTAL}from"../esm/lib/v2/constants.js";import{MessageEditor}from"../esm/lib/components/v2/message-editor/message-editor.js";import{ThreadViewState,ThreadedAnnotationsProvider,useThreadedAnnotationsContext}from"../esm/lib/v2/threaded-annotations-context.js";import{t as MessagesView}from"./messages-view.js";import{buildMentionContent}from"../esm/lib/v2/utils/build-mention-content.js";import clsx from"clsx";import{useCallback,useEffect,useMemo,useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";import '../styles/threaded-annotations2.css';var threaded_annotations_module_default={threadedAnnotations:`_threadedAnnotations_16hhz_1`,expandable:`_expandable_16hhz_10`,annotations:`_annotations_16hhz_18`,highlighted:`_highlighted_16hhz_18`},ThreadedAnnotationsContent=({messages:messageList,isResolved=!1,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,onPost,onPostError,isRichTextEnabled=!1,onFormatToggle,userSelectorProps,onEditorOpenChange,annotationTarget,onAnnotationBadgeClick,originalContentDeleted,isHighlighted=!1,autoFocusReplyEditor=!0})=>{let{viewState,dispatch,editingMessageId,replyMention,isReplyDisabled,isAnnotations}=useThreadedAnnotationsContext(),containerRef=useRef(null),isExpanded=viewState!==ThreadViewState.Collapsed,hasHiddenReplies=messageList.length>2,isExpandable=viewState===ThreadViewState.Collapsed&&(hasHiddenReplies||!isReplyDisabled&&!isResolved);useEffect(()=>{editingMessageId&&!messageList.some(message=>message.id===editingMessageId)&&dispatch({type:`CLEAR_EDIT`})},[editingMessageId,messageList,dispatch]),useEffect(()=>{onEditorOpenChange?.(isExpanded)},[isExpanded,onEditorOpenChange]),useEffect(()=>{if(!isExpanded)return;let portalSelector=`[${Object.keys(THREADED_ANNOTATIONS_PORTAL)[0]}]`,handleClickOutside=e=>{let target=e.target;containerRef.current?.contains(target)||document.querySelector(portalSelector)?.contains(target)||dispatch({type:`COLLAPSE`})};return document.addEventListener(`mousedown`,handleClickOutside),()=>document.removeEventListener(`mousedown`,handleClickOutside)},[isExpanded,dispatch]);let hasNoMessages=messageList.length===0,handleClearMention=useCallback(()=>dispatch({type:`CLEAR_MENTION`}),[dispatch]),initialReplyContent=useMemo(()=>replyMention?buildMentionContent(replyMention):null,[replyMention]),handleClick=useCallback(e=>{if(!isExpandable)return;let target=e.target;!e.currentTarget.contains(target)||target.closest(`[data-no-expand]`)||dispatch({type:`EXPAND`})},[isExpandable,dispatch]);return isAnnotations&&hasNoMessages?jsx(MessageEditor,{isFirstAnnotation:!0,isRichTextEnabled,maxCharacterCount,onFormatToggle,onPost,onPostError,onPostSuccess:handleClearMention,userSelectorProps}):jsxs(`div`,{ref:containerRef,className:clsx(threaded_annotations_module_default.threadedAnnotations,isExpandable&&threaded_annotations_module_default.expandable,isAnnotations&&threaded_annotations_module_default.annotations,isHighlighted&&threaded_annotations_module_default.highlighted),"data-thread-expandable":isExpandable?!0:void 0,"data-thread-highlighted":isHighlighted?!0:void 0,onClick:isExpandable?handleClick:void 0,children:[jsx(MessagesView,{messages:messageList,isResolved,resolvedBy,resolvedAt,maxCharacterCount,onDelete,onThreadDelete,onAvatarClick,onCopyLink,onEdit,onEditError,onResolve,onUnresolve,isRichTextEnabled,onFormatToggle,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted}),viewState===ThreadViewState.Composing&&jsx(MessageEditor,{autoFocus:autoFocusReplyEditor,initialContent:initialReplyContent,isRichTextEnabled,maxCharacterCount,onFormatToggle,onPost,onPostError,onPostSuccess:handleClearMention,isReply:!0,userSelectorProps})]})},ThreadedAnnotations=props=>jsx(ThreadedAnnotationsProvider,{defaultExpanded:props.defaultExpanded||props.messages.length===0,isReplyDisabled:props.isReplyDisabled||props.isResolved,isEditDisabled:props.isEditDisabled||props.isResolved,isAnnotations:props.isAnnotations,collapsed:props.collapsed,children:jsx(ThreadedAnnotationsContent,{...props})});export{ThreadedAnnotations as t};
@@ -1 +1 @@
1
- import{t as PluginKey}from"../../../../../../chunks/dist.js";var createSuggestionOptions=(pluginKeyName,char,callbacks)=>({char,pluginKey:new PluginKey(pluginKeyName),allowSpaces:!0,allow:props=>{let{from,to}=props.range,text=props.state.doc.textBetween(from+1,to,null,``),isSpaceFirstCharacter=text.startsWith(` `),hasDoubleSpace=text.includes(` `);return!isSpaceFirstCharacter&&!hasDoubleSpace},render:()=>({onStart:props=>{callbacks?.onSuggestionStart(props)},onUpdate:props=>{callbacks?.onSuggestionUpdate(props)},onKeyDown:props=>props.event.key===`Escape`?(callbacks?.onSuggestionExit(),!0):callbacks?.onSuggestionKeyDown(props)??!1,onExit:()=>{callbacks?.onSuggestionExit()}})});export{createSuggestionOptions};
1
+ import{i as PluginKey}from"../../../../../../chunks/dist.js";var createSuggestionOptions=(pluginKeyName,char,callbacks)=>({char,pluginKey:new PluginKey(pluginKeyName),allowSpaces:!0,allow:props=>{let{from,to}=props.range,text=props.state.doc.textBetween(from+1,to,null,``),isSpaceFirstCharacter=text.startsWith(` `),hasDoubleSpace=text.includes(` `);return!isSpaceFirstCharacter&&!hasDoubleSpace},render:()=>({onStart:props=>{callbacks?.onSuggestionStart(props)},onUpdate:props=>{callbacks?.onSuggestionUpdate(props)},onKeyDown:props=>props.event.key===`Escape`?(callbacks?.onSuggestionExit(),!0):callbacks?.onSuggestionKeyDown(props)??!1,onExit:()=>{callbacks?.onSuggestionExit()}})});export{createSuggestionOptions};
@@ -0,0 +1 @@
1
+ import{CustomMention}from"./custom-mention/custom-mention.js";import{CustomParagraph}from"./custom-paragraph.js";import{DismissSelectionOnEscape}from"./dismiss-selection-on-escape.js";import{NormalizeEmptyNodeSelection}from"./normalize-empty-node-selection.js";import Document from"@tiptap/extension-document";import Text from"@tiptap/extension-text";import Bold from"@tiptap/extension-bold";import Italic from"@tiptap/extension-italic";import{BulletList,ListItem,OrderedList}from"@tiptap/extension-list";import Underline from"@tiptap/extension-underline";import{Placeholder}from"@tiptap/extensions";var createMessageEditorExtensions=({isRichTextEnabled,mentionSuggestion,placeholder})=>{let baseExtensions=[Document,CustomParagraph,Placeholder.configure({placeholder,showOnlyWhenEditable:!1}),Text,CustomMention.configure({suggestion:mentionSuggestion})];return isRichTextEnabled?[...baseExtensions,Bold,Italic,Underline,BulletList.configure({keepMarks:!0}),OrderedList.configure({keepMarks:!0}),ListItem,NormalizeEmptyNodeSelection,DismissSelectionOnEscape]:baseExtensions};export{createMessageEditorExtensions};
@@ -1 +1 @@
1
- import{t as PluginKey}from"../../../../../../../chunks/dist.js";var createSuggestionOptions=(pluginKeyName,char,callbacks)=>({char,pluginKey:new PluginKey(pluginKeyName),allowSpaces:!0,allow:props=>{let{from,to}=props.range,text=props.state.doc.textBetween(from+1,to,null,``),isSpaceFirstCharacter=text.startsWith(` `),hasDoubleSpace=text.includes(` `);return!isSpaceFirstCharacter&&!hasDoubleSpace},render:()=>({onStart:props=>{callbacks?.onSuggestionStart(props)},onUpdate:props=>{callbacks?.onSuggestionUpdate(props)},onKeyDown:props=>props.event.key===`Escape`?(callbacks?.onSuggestionExit(),!0):callbacks?.onSuggestionKeyDown(props)??!1,onExit:()=>{callbacks?.onSuggestionExit()}})});export{createSuggestionOptions};
1
+ import{i as PluginKey}from"../../../../../../../chunks/dist.js";var createSuggestionOptions=(pluginKeyName,char,callbacks)=>({char,pluginKey:new PluginKey(pluginKeyName),allowSpaces:!0,allow:props=>{let{from,to}=props.range,text=props.state.doc.textBetween(from+1,to,null,``),isSpaceFirstCharacter=text.startsWith(` `),hasDoubleSpace=text.includes(` `);return!isSpaceFirstCharacter&&!hasDoubleSpace},render:()=>({onStart:props=>{callbacks?.onSuggestionStart(props)},onUpdate:props=>{callbacks?.onSuggestionUpdate(props)},onKeyDown:props=>props.event.key===`Escape`?(callbacks?.onSuggestionExit(),!0):callbacks?.onSuggestionKeyDown(props)??!1,onExit:()=>{callbacks?.onSuggestionExit()}})});export{createSuggestionOptions};
@@ -0,0 +1 @@
1
+ import{Extension}from"@tiptap/core";var DismissSelectionOnEscape=Extension.create({name:`dismissSelectionOnEscape`,addKeyboardShortcuts(){return{Escape:({editor})=>{let{empty,to}=editor.state.selection;return empty?!1:editor.commands.setTextSelection(to)}}}});export{DismissSelectionOnEscape};
@@ -0,0 +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 +1 @@
1
- import{THREADED_ANNOTATIONS_PORTAL}from"../../../v2/constants.js";import{useMentionContext}from"../../mention-component/mention-context.js";import{CustomMention}from"./editor-extensions/custom-mention/custom-mention.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{CustomParagraph}from"./editor-extensions/custom-paragraph.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";import Document from"@tiptap/extension-document";import Text$1 from"@tiptap/extension-text";import{Placeholder}from"@tiptap/extensions";var MessageEditorContent=props=>{let{autoFocus=!0,disableComponent=!1,initialContent,isFirstAnnotation=!1,isReply=!1,maxCharacterCount,userSelectorProps,videoTimestamp}=props,userSelectorRef=useRef(null),editorContainerRef=useRef(null),editorRef=useRef(null),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:[Document,CustomParagraph,Placeholder.configure({placeholder:placeholderText,showOnlyWhenEditable:!1}),Text$1,CustomMention.configure({suggestion:createSuggestionOptions(MENTION_PLUGIN_KEY,`@`,suggestionCallbacks)})],autofocus:autoFocus,content:initialContent,editorProps:{attributes:{class:message_editor_module_default.editor},handleTextInput:normalizeMentionTextInput,transformPastedText:normalizeMentionPastedText},onCreate:({editor:editorInstance})=>{editorRef.current=editorInstance.view.dom,autoFocus&&editorInstance.commands.focus(`end`)},onUpdate:()=>{closeAllPopovers?.()}},[placeholderText]),{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{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 +1 @@
1
- import{THREADED_ANNOTATIONS_RESIN_COMPONENTS}from"../../../v2/resin-targets.js";import{MessageEditorVariant}from"../message-editor/message-editor.types.js";import{MessageEditor}from"../message-editor/message-editor.js";import{useThreadedAnnotationsContext}from"../../../v2/threaded-annotations-context.js";import{t as AnnotationBadge}from"../../../../../chunks/annotation-badge.js";import{MessageHeader}from"../message-header/message-header.js";import messages from"./messages.js";import{t as text_message_module_default}from"../../../../../chunks/text-message.module.js";import{MessageFooter}from"./subcomponents/message-footer.js";import{MessageRenderer}from"./subcomponents/message-renderer.js";import clsx from"clsx";import{useIntl}from"react-intl";import{Fragment,jsx,jsxs}from"react/jsx-runtime";var TextMessage=({id,author,message,createdAt,updatedAt,permissions,showThreadedIndicator=!0,isResolved=!1,isFirstMessage=!1,hasReplies=!1,maxCharacterCount,onAvatarClick,onCopyLink,onDelete,onThreadDelete,onEdit,onEditError,onResolve,onUnresolve,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted})=>{let{canResolve,canEdit,canDelete}=permissions,intl=useIntl(),{dispatch,isReplyDisabled,isEditDisabled,isAnnotations,editingMessageId}=useThreadedAnnotationsContext(),isEditing=editingMessageId===id,canOpenEdit=!!onEdit&&!isEditDisabled&&canEdit;return jsxs(`div`,{"aria-label":intl.formatMessage(messages.annotationMessageAriaLabel),className:text_message_module_default.textMessage,"data-message-wrapper":!0,"data-message-id":id,"data-resin-component":THREADED_ANNOTATIONS_RESIN_COMPONENTS.COMMENT_CARD,children:[jsx(MessageHeader,{author,canResolve,isResolved,canDelete,canEdit:canOpenEdit,hasReplies,isFirstMessage,onAvatarClick,onCopyLink:onCopyLink?()=>onCopyLink(id):void 0,onDelete:()=>onDelete(id),onThreadDelete,onEdit:canOpenEdit?()=>dispatch({type:`EDIT`,id}):void 0,onResolve:onResolve?()=>onResolve(id):void 0,onUnresolve:onUnresolve?()=>onUnresolve(id):void 0}),jsxs(`div`,{className:text_message_module_default.contentWrapper,children:[jsx(`div`,{className:clsx(text_message_module_default.threadedIndicator,!showThreadedIndicator&&text_message_module_default.threadedIndicatorHidden)}),jsxs(`div`,{className:text_message_module_default.messageContent,children:[annotationTarget&&!isAnnotations&&jsx(`div`,{className:text_message_module_default.annotationBadgeWrapper,children:jsx(AnnotationBadge,{annotationTarget,onClick:()=>onAnnotationBadgeClick?.(id),originalContentDeleted})}),isEditing&&onEdit?jsx(`div`,{className:text_message_module_default.inlineEditSlot,children:jsx(MessageEditor,{initialContent:message,maxCharacterCount,onEditCancel:()=>dispatch({type:`CLEAR_EDIT`}),onEditSuccess:()=>dispatch({type:`CLEAR_EDIT`}),onSave:content=>onEdit(id,content),onSaveError:onEditError,userSelectorProps,variant:MessageEditorVariant.EDIT_MESSAGE})}):jsxs(Fragment,{children:[jsx(`div`,{"data-message-body":!0,children:jsx(MessageRenderer,{messageObject:message})}),jsx(MessageFooter,{createdAt,onReply:isReplyDisabled?void 0:()=>dispatch({type:`REPLY`,author}),updatedAt})]})]})]})]})};export{TextMessage};
1
+ import{THREADED_ANNOTATIONS_RESIN_COMPONENTS}from"../../../v2/resin-targets.js";import{MessageEditorVariant}from"../message-editor/message-editor.types.js";import{MessageEditor}from"../message-editor/message-editor.js";import{useThreadedAnnotationsContext}from"../../../v2/threaded-annotations-context.js";import{t as AnnotationBadge}from"../../../../../chunks/annotation-badge.js";import{MessageHeader}from"../message-header/message-header.js";import messages from"./messages.js";import{t as text_message_module_default}from"../../../../../chunks/text-message.module.js";import{MessageFooter}from"./subcomponents/message-footer.js";import{MessageRenderer}from"./subcomponents/message-renderer.js";import clsx from"clsx";import{useIntl}from"react-intl";import{Fragment,jsx,jsxs}from"react/jsx-runtime";var TextMessage=({id,author,message,createdAt,updatedAt,permissions,showThreadedIndicator=!0,isResolved=!1,isFirstMessage=!1,hasReplies=!1,maxCharacterCount,onAvatarClick,onCopyLink,onDelete,onThreadDelete,onEdit,onEditError,onResolve,onUnresolve,isRichTextEnabled=!1,onFormatToggle,userSelectorProps,annotationTarget,onAnnotationBadgeClick,originalContentDeleted})=>{let{canResolve,canEdit,canDelete}=permissions,intl=useIntl(),{dispatch,isReplyDisabled,isEditDisabled,isAnnotations,editingMessageId}=useThreadedAnnotationsContext(),isEditing=editingMessageId===id,canOpenEdit=!!onEdit&&!isEditDisabled&&canEdit;return jsxs(`div`,{"aria-label":intl.formatMessage(messages.annotationMessageAriaLabel),className:text_message_module_default.textMessage,"data-message-wrapper":!0,"data-message-id":id,"data-resin-component":THREADED_ANNOTATIONS_RESIN_COMPONENTS.COMMENT_CARD,children:[jsx(MessageHeader,{author,canResolve,isResolved,canDelete,canEdit:canOpenEdit,hasReplies,isFirstMessage,onAvatarClick,onCopyLink:onCopyLink?()=>onCopyLink(id):void 0,onDelete:()=>onDelete(id),onThreadDelete,onEdit:canOpenEdit?()=>dispatch({type:`EDIT`,id}):void 0,onResolve:onResolve?()=>onResolve(id):void 0,onUnresolve:onUnresolve?()=>onUnresolve(id):void 0}),jsxs(`div`,{className:text_message_module_default.contentWrapper,children:[jsx(`div`,{className:clsx(text_message_module_default.threadedIndicator,!showThreadedIndicator&&text_message_module_default.threadedIndicatorHidden)}),jsxs(`div`,{className:text_message_module_default.messageContent,children:[annotationTarget&&!isAnnotations&&jsx(`div`,{className:text_message_module_default.annotationBadgeWrapper,children:jsx(AnnotationBadge,{annotationTarget,onClick:()=>onAnnotationBadgeClick?.(id),originalContentDeleted})}),isEditing&&onEdit?jsx(`div`,{className:text_message_module_default.inlineEditSlot,children:jsx(MessageEditor,{initialContent:message,isRichTextEnabled,maxCharacterCount,onFormatToggle,onEditCancel:()=>dispatch({type:`CLEAR_EDIT`}),onEditSuccess:()=>dispatch({type:`CLEAR_EDIT`}),onSave:content=>onEdit(id,content),onSaveError:onEditError,userSelectorProps,variant:MessageEditorVariant.EDIT_MESSAGE})}):jsxs(Fragment,{children:[jsx(`div`,{"data-message-body":!0,children:jsx(MessageRenderer,{messageObject:message})}),jsx(MessageFooter,{createdAt,onReply:isReplyDisabled?void 0:()=>dispatch({type:`REPLY`,author}),updatedAt})]})]})]})]})};export{TextMessage};
@@ -1,2 +1,2 @@
1
- var serializeMentionMarkup=doc=>{if(!doc||!doc.content)return{hasMention:!1,text:``};let hasMention=!1,text=doc.content.map(paragraph=>paragraph.content?paragraph.content.map(node=>node.type===`mention`?(hasMention=!0,serializeMention(node)):serializeText(node)).join(``):``).join(`
1
+ var serializeMentionMarkup=doc=>{if(!doc||!doc.content)return{hasMention:!1,text:``};let hasMention=!1,serializeParagraph=paragraph=>paragraph.content?paragraph.content.map(node=>node.type===`mention`?(hasMention=!0,serializeMention(node)):serializeText(node)).join(``):``,serializeListItem=item=>(item.content??[]).flatMap(block=>serializeBlock(block)),serializeBlock=block=>block.type===`bulletList`||block.type===`orderedList`?(block.content??[]).flatMap(serializeListItem):[serializeParagraph(block)],text=doc.content.flatMap(block=>serializeBlock(block)).join(`
2
2
  `);return{hasMention,text}},serializeMention=node=>`@[${node.attrs.mentionedUserId}:${node.attrs.mentionedUserName}]`,serializeText=node=>node.text;export{serializeMentionMarkup};
@@ -0,0 +1,13 @@
1
+ import { Extensions } from '@tiptap/core';
2
+ import { SuggestionOptions } from '@tiptap/suggestion';
3
+ export interface CreateMessageEditorExtensionsOptions {
4
+ /**
5
+ * When true, adds the rich text mark and list extensions (bold, italic,
6
+ * underline, bullet/ordered lists), enabling their keyboard shortcuts and
7
+ * input rules. When false the editor supports plain text and mentions only.
8
+ */
9
+ isRichTextEnabled: boolean;
10
+ mentionSuggestion: Omit<SuggestionOptions, 'editor'>;
11
+ placeholder: string;
12
+ }
13
+ export declare const createMessageEditorExtensions: ({ isRichTextEnabled, mentionSuggestion, placeholder, }: CreateMessageEditorExtensionsOptions) => Extensions;
@@ -0,0 +1,8 @@
1
+ import { Extension } from '@tiptap/core';
2
+ /**
3
+ * Escape dismisses the selection-driven formatting bar by collapsing the
4
+ * selection to a caret — the bar only shows for selections containing text.
5
+ * Escape presses while focus is inside the bar are handled by the bar itself
6
+ * (editor keymaps cannot see them).
7
+ */
8
+ export declare const DismissSelectionOnEscape: Extension<any, any>;
@@ -0,0 +1,17 @@
1
+ import { Extension } from '@tiptap/core';
2
+ /**
3
+ * Select-all + delete leaves a node/all selection over the empty paragraph
4
+ * instead of a collapsed caret. In that state mark shortcuts (Cmd/Ctrl+B/I/U)
5
+ * are silent no-ops: toggleMark applies to the selected range (zero text)
6
+ * rather than setting stored marks for the next input, so "format before
7
+ * typing" breaks until the user clicks again. The browser also paints a
8
+ * selection highlight over the empty paragraph.
9
+ *
10
+ * This plugin normalizes two selection shapes into a caret:
11
+ * - a NodeSelection on an empty textblock;
12
+ * - an AllSelection over a truly empty doc (a single empty textblock).
13
+ *
14
+ * Selections that actually contain content — including mention chips (inline
15
+ * atoms) and all-selections over non-empty docs — are left untouched.
16
+ */
17
+ export declare const NormalizeEmptyNodeSelection: Extension<any, any>;
@@ -1,6 +1,6 @@
1
- import { HeadlessUserSelectorProps } from '@box/user-selector';
2
1
  import { JSONContent } from '@tiptap/react';
3
- import { TextMessageType } from '../../../v2/types';
2
+ import { HeadlessUserSelectorProps } from '@box/user-selector';
3
+ import { RichTextFormat, TextMessageType } from '../../../v2/types';
4
4
  export declare enum MessageEditorVariant {
5
5
  CREATE_MESSAGE = "CREATE_MESSAGE",
6
6
  EDIT_MESSAGE = "EDIT_MESSAGE"
@@ -37,6 +37,18 @@ interface BaseMessageEditorProps {
37
37
  isReply?: boolean;
38
38
  /** Optional initial editor content used to prefill the editor (both edit and post modes). */
39
39
  initialContent?: JSONContent | string | null;
40
+ /**
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.
44
+ */
45
+ isRichTextEnabled?: boolean;
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.
50
+ */
51
+ onFormatToggle?: (format: RichTextFormat, isActive: boolean) => void;
40
52
  /** Maximum character count. Defaults to 5000. */
41
53
  maxCharacterCount?: number;
42
54
  /** Properties for the user selector component from blueprint-web. */
@@ -1,6 +1,9 @@
1
1
  import { UserContactType } from '@box/user-selector';
2
+ import { JSONContent } from '@tiptap/react';
2
3
  import { MessageEditorProps } from '../message-editor';
3
4
  export declare const defaultUserSelectorProps: Omit<import('@box/user-selector').HeadlessUserSelectorProps, "value" | "open" | "rootElement" | "onSelectedUserChange" | "inputElementRef">;
5
+ /** Document exercising every rich text format: the three marks plus both list types. */
6
+ export declare const RICH_TEXT_INITIAL_CONTENT: JSONContent;
4
7
  type DefaultMessageEditorProps = MessageEditorProps & {
5
8
  fetchCollaboratorState?: (user: UserContactType) => Promise<boolean>;
6
9
  };
@@ -16,9 +16,13 @@ export interface MessagesViewProps {
16
16
  onEditError?: (error: unknown) => string | undefined;
17
17
  onResolve?: (id: string) => void;
18
18
  onUnresolve?: (id: string) => void;
19
+ /** When true, enables the rich text experience in the edit-mode composer. Defaults to false. */
20
+ isRichTextEnabled?: boolean;
21
+ /** Called when a rich text format is toggled in the edit-mode composer. */
22
+ onFormatToggle?: MessageEditorProps['onFormatToggle'];
19
23
  userSelectorProps: MessageEditorProps['userSelectorProps'];
20
24
  annotationTarget?: AnnotationBadgeTargetType;
21
25
  onAnnotationBadgeClick?: (id: string) => void;
22
26
  originalContentDeleted?: boolean;
23
27
  }
24
- export declare const MessagesView: ({ messages, isResolved, resolvedBy, resolvedAt, maxCharacterCount, onDelete, onThreadDelete, onAvatarClick, onCopyLink, onEdit, onEditError, onResolve, onUnresolve, userSelectorProps, annotationTarget, onAnnotationBadgeClick, originalContentDeleted, }: MessagesViewProps) => import("react/jsx-runtime").JSX.Element;
28
+ export declare const MessagesView: ({ messages, isResolved, resolvedBy, resolvedAt, maxCharacterCount, onDelete, onThreadDelete, onAvatarClick, onCopyLink, onEdit, onEditError, onResolve, onUnresolve, isRichTextEnabled, onFormatToggle, userSelectorProps, annotationTarget, onAnnotationBadgeClick, originalContentDeleted, }: MessagesViewProps) => import("react/jsx-runtime").JSX.Element;
@@ -20,6 +20,10 @@ export interface TextMessageProps extends TextMessageType {
20
20
  onEditError?: (error: unknown) => string | undefined;
21
21
  onResolve?: (id: string) => void;
22
22
  onUnresolve?: (id: string) => void;
23
+ /** When true, enables the rich text experience in the edit-mode composer. Defaults to false. */
24
+ isRichTextEnabled?: boolean;
25
+ /** Called when a rich text format is toggled in the edit-mode composer. */
26
+ onFormatToggle?: MessageEditorProps['onFormatToggle'];
23
27
  userSelectorProps: MessageEditorProps['userSelectorProps'];
24
28
  annotationTarget?: AnnotationBadgeTargetType;
25
29
  onAnnotationBadgeClick?: (id: string) => void;
@@ -32,4 +36,4 @@ export interface TextMessageProps extends TextMessageType {
32
36
  * the message content itself, a relative timestamp, and providing a mechanism
33
37
  * for deleting the message.
34
38
  */
35
- export declare const TextMessage: ({ id, author, message, createdAt, updatedAt, permissions, showThreadedIndicator, isResolved, isFirstMessage, hasReplies, maxCharacterCount, onAvatarClick, onCopyLink, onDelete, onThreadDelete, onEdit, onEditError, onResolve, onUnresolve, userSelectorProps, annotationTarget, onAnnotationBadgeClick, originalContentDeleted, }: TextMessageProps) => import("react/jsx-runtime").JSX.Element;
39
+ export declare const TextMessage: ({ id, author, message, createdAt, updatedAt, permissions, showThreadedIndicator, isResolved, isFirstMessage, hasReplies, maxCharacterCount, onAvatarClick, onCopyLink, onDelete, onThreadDelete, onEdit, onEditError, onResolve, onUnresolve, isRichTextEnabled, onFormatToggle, userSelectorProps, annotationTarget, onAnnotationBadgeClick, originalContentDeleted, }: TextMessageProps) => import("react/jsx-runtime").JSX.Element;
@@ -34,6 +34,17 @@ interface ThreadedAnnotationsBaseProps {
34
34
  onUnresolve?: (id: string) => void;
35
35
  onPost: MessageActionCallback;
36
36
  onPostError?: (error: unknown) => string | undefined;
37
+ /**
38
+ * When true, enables the rich text experience in every composer (create, reply, edit).
39
+ * Defaults to false. Hosts gate this on their own feature split — the package has no
40
+ * flag mechanism.
41
+ */
42
+ isRichTextEnabled?: boolean;
43
+ /**
44
+ * Called when the user toggles a rich text format from the formatting bar or a keyboard
45
+ * shortcut in any composer. `isActive` is the format's state after the toggle.
46
+ */
47
+ onFormatToggle?: MessageEditorProps['onFormatToggle'];
37
48
  userSelectorProps: MessageEditorProps['userSelectorProps'];
38
49
  /** When true, globally disables replies (hides reply buttons and blocks editor opening on click). */
39
50
  isReplyDisabled?: boolean;
@@ -4,6 +4,12 @@ import { DocumentNode } from '../types';
4
4
  * Mention nodes are formatted as `@[userId:userName]` for the Traditional API.
5
5
  * Paragraphs are joined with newlines.
6
6
  *
7
+ * List blocks (bulletList/orderedList) are flattened to plain lines — one line
8
+ * per paragraph inside each list item (typically one per item, though pasted
9
+ * content can carry multi-paragraph items) — and marks (bold/italic/underline)
10
+ * are ignored. This is a temporary bridge for the rich text composer until
11
+ * dedicated markdown converters replace this serialization path.
12
+ *
7
13
  * Used by BUIE and box-annotations when posting or editing comments via the
8
14
  * Traditional API (onPost/onSave callbacks). The backend parses `@[id:name]`
9
15
  * patterns to generate @mention notifications.
package/package.json CHANGED
@@ -1,15 +1,19 @@
1
1
  {
2
2
  "name": "@box/threaded-annotations",
3
- "version": "4.3.2",
3
+ "version": "4.4.1",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "dependencies": {
6
6
  "@floating-ui/dom": "^1.6.0",
7
7
  "@tanstack/react-virtual": "^3.10.8",
8
8
  "@tiptap/core": "3.26.1",
9
+ "@tiptap/extension-bold": "3.26.1",
9
10
  "@tiptap/extension-document": "3.26.1",
11
+ "@tiptap/extension-italic": "3.26.1",
12
+ "@tiptap/extension-list": "3.26.1",
10
13
  "@tiptap/extension-mention": "3.26.1",
11
14
  "@tiptap/extension-paragraph": "3.26.1",
12
15
  "@tiptap/extension-text": "3.26.1",
16
+ "@tiptap/extension-underline": "3.26.1",
13
17
  "@tiptap/extensions": "3.26.1",
14
18
  "@tiptap/pm": "3.26.1",
15
19
  "@tiptap/react": "3.26.1",
@@ -17,23 +21,23 @@
17
21
  "uuid": "^9.0.1"
18
22
  },
19
23
  "peerDependencies": {
20
- "@box/blueprint-web": "^16.16.0",
21
- "@box/blueprint-web-assets": "^5.6.4",
22
- "@box/collaboration-popover": "^2.2.4",
23
- "@box/readable-time": "^2.2.4",
24
- "@box/user-selector": "^2.2.4",
24
+ "@box/blueprint-web": "^16.16.1",
25
+ "@box/blueprint-web-assets": "^5.6.5",
26
+ "@box/collaboration-popover": "^2.2.5",
27
+ "@box/readable-time": "^2.2.5",
28
+ "@box/user-selector": "^2.2.5",
25
29
  "clsx": "^1.2.1",
26
30
  "react": "^18.0.0",
27
31
  "react-dom": "^18.0.0",
28
32
  "react-intl": "^6.4.2"
29
33
  },
30
34
  "devDependencies": {
31
- "@box/blueprint-web": "^16.16.0",
32
- "@box/blueprint-web-assets": "^5.6.4",
33
- "@box/eslint-plugin-blueprint": "2.2.0",
34
- "@box/readable-time": "^2.2.4",
35
- "@box/storybook-utils": "^1.2.4",
36
- "@box/user-selector": "^2.2.4",
35
+ "@box/blueprint-web": "^16.16.1",
36
+ "@box/blueprint-web-assets": "^5.6.5",
37
+ "@box/eslint-plugin-blueprint": "2.2.1",
38
+ "@box/readable-time": "^2.2.5",
39
+ "@box/storybook-utils": "^1.2.5",
40
+ "@box/user-selector": "^2.2.5",
37
41
  "react": "^18.0.0",
38
42
  "react-dom": "^18.0.0"
39
43
  },