MCPcopy
hub / github.com/antonmedv/codejar / restore

Function restore

codejar.ts:221–285  ·  view source on GitHub ↗
(pos: Position)

Source from the content-addressed store, hash-verified

219 }
220
221 function restore(pos: Position) {
222 const s = getSelection()
223 let startNode: Node | undefined, startOffset = 0
224 let endNode: Node | undefined, endOffset = 0
225
226 if (!pos.dir) pos.dir = '->'
227 if (pos.start < 0) pos.start = 0
228 if (pos.end < 0) pos.end = 0
229
230 // Flip start and end if the direction reversed
231 if (pos.dir == '<-') {
232 const {start, end} = pos
233 pos.start = end
234 pos.end = start
235 }
236
237 let current = 0
238
239 visit(editor, el => {
240 if (el.nodeType !== Node.TEXT_NODE) return
241
242 const len = (el.nodeValue || '').length
243 if (current + len > pos.start) {
244 if (!startNode) {
245 startNode = el
246 startOffset = pos.start - current
247 }
248 if (current + len > pos.end) {
249 endNode = el
250 endOffset = pos.end - current
251 return 'stop'
252 }
253 }
254 current += len
255 })
256
257 if (!startNode) startNode = editor, startOffset = editor.childNodes.length
258 if (!endNode) endNode = editor, endOffset = editor.childNodes.length
259
260 // Flip back the selection
261 if (pos.dir == '<-') {
262 [startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset]
263 }
264
265 {
266 // If nodes not editable, create a text node.
267 const startEl = uneditable(startNode)
268 if (startEl) {
269 const node = document.createTextNode('')
270 startEl.parentNode?.insertBefore(node, startEl)
271 startNode = node
272 startOffset = 0
273 }
274 const endEl = uneditable(endNode)
275 if (endEl) {
276 const node = document.createTextNode('')
277 endEl.parentNode?.insertBefore(node, endEl)
278 endNode = node

Callers 8

CodeJarFunction · 0.85
handleNewLineFunction · 0.85
legacyNewLineFixFunction · 0.85
handleTabCharactersFunction · 0.85
handleUndoRedoFunction · 0.85
handlePasteFunction · 0.85
handleCutFunction · 0.85

Calls 3

getSelectionFunction · 0.85
visitFunction · 0.85
uneditableFunction · 0.85

Tested by

no test coverage detected