@@ -110,7 +110,7 @@ function initItem(el: HTMLElement) {
110110 handle . addEventListener ( 'mouseenter' , onHandleMouseOver )
111111 handle . addEventListener ( 'mouseleave' , onHandleMouseOut )
112112
113- sortable ( el , onSorted )
113+ sortable ( el , onSortStart , onSorted )
114114
115115 // Drag operations don't remove :hover styles, so manage drag handle hover state.
116116 el . addEventListener ( 'mouseenter' , onListItemMouseOver )
@@ -136,12 +136,10 @@ function onListItemMouseOut(event: MouseEvent) {
136136}
137137
138138// Returns the list item position as a (list index, item index) tuple.
139- // Listen on top-level task lists because item indexing includes nested task lists.
140- function position ( el : Element ) : [ number , number ] {
141- const list = rootTaskList ( el )
139+ function position ( checkbox : HTMLInputElement ) : [ number , number ] {
140+ const list = taskList ( checkbox )
142141 if ( ! list ) throw new Error ( '.contains-task-list not found' )
143- const flattened = Array . from ( list . querySelectorAll ( 'li' ) )
144- const index = flattened . indexOf ( el . closest ( '.task-list-item' ) )
142+ const index = Array . from ( list . children ) . indexOf ( checkbox . closest ( '.task-list-item' ) )
145143 return [ listIndex ( list ) , index ]
146144}
147145
@@ -187,22 +185,33 @@ function syncDisabled(list: TaskListsElement) {
187185// lists in the container, not just task lists, are indexed to match the
188186// server-side Markdown parser's indexing.
189187function listIndex ( list : Element ) : number {
190- const container = list . parentElement
188+ const container = list . closest ( 'task-lists' )
191189 if ( ! container ) throw new Error ( 'parent not found' )
192- const top = Array . from ( container . children ) . filter ( el => el . nodeName === 'OL' || el . nodeName === 'UL' )
193- return top . indexOf ( list )
190+ return Array . from ( container . querySelectorAll ( 'ol, ul' ) ) . indexOf ( list )
191+ }
192+
193+ const originalLists = new WeakMap ( )
194+
195+ function onSortStart ( srcList : Element ) {
196+ const container = srcList . closest ( 'task-lists' )
197+ if ( ! container ) throw new Error ( 'parent not found' )
198+ originalLists . set ( container , Array . from ( container . querySelectorAll ( 'ol, ul' ) ) )
194199}
195200
196201function onSorted ( { src, dst} ) {
197202 const container = src . list . closest ( 'task-lists' )
198203 if ( ! container ) return
199204
205+ const lists = originalLists . get ( container )
206+ if ( ! lists ) return
207+ originalLists . delete ( container )
208+
200209 container . dispatchEvent (
201210 new CustomEvent ( 'task-lists:move' , {
202211 bubbles : true ,
203212 detail : {
204- src : [ listIndex ( src . list ) , src . index ] ,
205- dst : [ listIndex ( dst . list ) , dst . index ]
213+ src : [ lists . indexOf ( src . list ) , src . index ] ,
214+ dst : [ lists . indexOf ( dst . list ) , dst . index ]
206215 }
207216 } )
208217 )
0 commit comments