Add text in a text Area at the cursor position

I would like to add some text when I click on a button in a perspective text area component at the current editing cursor position in the text Area.

not sure it can be done in perspective ?

Hi @mazeyrat ,
Have you got any solution on add test in text areas at cursor positon

no, you can with vision but I did not find any solution for perspective

You can use JavaScript injection in a hidden Markdown component with the following as its source:

<img style='display: none' src='/favicon.ico' onload=" \
		const view = [...window.__client.page.views._data.values()].find(view => view.value.mountPath == this.parentNode.parentNode.parentNode.getAttributeNode('data-component-path').value.split('.')[0]).value; \
		const notesTextArea = document.getElementById('textAreaDomID'); \
		function getSelected() { \
			const selectionStart = notesTextArea.selectionStart; \
			view.custom.write('selectionStart', selectionStart); \
			const selectionEnd = notesTextArea.selectionEnd; \
			view.custom.write('selectionEnd', selectionEnd); \
		} \
		function reportSel() { \
			setCursorAt = view.custom.read('setCursorAt'); \
			if (setCursorAt > -1) { \
				notesTextArea.blur(); \
				notesTextArea.setSelectionRange(setCursorAt, setCursorAt); \
				notesTextArea.focus(); \
				getSelected(); \
				view.custom.write('setCursorAt', -1); \
			} \
			if (view.custom.read('runJS')) \
				setTimeout(() => { reportSel(); }, 100); \
		} \
		notesTextArea.onclick = getSelected; \
		notesTextArea.onkeyup = getSelected; \
		notesTextArea.oncontextmenu = getSelected; \
		notesTextArea.onmouseout = getSelected; \
		view.custom.write('runJS', true); \
		reportSel();"></img>

Assign "textAreaDomID" as the DOM ID, and create the custom view properties "selectionStart" and "selectionEnd" that will capture the cursor/selection location. The custom view property "runJS" is required if you want to make sure the JavaScript stops running when the view is shut down (you'll need to set it to False when that happens).

This is a bit of a hack; not nearly as good as @Ryan_Deardorff solution but it was good enough (and simple enough for my limited skills) to meet my requirement. This is in the text Change Script.

It does require the user to do some editing for the insertion point to be > 0.

	if origin in ['Browser','Script']:
		# compare previous to current and estimate the insertion point
		previousLen = len(previousValue.value)
		currentLen = len(currentValue.value)
		pos = 0
		while pos < min(previousLen, currentLen):
			if previousValue.value[pos] != currentValue.value[pos]:
				break
			pos += 1		
		self.custom.insertionPoint = pos

I use the custom.insertionPoint in a message script on the textArea component:

myText = self.props.text
newText = payload['newText']
insertAt = self.custom.insertionPoint
self.props.text = myText[:insertAt] + newText + myText[insertAt:]