2023-10-10 06:43:25 +11:00
|
|
|
import { SetVarNameModal } from 'components/SetVarNameModal'
|
2023-09-09 01:38:36 -04:00
|
|
|
import { moveValueIntoNewVariable } from 'lang/modifyAst'
|
|
|
|
import { isNodeSafeToReplace } from 'lang/queryAst'
|
|
|
|
import { useEffect, useState } from 'react'
|
2023-10-10 06:43:25 +11:00
|
|
|
import { create } from 'react-modal-promise'
|
2023-09-09 01:38:36 -04:00
|
|
|
import { useStore } from 'useStore'
|
|
|
|
|
2023-10-10 06:43:25 +11:00
|
|
|
const getModalInfo = create(SetVarNameModal as any)
|
2023-09-09 01:38:36 -04:00
|
|
|
|
|
|
|
export function useConvertToVariable() {
|
|
|
|
const { guiMode, selectionRanges, ast, programMemory, updateAst } = useStore(
|
|
|
|
(s) => ({
|
|
|
|
guiMode: s.guiMode,
|
|
|
|
ast: s.ast,
|
|
|
|
updateAst: s.updateAst,
|
|
|
|
selectionRanges: s.selectionRanges,
|
|
|
|
programMemory: s.programMemory,
|
|
|
|
})
|
|
|
|
)
|
|
|
|
const [enable, setEnabled] = useState(false)
|
|
|
|
useEffect(() => {
|
|
|
|
if (!ast) return
|
|
|
|
|
|
|
|
const { isSafe, value } = isNodeSafeToReplace(
|
|
|
|
ast,
|
|
|
|
selectionRanges.codeBasedSelections?.[0]?.range || []
|
|
|
|
)
|
|
|
|
const canReplace = isSafe && value.type !== 'Identifier'
|
|
|
|
const isOnlyOneSelection = selectionRanges.codeBasedSelections.length === 1
|
|
|
|
|
|
|
|
const _enableHorz = canReplace && isOnlyOneSelection
|
|
|
|
setEnabled(_enableHorz)
|
|
|
|
}, [guiMode, selectionRanges])
|
|
|
|
|
|
|
|
const handleClick = async () => {
|
|
|
|
if (!ast) return
|
|
|
|
try {
|
|
|
|
const { variableName } = await getModalInfo({
|
|
|
|
valueName: 'var',
|
2023-10-10 06:43:25 +11:00
|
|
|
} as any)
|
2023-09-09 01:38:36 -04:00
|
|
|
|
|
|
|
const { modifiedAst: _modifiedAst } = moveValueIntoNewVariable(
|
|
|
|
ast,
|
|
|
|
programMemory,
|
|
|
|
selectionRanges.codeBasedSelections[0].range,
|
|
|
|
variableName
|
|
|
|
)
|
|
|
|
|
2023-09-15 04:35:48 -07:00
|
|
|
updateAst(_modifiedAst, true)
|
2023-09-09 01:38:36 -04:00
|
|
|
} catch (e) {
|
2023-09-25 17:28:03 +10:00
|
|
|
console.log('error', e)
|
2023-09-09 01:38:36 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return { enable, handleClick }
|
|
|
|
}
|