├── .npmignore ├── example ├── .vscode │ └── settings.json ├── package.json ├── anotherFile.ts ├── package-lock.json ├── index.ts └── tsconfig.json ├── .vscode └── launch.json ├── package.json ├── tsconfig.json ├── LICENSE ├── .gitignore ├── src ├── utils.ts ├── treesitter.ts ├── queries.ts ├── index.ts └── xstate.ts └── README.md /.npmignore: -------------------------------------------------------------------------------- 1 | example -------------------------------------------------------------------------------- /example/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib" 3 | } -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example-tsc-codebase", 3 | "dependencies": { 4 | "typescript": "^5.7.3", 5 | "xstate": "^5.19.2", 6 | "xstate-tsserver": "file:.." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /example/anotherFile.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Some kind of magic comment 3 | */ 4 | export const importedAction = () => {}; 5 | 6 | /** 7 | * Some kind of magic comment 8 | */ 9 | export const importedGuard = () => true; 10 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | // See: https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code 9 | "type": "node", 10 | "request": "attach", 11 | "name": "Attach to VS Code TS Server via Port", 12 | "processId": "${command:PickProcess}", 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "xstate-tsserver", 3 | "description": "XState tsserver plugin for easier navigation in state machines", 4 | "version": "0.0.6", 5 | "license": "MIT", 6 | "main": "./out", 7 | "scripts": { 8 | "build": "tsc", 9 | "dev": "tsc --watch", 10 | "prepublishOnly": "npm run build" 11 | }, 12 | "author": "Nick Worrall", 13 | "homepage": "https://github.com/xylophonehero/xstate-tsserver", 14 | "bugs": "https://github.com/xylophonehero/xstate-tsserver/issues", 15 | "dependencies": { 16 | "tree-sitter": "^0.21.1", 17 | "tree-sitter-typescript": "^0.23.2", 18 | "typescript": "^5.7.3" 19 | }, 20 | "keywords": [ 21 | "typescript", 22 | "xstate", 23 | "tsserver", 24 | "plugin", 25 | "tree-sitter" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "paths": ["src/**"], 3 | "exclude": ["example"], 4 | "compilerOptions": { 5 | "target": "ES2023", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 6 | "module": "commonjs", /* Specify what module code is generated. */ 7 | "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 8 | "outDir": "./out", /* Specify an output folder for all emitted files. */ 9 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 10 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 11 | "strict": true, /* Enable all strict type-checking options. */ 12 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Nick Worrall 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | .DS_Store 45 | 46 | # Optional eslint cache 47 | .eslintcache 48 | 49 | # Optional REPL history 50 | .node_repl_history 51 | 52 | # Output of 'npm pack' 53 | *.tgz 54 | 55 | # Yarn Integrity file 56 | .yarn-integrity 57 | 58 | # dotenv environment variables file 59 | .env 60 | 61 | # next.js build output 62 | .next 63 | 64 | # cra 65 | .cache 66 | 67 | # tdsx 68 | dist 69 | 70 | .yarn/cache 71 | .yarn/unplugged 72 | .yarn/build-state.yml 73 | .yarn/install-state.gz 74 | out -------------------------------------------------------------------------------- /example/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example-tsc-codebase", 3 | "lockfileVersion": 3, 4 | "requires": true, 5 | "packages": { 6 | "": { 7 | "name": "example-tsc-codebase", 8 | "dependencies": { 9 | "typescript": "^5.7.3", 10 | "xstate": "^5.19.2", 11 | "xstate-tsserver": "file:.." 12 | } 13 | }, 14 | "..": { 15 | "version": "0.0.1", 16 | "license": "MIT", 17 | "dependencies": { 18 | "tree-sitter": "^0.21.1", 19 | "tree-sitter-typescript": "^0.23.2", 20 | "typescript": "^5.7.3" 21 | }, 22 | "devDependencies": { 23 | "xstate": "^5.19.2" 24 | } 25 | }, 26 | "node_modules/typescript": { 27 | "version": "5.7.3", 28 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", 29 | "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", 30 | "license": "Apache-2.0", 31 | "bin": { 32 | "tsc": "bin/tsc", 33 | "tsserver": "bin/tsserver" 34 | }, 35 | "engines": { 36 | "node": ">=14.17" 37 | } 38 | }, 39 | "node_modules/xstate": { 40 | "version": "5.19.2", 41 | "resolved": "https://registry.npmjs.org/xstate/-/xstate-5.19.2.tgz", 42 | "integrity": "sha512-B8fL2aP0ogn5aviAXFzI5oZseAMqN00fg/TeDa3ZtatyDcViYLIfuQl4y8qmHCiKZgGEzmnTyNtNQL9oeJE2gw==", 43 | "license": "MIT", 44 | "funding": { 45 | "type": "opencollective", 46 | "url": "https://opencollective.com/xstate" 47 | } 48 | }, 49 | "node_modules/xstate-tsserver": { 50 | "resolved": "..", 51 | "link": true 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import Parser from "tree-sitter"; 2 | import { 3 | ReferencedSymbolEntry, 4 | ScriptElementKind, 5 | } from "typescript/lib/tsserverlibrary"; 6 | 7 | export function createNodeDefinition( 8 | fileName: string, 9 | node: Parser.SyntaxNode, 10 | ) { 11 | return { 12 | name: node.text, 13 | textSpan: { 14 | start: node.startIndex, 15 | length: node.endIndex - node.startIndex, 16 | }, 17 | fileName, 18 | // TODO: Check if these are correct and what else should be added 19 | containerName: "", 20 | containerKind: ScriptElementKind.unknown, 21 | kind: ScriptElementKind.string, 22 | }; 23 | } 24 | 25 | export function createNodeDefinitionWithTextSpan( 26 | fileName: string, 27 | newNode: Parser.SyntaxNode, 28 | originalNode: Parser.SyntaxNode, 29 | ) { 30 | return { 31 | definitions: [createNodeDefinition(fileName, newNode)], 32 | textSpan: { 33 | start: originalNode.startIndex, 34 | length: originalNode.endIndex - originalNode.startIndex, 35 | }, 36 | }; 37 | } 38 | 39 | export function createNodeDefinitionWithDisplayParts( 40 | fileName: string, 41 | newNode: Parser.SyntaxNode, 42 | ) { 43 | return { 44 | ...createNodeDefinition(fileName, newNode), 45 | displayParts: [ 46 | { 47 | kind: ScriptElementKind.string, 48 | text: newNode.text, 49 | }, 50 | ], 51 | }; 52 | } 53 | 54 | export function createReferenceDefinition( 55 | fileName: string, 56 | node: Parser.SyntaxNode, 57 | extraOpts?: Partial, 58 | ) { 59 | return { 60 | fileName, 61 | textSpan: { 62 | start: node.startIndex, 63 | length: node.endIndex - node.startIndex, 64 | }, 65 | isWriteAccess: true, 66 | isDefinition: false, 67 | ...extraOpts, 68 | }; 69 | } 70 | 71 | export type TransitionType = 72 | // A string made up of words separated by dots 73 | | "relative" 74 | // A string made up of words separated by dots and starting with a dot 75 | | "relativeChildren" 76 | // A string made up of words separated by dots and starting with a hash 77 | | "absolute" 78 | // Unknown transition type 79 | | "unknown"; 80 | 81 | /** 82 | * Returns the transition type and target string 83 | */ 84 | export function getTransitionType(transition?: string): { 85 | type: TransitionType; 86 | target: string; 87 | } { 88 | if (!transition) return { type: "unknown", target: "" }; 89 | if (transition.startsWith("#")) 90 | return { 91 | type: "absolute", 92 | target: transition.slice(1), 93 | }; 94 | if (transition.startsWith(".")) { 95 | return { 96 | type: "relativeChildren", 97 | target: transition.slice(1), 98 | }; 99 | } 100 | return { 101 | type: "relative", 102 | target: transition, 103 | }; 104 | } 105 | -------------------------------------------------------------------------------- /src/treesitter.ts: -------------------------------------------------------------------------------- 1 | import Parser from "tree-sitter"; 2 | import TypeScript from "tree-sitter-typescript"; 3 | import { SourceFile } from "typescript"; 4 | 5 | export function createParser() { 6 | const parser = new Parser(); 7 | parser.setLanguage(TypeScript.typescript); 8 | return parser; 9 | } 10 | 11 | export function getFileRootNode(sourceFile: SourceFile) { 12 | const parser = createParser(); 13 | const tree = parser.parse(sourceFile.getFullText()); 14 | return tree.rootNode; 15 | } 16 | 17 | export function findCaptureNodeWithText( 18 | rootNode: Parser.SyntaxNode, 19 | queryString: string, 20 | captureName: string, 21 | captureText: string, 22 | ) { 23 | const parser = createParser(); 24 | const queryMatches = new Parser.Query(parser.getLanguage(), queryString); 25 | const matches = queryMatches.matches(rootNode); 26 | 27 | for (const match of matches) { 28 | const captureNode = match.captures.find( 29 | (cap) => cap.name === captureName && cap.node.text === captureText, 30 | )?.node; 31 | if (captureNode) { 32 | return captureNode; 33 | } 34 | } 35 | } 36 | 37 | export function findAllCaptureMatches( 38 | rootNode: Parser.SyntaxNode, 39 | queryString: string, 40 | ) { 41 | const parser = createParser(); 42 | const queryMatches = new Parser.Query(parser.getLanguage(), queryString); 43 | const matches = queryMatches.matches(rootNode); 44 | 45 | const results: Record = {}; 46 | for (const match of matches) { 47 | for (const capture of match.captures) { 48 | results[capture.name] = capture.node; 49 | } 50 | } 51 | return results; 52 | } 53 | 54 | export function findFirstMatchingNode( 55 | rootNode: Parser.SyntaxNode, 56 | queryString: string, 57 | captureMatch: string, 58 | ) { 59 | const parser = createParser(); 60 | const queryMatches = new Parser.Query(parser.getLanguage(), queryString); 61 | const matches = queryMatches.matches(rootNode); 62 | 63 | for (const match of matches) { 64 | const keyNode = match.captures.find( 65 | (cap) => cap.name === captureMatch, 66 | )?.node; 67 | if (keyNode) { 68 | return keyNode; 69 | } 70 | } 71 | 72 | return null; 73 | } 74 | 75 | export function findMatchingNode( 76 | rootNode: Parser.SyntaxNode, 77 | position: number, 78 | queryString: string, 79 | captureMatch: string, 80 | returnCaptureMatch?: string, 81 | ) { 82 | const parser = createParser(); 83 | const queryMatches = new Parser.Query(parser.getLanguage(), queryString); 84 | const matches = queryMatches.matches(rootNode); 85 | 86 | for (const match of matches) { 87 | const keyNode = match.captures.find( 88 | (cap) => cap.name === captureMatch, 89 | )?.node; 90 | if (keyNode) { 91 | if (position >= keyNode.startIndex && position < keyNode.endIndex) { 92 | if (!returnCaptureMatch) return keyNode; 93 | const returnNode = match.captures.find( 94 | (cap) => cap.name === returnCaptureMatch, 95 | )?.node; 96 | if (returnNode) { 97 | return returnNode; 98 | } 99 | } 100 | } 101 | } 102 | 103 | return null; 104 | } 105 | 106 | export function getAllCapturesOfMatch(match: Parser.QueryMatch) { 107 | const results: Record = {}; 108 | for (const capture of match.captures) { 109 | results[capture.name] = capture.node; 110 | } 111 | return results; 112 | } 113 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **XState TypeScript Language Service Plugin** 2 | 3 | Enhance your **TypeScript experience** when working with **XState state machines**! 4 | This **TypeScript TSServer plugin** provides **better navigation for state machine configurations** inside your IDE. 5 | 6 | --- 7 | 8 | ## **Features** 9 | 10 | ✅ **Go to Definition (`F12`/`gd`)** to jump from a given action, guard, actor, or delay to its definition within the setup block of a machine. 11 | ✅ **Find all references (`Shift+F12`/`gr`)** to list implementations of a given action, guard, actor, or delay. 12 | ✅ **Jump to state target (`F12`/`gd`)** from a transition target or initial state to the state. 13 | ✅ **Autocompletions for state targets** for a transition target or initial state. 14 | 15 | ### Coming soon 16 | 17 | 🛠️ **Show implementation on hover** of the given implementation of a given action, guard, actor, or delay. 18 | 🛠️ **Diagnostics on invalid states** show errors when the state target or 19 | initial state is invalid. If the initial state does not exist then show a 20 | warning 21 | 🛠️ **Code actions for building a state machine** to add states, transitions, 22 | actions, guards, etc. 23 | 24 | --- 25 | 26 | ## **Installation** 27 | 28 | You can install the plugin globally or per project. 29 | 30 | ### **📌 Project Installation** 31 | 32 | To install the plugin in your project, simply run: 33 | 34 | ```sh 35 | npm install --save-dev xstate-tsserver 36 | ``` 37 | 38 | ### **📌 Global Installation** 39 | 40 | You can also install the plugin globally by running: 41 | 42 | ```sh 43 | npm install -g xstate-tsserver 44 | ``` 45 | 46 | You will also need to add your global node_modules path to tsserver's plugin paths. 47 | 48 | For example, in VSCode, you can edit your **`settings.json`** to add the plugin path: 49 | 50 | ```json 51 | { 52 | "typescript.tsserver.pluginPaths": ["path/to/global/node_modules"] 53 | } 54 | ``` 55 | 56 | 💡 **Tip:** You can find your global node_modules path by running: 57 | 58 | ```sh 59 | npm root -g 60 | ``` 61 | 62 | ### Plugin activation 63 | 64 | Modify your **`tsconfig.json`** to include the plugin: 65 | 66 | ```json 67 | { 68 | "compilerOptions": { 69 | "plugins": [{ "name": "xstate-tsserver" }] 70 | } 71 | } 72 | ``` 73 | 74 | Restart the TypeScript server (in VSCode by running **"TypeScript: Restart TS Server"** from the command palette) 75 | 76 | TODO: Make a vscode extension to activate the plugin globally 77 | 78 | --- 79 | 80 | ## **Usage** 81 | 82 | XState tsserver extends the regular tsserver definitions to make navigating 83 | around a state machine much easier 84 | 85 | ### Go to implementation definition 86 | 87 | Under any named action, guard, actor or delay within the machine config, go to definition will navigate to it's implementation within the setup block of the machine. 88 | 89 | 💡 **Tip:** In VSCode, hover over the implementation and press `F12` or `cmd+click` to navigate to the definition. 90 | 91 | ### Find implementation references 92 | 93 | Under any named action, guard, actor or delay within the machine config, find all references will navigate to it's implementation within the setup block of the machine and show other uses of it in the machine config 94 | 95 | 💡 **Tip:** In VSCode, hover over the implementation and press `shift+F12` to navigate to the definition. 96 | 97 | ### Jump to state target 98 | 99 | Under any transition target or initial state within the machine config, go to definition will navigate 100 | to that target state 101 | 102 | 💡 **Tip:** In VSCode, hover over the state name and press `F12` or `cmd+click` to navigate to the state config. 103 | 104 | ### Get autocompletions for state targets 105 | 106 | Under any transition target or initial state within the machine config, the 107 | autocompletion array will show all the valid state targets. 108 | 109 | 💡 **Tip:** In VSCode, press `ctrl+space` to show the autocompletion list for valid state targets. 110 | 111 | --- 112 | 113 | ## Troubleshooting 114 | 115 | 💡 **Tip:** Open **TS Server Logs** (`"TypeScript: Open TS Server Logs"`) to verify that the plugin is loaded. 116 | You should see this log line `xstate tsserver loaded` 117 | 118 | --- 119 | 120 | ## **Contributing** 121 | 122 | Contributions are welcome! 🚀 If you find any issues or have ideas to improve the plugin, feel free to: 123 | 124 | - **Submit an issue** on GitHub. 125 | - **Open a pull request** with improvements. 126 | 127 | --- 128 | 129 | ## **Resources** 130 | 131 | - [TypeScript Language Service Plugin Docs](https://github.com/microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin#overview-writing-a-simple-plugin) 132 | - [XState Documentation](https://stately.ai/docs) 133 | 134 | --- 135 | 136 | ## **License** 137 | 138 | MIT License. 📝 139 | -------------------------------------------------------------------------------- /example/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | and, 3 | AnyActorRef, 4 | AnyEventObject, 5 | assign, 6 | fromCallback, 7 | not, 8 | or, 9 | raise, 10 | sendTo, 11 | setup, 12 | spawnChild, 13 | } from "xstate"; 14 | import { importedAction, importedGuard } from "./anotherFile"; 15 | 16 | const sameFileAction = () => {}; 17 | 18 | setup({ 19 | types: {} as { 20 | context: { fooActor: AnyActorRef; anotherFooActor: AnyActorRef }; 21 | events: { type: "event" } | { type: "event2" } | { type: "event3" }; 22 | }, 23 | actors: { 24 | simpleActor: fromCallback(() => {}), 25 | actorWithInput: fromCallback(() => {}), 26 | }, 27 | actions: { 28 | spawn: spawnChild("simpleActor"), 29 | aliasedAction: importedAction, 30 | sameFileAction, 31 | importedAction, 32 | simpleAction: () => {}, 33 | actionWithParams: (_, _params: string) => {}, 34 | }, 35 | guards: { 36 | importedGuard, 37 | simpleGuard: () => true, 38 | guardWithParams: (_, _params: string) => true, 39 | }, 40 | delays: { 41 | simpleDelay: 1000, 42 | functionDelay: () => 1000, 43 | }, 44 | }).createMachine({ 45 | id: "root", 46 | context: ({ spawn }) => ({ 47 | fooActor: spawn("simpleActor"), 48 | anotherFooActor: spawn("actorWithInput", { 49 | input: { foo: "bar" }, 50 | }), 51 | }), 52 | always: [ 53 | { 54 | target: ".b.child", 55 | }, 56 | ], 57 | entry: [ 58 | spawnChild("simpleActor"), 59 | spawnChild("actorWithInput", { 60 | input: { foo: "bar" }, 61 | }), 62 | "aliasedAction", 63 | "sameFileAction", 64 | "importedAction", 65 | "simpleAction", 66 | { 67 | type: "actionWithParams", 68 | params: "hello", 69 | }, 70 | ], 71 | exit: [ 72 | spawnChild("simpleActor"), 73 | "importedAction", 74 | "simpleAction", 75 | { 76 | type: "actionWithParams", 77 | params: "hello", 78 | }, 79 | ], 80 | invoke: { 81 | src: "simpleActor", 82 | }, 83 | initial: "b", 84 | states: { 85 | idle: { 86 | entry: [ 87 | raise({ type: "event" }, { delay: "functionDelay" }), 88 | sendTo("thing", { type: "event" }, { delay: "simpleDelay" }), 89 | ], 90 | invoke: [ 91 | { 92 | src: "simpleActor", 93 | onDone: { 94 | target: "b", 95 | }, 96 | onError: "c", 97 | }, 98 | { 99 | src: "simpleActor", 100 | onDone: [ 101 | { 102 | guard: "simpleGuard", 103 | target: "b", 104 | }, 105 | { 106 | target: "", 107 | }, 108 | ], 109 | }, 110 | ], 111 | after: { 112 | simpleDelay: { 113 | target: "b", 114 | }, 115 | functionDelay: [ 116 | { 117 | guard: "simpleGuard", 118 | target: "b", 119 | }, 120 | { 121 | target: "c", 122 | }, 123 | ], 124 | }, 125 | on: { 126 | event: { 127 | target: "b", 128 | }, 129 | event2: [ 130 | { 131 | guard: "simpleGuard", 132 | target: "b", 133 | }, 134 | { 135 | target: "c", 136 | }, 137 | ], 138 | event3: "", 139 | }, 140 | }, 141 | b: { 142 | after: { 143 | simpleDelay: [ 144 | { 145 | guard: "simpleGuard", 146 | target: "", 147 | }, 148 | { 149 | target: ".child2", 150 | }, 151 | ], 152 | }, 153 | initial: "child", 154 | states: { 155 | child: {}, 156 | child2: { 157 | on: { 158 | event: "#root", 159 | event2: "#root.b.child", 160 | }, 161 | }, 162 | }, 163 | always: [ 164 | { 165 | target: "", 166 | }, 167 | { 168 | target: "deep1.deep2", 169 | }, 170 | ], 171 | }, 172 | c: { 173 | on: { 174 | event: "deep1.deep2.deep3.deep4", 175 | }, 176 | states: { 177 | noInitial: {}, 178 | }, 179 | always: { 180 | target: "deep1", 181 | }, 182 | }, 183 | deep1: { 184 | id: "deep1", 185 | on: { 186 | event: ".deep2", 187 | event2: ".deep2.deep3", 188 | event3: ".deep2.deep3.deep4", 189 | }, 190 | after: { 191 | simpleDelay: { 192 | target: "#deepest", 193 | }, 194 | functionDelay: { 195 | target: "#deep1.deep2", 196 | }, 197 | }, 198 | states: { 199 | deep2: { 200 | after: { 201 | 1000: { target: ".deep3" }, 202 | }, 203 | states: { 204 | deep3: { 205 | states: { 206 | deep4: { 207 | id: "deepest", 208 | }, 209 | }, 210 | }, 211 | }, 212 | }, 213 | }, 214 | }, 215 | }, 216 | on: { 217 | event: [ 218 | { 219 | guard: "importedGuard", 220 | target: ".idle", 221 | }, 222 | { 223 | guard: "simpleGuard", 224 | target: "#root.idle", 225 | }, 226 | { 227 | guard: { type: "guardWithParams", params: "hello" }, 228 | target: ".deep1.deep2.deep3.deep4", 229 | }, 230 | { 231 | guard: not("simpleGuard"), 232 | }, 233 | { 234 | guard: not({ type: "guardWithParams", params: "hello" }), 235 | }, 236 | { 237 | guard: and([ 238 | { type: "guardWithParams", params: "hello" }, 239 | { type: "guardWithParams", params: "hello" }, 240 | ]), 241 | }, 242 | { 243 | guard: or(["simpleGuard", "simpleGuard"]), 244 | }, 245 | { 246 | guard: or([ 247 | { type: "guardWithParams", params: "hello" }, 248 | { type: "guardWithParams", params: "hello" }, 249 | ]), 250 | }, 251 | { 252 | actions: [ 253 | "importedAction", 254 | "simpleAction", 255 | { 256 | type: "actionWithParams", 257 | params: "hello", 258 | }, 259 | spawnChild("simpleActor"), 260 | assign({ 261 | fooActor: ({ spawn }) => spawn("simpleActor"), 262 | anotherFooActor: ({ spawn }) => 263 | spawn("actorWithInput", { 264 | input: { foo: "bar" }, 265 | }), 266 | }), 267 | ], 268 | }, 269 | ], 270 | }, 271 | }); 272 | -------------------------------------------------------------------------------- /src/queries.ts: -------------------------------------------------------------------------------- 1 | export const machineWithSetupQuery = ` 2 | (call_expression 3 | function: (member_expression 4 | object: (call_expression 5 | function: (identifier) @xstate.setup (#eq? @xstate.setup "setup") 6 | arguments: (arguments) @xstate.setup.config) 7 | property: (property_identifier) @xstate.createMachine (#eq? @xstate.createMachine "createMachine")) 8 | arguments: (arguments 9 | (object) @xstate.state.config @xstate.root.config)) @xstate.machine 10 | `; 11 | 12 | export const setupActionsQuery = ` 13 | (pair 14 | key: (property_identifier) @key (#eq? @key "actions") 15 | value: (object [ 16 | (pair 17 | key: (property_identifier) @action.name 18 | value: (_) 19 | ) 20 | (shorthand_property_identifier) @action.name 21 | ]) 22 | ) 23 | `; 24 | 25 | export const machineActionsQuery = ` 26 | (pair 27 | key: (property_identifier) @key 28 | (#match? @key "actions|entry|exit") 29 | value: [ 30 | (array (string (string_fragment) @xstate.action.name) @xstate.action) 31 | (string (string_fragment) @xstate.action.name) @xstate.action 32 | (array 33 | (object 34 | (pair 35 | key: (property_identifier) @type_key 36 | (#eq? @type_key "type") 37 | value: (string (string_fragment) @xstate.action.name) @xstate.action 38 | ) 39 | ) 40 | ) 41 | (object 42 | (pair 43 | key: (property_identifier) @type_key 44 | (#eq? @type_key "type") 45 | value: (string (string_fragment) @xstate.action.name) @xstate.action 46 | ) 47 | ) 48 | ] 49 | ) 50 | 51 | (call_expression 52 | function: (identifier) @enqueue (#eq? @enqueue "enqueue") 53 | arguments: (arguments [ 54 | (string (string_fragment) @xstate.action.name) @xstate.action 55 | (object 56 | (pair 57 | key: (property_identifier) @type_key 58 | (#eq? @type_key "type") 59 | value: (string (string_fragment) @xstate.action.name) @xstate.action 60 | ) 61 | ) 62 | ]) 63 | ) 64 | `; 65 | 66 | export const setupGuardsQuery = ` 67 | (pair 68 | key: (property_identifier) @key (#eq? @key "guards") 69 | value: (object [ 70 | (pair 71 | key: (property_identifier) @guard.name 72 | value: (_) 73 | ) 74 | (shorthand_property_identifier) @guard.name 75 | ]) 76 | ) 77 | `; 78 | 79 | export const machineGuardsQuery = ` 80 | (pair 81 | key: (property_identifier) @key 82 | (#eq? @key "guard") 83 | value: [ 84 | (string (string_fragment) @xstate.guard.name) @xstate.guard 85 | (object 86 | (pair 87 | key: (property_identifier) @type_key 88 | (#eq? @type_key "type") 89 | value: (string (string_fragment) @xstate.guard.name) @xstate.guard 90 | ) 91 | ) 92 | ] 93 | ) 94 | 95 | (call_expression 96 | function: (identifier) @check (#match? @check "check|not") 97 | arguments: (arguments [ 98 | (string (string_fragment) @xstate.guard.name) @xstate.guard 99 | (object 100 | (pair 101 | key: (property_identifier) @type_key 102 | (#eq? @type_key "type") 103 | value: (string (string_fragment) @xstate.guard.name) @xstate.guard 104 | ) 105 | )] 106 | ) 107 | ) 108 | 109 | (call_expression 110 | function: (identifier) @hog (#match? @hog "and|or") 111 | arguments: (arguments 112 | (array [ 113 | (string (string_fragment) @xstate.guard.name) @xstate.guard 114 | (object 115 | (pair 116 | key: (property_identifier) @type_key 117 | (#eq? @type_key "type") 118 | value: (string (string_fragment) @xstate.guard.name) @xstate.guard 119 | ) 120 | )] 121 | ) 122 | ) 123 | ) 124 | `; 125 | 126 | export const setupActorsQuery = ` 127 | (pair 128 | key: (property_identifier) @key (#eq? @key "actors") 129 | value: (object [ 130 | (pair 131 | key: (property_identifier) @actor.name 132 | value: (_) 133 | ) 134 | (shorthand_property_identifier) @actor.name 135 | ]) 136 | ) 137 | `; 138 | 139 | export const machineActorsQuery = ` 140 | (pair 141 | key: (property_identifier) @invoke (#eq? @invoke "invoke") 142 | value: [ 143 | (object 144 | (pair 145 | key: (property_identifier) @invoke.src (#eq? @invoke.src "src") 146 | value: (string (string_fragment) @xstate.actor.name) @xstate.actor 147 | ) 148 | ) 149 | (array 150 | (object 151 | (pair 152 | key: (property_identifier) @invoke.src (#eq? @invoke.src "src") 153 | value: (string (string_fragment) @xstate.actor.name) @xstate.actor 154 | ) 155 | ) 156 | ) 157 | ] 158 | ) 159 | 160 | (pair 161 | key: (property_identifier) @key 162 | (#match? @key "actions|entry|exit") 163 | value: [ 164 | (call_expression 165 | function: (identifier) @action.spawnChild (#eq? @action.spawnChild "spawnChild") 166 | arguments: (arguments (string (string_fragment) @xstate.actor.name) @xstate.actor) 167 | ) 168 | (array 169 | (call_expression 170 | function: (identifier) @action.spawnChild (#eq? @action.spawnChild "spawnChild") 171 | arguments: (arguments (string (string_fragment) @xstate.actor.name) @xstate.actor) 172 | ) 173 | ) 174 | ] 175 | ) 176 | 177 | (call_expression 178 | function: (identifier) @xstate.spawn (#eq? @xstate.spawn "spawn") 179 | arguments: (arguments 180 | (string (string_fragment) @xstate.actor.name) @xstate.actor 181 | ) 182 | ) 183 | `; 184 | 185 | export const setupDelaysQuery = ` 186 | (pair 187 | key: (property_identifier) @key (#eq? @key "delays") 188 | value: (object [ 189 | (pair 190 | key: (property_identifier) @delay.name 191 | value: (_) 192 | ) 193 | (shorthand_property_identifier) @delay.name 194 | ]) 195 | ) 196 | `; 197 | 198 | export const machineDelaysQuery = ` 199 | (pair 200 | key: (property_identifier) @key (#eq? @key "after") 201 | value: (object 202 | (pair 203 | key: (property_identifier) @xstate.delay @xstate.delay.name 204 | value: (_) 205 | ) 206 | ) 207 | ) 208 | 209 | (call_expression 210 | function: (identifier) @action (#match? @action "sendTo|raise") 211 | arguments: (arguments 212 | (object 213 | (pair 214 | key: (property_identifier) @event (#eq? @event "delay") 215 | value: (string (string_fragment) @xstate.delay.name) @xstate.delay 216 | ) 217 | ) 218 | ) 219 | ) 220 | `; 221 | 222 | export const setupImplementableQuery = ` 223 | (pair 224 | key: (property_identifier) @setup.key (#match? @setup.key "actors|actions|guards|delays") 225 | value: (object [ 226 | (pair 227 | key: (property_identifier) @implementation.name 228 | value: (_) @implementation.definition 229 | ) 230 | (shorthand_property_identifier) @implementation.name @implementation.definition 231 | ]) 232 | ) 233 | `; 234 | 235 | export const stateQuery = ` 236 | (object 237 | (pair 238 | key: (property_identifier) @states.key (#eq? @states.key "states") 239 | value: (object 240 | (pair 241 | key: (property_identifier) @xstate.state.name 242 | value: (object) @xstate.state.config 243 | ) @xstate.state 244 | ) 245 | ) 246 | ) 247 | `; 248 | 249 | export const transitionQuery = ` 250 | (pair 251 | key: (property_identifier) @transition.key (#match? @transition.key "after|on$") 252 | value: (object 253 | (pair 254 | key: (_) 255 | value: [ 256 | (string) @transition.target 257 | (object 258 | (pair 259 | key: (property_identifier) @transition.target.key 260 | value: (string) @transition.target 261 | ) 262 | ) 263 | (array 264 | (object 265 | (pair 266 | key: (property_identifier) @transition.target.key (#eq? @transition.target.key "target") 267 | value: (string) @transition.target 268 | ) 269 | ) 270 | ) 271 | ] 272 | ) 273 | ) 274 | ) 275 | 276 | (pair 277 | key: (property_identifier) @transition.key (#match? @transition.key "onDone|onError|always") 278 | value: [ 279 | (string) @transition.target 280 | (object 281 | (pair 282 | key: (property_identifier) @transition.target.key 283 | value: (string) @transition.target 284 | ) 285 | ) 286 | (array 287 | (object 288 | (pair 289 | key: (property_identifier) @transition.target.key (#eq? @transition.target.key "target") 290 | value: (string) @transition.target 291 | ) 292 | ) 293 | ) 294 | ] 295 | ) 296 | `; 297 | 298 | export const initialStateQuery = ` 299 | (pair 300 | key: (property_identifier) @key (#eq? @key "initial") 301 | value: (string) @initial.state 302 | ) 303 | `; 304 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | // This matches the package name given in this package.json 4 | "plugins": [ 5 | { 6 | "name": "xstate-tsserver" 7 | } 8 | ], 9 | 10 | // Everything below is just the default for `tsc --init` 11 | 12 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 13 | 14 | /* Projects */ 15 | // "incremental": true, /* Enable incremental compilation */ 16 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 17 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 18 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 19 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 20 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 21 | 22 | /* Language and Environment */ 23 | "target": "es2017" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 24 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 25 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 26 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 27 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 28 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 29 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 30 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 31 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 32 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 33 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 34 | 35 | /* Modules */ 36 | "module": "commonjs" /* Specify what module code is generated. */, 37 | // "rootDir": "./", /* Specify the root folder within your source files. */ 38 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 39 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 40 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 41 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 42 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 43 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 44 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 45 | // "resolveJsonModule": true, /* Enable importing .json files */ 46 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 47 | 48 | /* JavaScript Support */ 49 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 50 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 51 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 52 | 53 | /* Emit */ 54 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 55 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 56 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 57 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 58 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 59 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 60 | // "removeComments": true, /* Disable emitting comments. */ 61 | // "noEmit": true, /* Disable emitting files from a compilation. */ 62 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 63 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 64 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 65 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 66 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 67 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 68 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 69 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 70 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 71 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 72 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 73 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 74 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 75 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 76 | 77 | /* Interop Constraints */ 78 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 83 | 84 | /* Type Checking */ 85 | "strict": true /* Enable all strict type-checking options. */, 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 87 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 92 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ScriptElementKind, 3 | type LanguageService, 4 | type server, 5 | } from "typescript/lib/tsserverlibrary"; 6 | import { 7 | createNodeDefinitionWithDisplayParts, 8 | createNodeDefinitionWithTextSpan, 9 | createReferenceDefinition, 10 | } from "./utils"; 11 | import { getFileRootNode } from "./treesitter"; 12 | import { 13 | findAllImplementablesInMachine, 14 | getImplementableInMachine, 15 | getMachineConfigNodes, 16 | findImplementableInSetup, 17 | getImplementableInSetupInPosition, 18 | getStateObjectsAtPosition, 19 | getAllDescendantStateObjects, 20 | getTransitionObjectAtPosition, 21 | getAllStateTargets, 22 | getInitialStateObjectAtPosition, 23 | getAllDirectChildStateTargets, 24 | } from "./xstate"; 25 | 26 | function init(modules: { 27 | typescript: typeof import("typescript/lib/tsserverlibrary"); 28 | }) { 29 | // TODO: Figure out how bad it is to use the global typescript module even 30 | // though it might be different 31 | const ts = modules.typescript; 32 | 33 | function create(info: server.PluginCreateInfo) { 34 | // Diagnostic logging 35 | function log(message: string) { 36 | info.project.projectService.logger.info(message); 37 | } 38 | 39 | log("xstate tsserver loaded"); 40 | 41 | // Set up decorator object 42 | const proxy: LanguageService = Object.create(null); 43 | for (let k of Object.keys(info.languageService) as Array< 44 | keyof LanguageService 45 | >) { 46 | const x = info.languageService[k]!; 47 | // @ts-expect-error - JS runtime trickery which is tricky to type tersely 48 | proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args); 49 | } 50 | 51 | function getMachineAtPosition(fileName: string, position: number) { 52 | const program = info.languageService.getProgram(); 53 | const sourceFile = program?.getSourceFile(fileName); 54 | if (!sourceFile) return null; 55 | 56 | const rootNode = getFileRootNode(sourceFile); 57 | 58 | const machineConfigNodes = getMachineConfigNodes(rootNode, position); 59 | if (!machineConfigNodes) return null; 60 | 61 | return machineConfigNodes; 62 | } 63 | 64 | proxy.getQuickInfoAtPosition = (fileName, position) => { 65 | const prior = info.languageService.getQuickInfoAtPosition( 66 | fileName, 67 | position, 68 | ); 69 | 70 | // TODO: Get the hover info for a thing inside a machine config and 71 | // display it's implementation 72 | 73 | return prior; 74 | }; 75 | 76 | // If used on a setup implementable, find the references within the machine 77 | // to it 78 | // If used on a machine implementable, find the reference within setup 79 | // function. If the setup implementable is a shorthand_property_identifier, 80 | // then merge in the references at that position 81 | proxy.findReferences = (fileName, position) => { 82 | const prior = info.languageService.findReferences(fileName, position); 83 | 84 | const machineConfigNodes = getMachineAtPosition(fileName, position); 85 | if (!machineConfigNodes) return prior; 86 | 87 | const { machineConfig, setupConfig, location } = machineConfigNodes; 88 | if (location === "setupConfig") { 89 | const { type, node, text } = getImplementableInSetupInPosition( 90 | setupConfig, 91 | position, 92 | ); 93 | if (type === "unknown") return prior; 94 | log(`✅ Found ${type} implementation for ${text}`); 95 | const implementations = findAllImplementablesInMachine( 96 | machineConfig, 97 | type, 98 | text, 99 | ); 100 | if (implementations.length === 0) return prior; 101 | 102 | return [ 103 | ...(prior ?? []), 104 | { 105 | definition: createNodeDefinitionWithDisplayParts(fileName, node), 106 | references: implementations.map((implementation) => 107 | createReferenceDefinition(fileName, implementation), 108 | ), 109 | }, 110 | ]; 111 | } else if (location === "machineConfig") { 112 | const { type, text, node } = getImplementableInMachine( 113 | machineConfig, 114 | position, 115 | ); 116 | if (type === "unknown") return prior; 117 | 118 | const setupNode = findImplementableInSetup(setupConfig, type, text); 119 | if (setupNode) { 120 | log(`✅ Found ${type} definition for ${text} in setup`); 121 | return [ 122 | ...(prior ?? []), 123 | ...(setupNode.type === "shorthand_property_identifier" 124 | ? (info.languageService.findReferences( 125 | fileName, 126 | setupNode.startIndex, 127 | ) ?? []) 128 | : []), 129 | { 130 | definition: createNodeDefinitionWithDisplayParts(fileName, node), 131 | references: [createReferenceDefinition(fileName, node)], 132 | }, 133 | ]; 134 | } 135 | } 136 | return prior; 137 | }; 138 | 139 | // If used on a implementable within the machine config, find the definition 140 | // within the setup config 141 | // If the defintion is a shorthand_property_identifier, then use it's 142 | // definition for the implementable definition 143 | // If used on a transition target node, go to the state which it targets 144 | // If used on an initial state identifier, go to the state which is targets 145 | proxy.getDefinitionAndBoundSpan = (fileName, position) => { 146 | const prior = info.languageService.getDefinitionAndBoundSpan( 147 | fileName, 148 | position, 149 | ); 150 | 151 | const machineConfigNodes = getMachineAtPosition(fileName, position); 152 | if (!machineConfigNodes) return prior; 153 | 154 | const { machineConfig, setupConfig, location } = machineConfigNodes; 155 | if (location !== "machineConfig") return prior; 156 | 157 | const { type, text, node } = getImplementableInMachine( 158 | machineConfig, 159 | position, 160 | ); 161 | 162 | if (type !== "unknown") { 163 | const setupNode = findImplementableInSetup(setupConfig, type, text); 164 | if (setupNode) { 165 | log(`✅ Found ${type} definition for ${text} in setup`); 166 | if (setupNode.type === "shorthand_property_identifier") 167 | return info.languageService.getDefinitionAndBoundSpan( 168 | fileName, 169 | setupNode.startIndex, 170 | ); 171 | return createNodeDefinitionWithTextSpan(fileName, setupNode, node); 172 | } 173 | } 174 | 175 | const transitionObject = getTransitionObjectAtPosition( 176 | machineConfig, 177 | position, 178 | ); 179 | if (transitionObject) { 180 | const { 181 | node: transitionNode, 182 | text: transitionText, 183 | target: transitionTarget, 184 | type: transitionType, 185 | } = transitionObject; 186 | 187 | log(`✅ Found transition ${transitionText} at ${position}`); 188 | const machineStates = getAllDescendantStateObjects(machineConfig); 189 | 190 | if (transitionType === "absolute") { 191 | const [idTarget, ...rest] = transitionTarget.split("."); 192 | const relativeTarget = rest.join("."); 193 | const stateWithId = machineStates.find( 194 | (state) => state.id === idTarget, 195 | ); 196 | if (stateWithId) { 197 | // If just a pure id, then go to the state 198 | if (relativeTarget === "") { 199 | log( 200 | `✅ Found state target ${stateWithId.name || "(machine)"} at ${position}`, 201 | ); 202 | return createNodeDefinitionWithTextSpan( 203 | fileName, 204 | stateWithId.node, 205 | transitionNode, 206 | ); 207 | } else { 208 | // If more after . then run the state children search 209 | const stateTarget = machineStates.find( 210 | (state) => 211 | state.path === `${stateWithId.path}.${relativeTarget}`, 212 | ); 213 | 214 | if (stateTarget) { 215 | log(`✅ Found state target ${stateTarget.path} at ${position}`); 216 | return createNodeDefinitionWithTextSpan( 217 | fileName, 218 | stateTarget.node, 219 | transitionNode, 220 | ); 221 | } 222 | } 223 | } 224 | } else { 225 | const currentStateObjects = getStateObjectsAtPosition( 226 | machineStates, 227 | position, 228 | ); 229 | 230 | const baseStateObject = currentStateObjects.at( 231 | transitionType === "relativeChildren" ? -1 : -2, 232 | ); 233 | if (!baseStateObject) return prior; 234 | 235 | const stateObjectTarget = machineStates.find( 236 | (state) => 237 | state.path === `${baseStateObject.path}.${transitionTarget}`, 238 | ); 239 | 240 | if (stateObjectTarget) { 241 | log( 242 | `✅ Found state target ${stateObjectTarget.path} at ${position}`, 243 | ); 244 | return createNodeDefinitionWithTextSpan( 245 | fileName, 246 | stateObjectTarget.node, 247 | transitionNode, 248 | ); 249 | } 250 | } 251 | } 252 | 253 | const initialStateObject = getInitialStateObjectAtPosition( 254 | machineConfig, 255 | position, 256 | ); 257 | if (initialStateObject) { 258 | log(`✅ Found initial state ${initialStateObject.text} at ${position}`); 259 | const machineStates = getAllDescendantStateObjects(machineConfig); 260 | const currentStateObjects = getStateObjectsAtPosition( 261 | machineStates, 262 | position, 263 | ); 264 | 265 | const currentStatePath = currentStateObjects.at(-1)?.path; 266 | const targetPath = `${currentStatePath}.${initialStateObject.text}`; 267 | const targetStateObject = machineStates.find( 268 | (state) => state.path === targetPath, 269 | ); 270 | 271 | if (targetStateObject) { 272 | log(`✅ Found initial state target ${targetPath} at ${position}`); 273 | return createNodeDefinitionWithTextSpan( 274 | fileName, 275 | targetStateObject.node, 276 | initialStateObject.node, 277 | ); 278 | } 279 | } 280 | 281 | return prior; 282 | }; 283 | 284 | // If used on a transition target node, list all the possible transitions 285 | proxy.getCompletionsAtPosition = ( 286 | fileName, 287 | position, 288 | options, 289 | formatSettings, 290 | ) => { 291 | const prior = info.languageService.getCompletionsAtPosition( 292 | fileName, 293 | position, 294 | options, 295 | formatSettings, 296 | ); 297 | 298 | const machineConfigNodes = getMachineAtPosition(fileName, position); 299 | if (!machineConfigNodes) return prior; 300 | 301 | const { machineConfig, location } = machineConfigNodes; 302 | if (location !== "machineConfig") return prior; 303 | 304 | const transitionObject = getTransitionObjectAtPosition( 305 | machineConfig, 306 | position, 307 | ); 308 | 309 | if (transitionObject) { 310 | const { node: transitionNode } = transitionObject; 311 | log(`✅ Found transition at ${position}`); 312 | const machineStates = getAllDescendantStateObjects(machineConfig); 313 | 314 | // Get all state nodes 315 | const currentStatePath = 316 | getStateObjectsAtPosition(machineStates, position).at(-1)?.path ?? ""; 317 | 318 | const stateTargets = getAllStateTargets( 319 | currentStatePath, 320 | machineStates, 321 | ); 322 | 323 | return { 324 | isGlobalCompletion: false, 325 | isMemberCompletion: true, 326 | isNewIdentifierLocation: false, 327 | entries: stateTargets.map((target) => ({ 328 | replacementSpan: { 329 | start: transitionNode.startIndex + 1, 330 | length: transitionNode.endIndex - transitionNode.startIndex - 2, 331 | }, 332 | name: target.transitionName, 333 | kind: ScriptElementKind.string, 334 | sortText: target.sortText, 335 | })), 336 | }; 337 | } 338 | 339 | const initialStateObject = getInitialStateObjectAtPosition( 340 | machineConfig, 341 | position, 342 | ); 343 | 344 | if (initialStateObject) { 345 | const { node: initialStateNode } = initialStateObject; 346 | log(`✅ Found initial state at ${position}`); 347 | const machineStates = getAllDescendantStateObjects(machineConfig); 348 | 349 | // Get all state nodes 350 | const currentStatePath = 351 | getStateObjectsAtPosition(machineStates, position).at(-1)?.path ?? ""; 352 | 353 | const stateTargets = getAllDirectChildStateTargets( 354 | currentStatePath, 355 | machineStates, 356 | ); 357 | 358 | return { 359 | isGlobalCompletion: false, 360 | isMemberCompletion: true, 361 | isNewIdentifierLocation: false, 362 | entries: stateTargets.map((target) => ({ 363 | replacementSpan: { 364 | start: initialStateNode.startIndex + 1, 365 | length: initialStateNode.endIndex - initialStateNode.startIndex - 2, 366 | }, 367 | name: target.transitionName, 368 | kind: ScriptElementKind.string, 369 | sortText: target.sortText, 370 | })), 371 | }; 372 | } 373 | 374 | return prior; 375 | }; 376 | 377 | return proxy; 378 | } 379 | 380 | return { create }; 381 | } 382 | 383 | export = init; 384 | -------------------------------------------------------------------------------- /src/xstate.ts: -------------------------------------------------------------------------------- 1 | import Parser from "tree-sitter"; 2 | import { 3 | initialStateQuery, 4 | machineActionsQuery, 5 | machineActorsQuery, 6 | machineDelaysQuery, 7 | machineGuardsQuery, 8 | machineWithSetupQuery, 9 | setupActionsQuery, 10 | setupActorsQuery, 11 | setupDelaysQuery, 12 | setupGuardsQuery, 13 | setupImplementableQuery, 14 | stateQuery, 15 | transitionQuery, 16 | } from "./queries"; 17 | import { 18 | createParser, 19 | findCaptureNodeWithText, 20 | findMatchingNode, 21 | getAllCapturesOfMatch, 22 | } from "./treesitter"; 23 | import { getTransitionType, TransitionType } from "./utils"; 24 | 25 | /** 26 | * Finds the machine at the given position and returns all capture groups within 27 | * the match 28 | */ 29 | function getMachineNodes(rootNode: Parser.SyntaxNode, position: number) { 30 | const parser = createParser(); 31 | const queryMatches = new Parser.Query( 32 | parser.getLanguage(), 33 | machineWithSetupQuery, 34 | ); 35 | const matches = queryMatches.matches(rootNode); 36 | 37 | const results: Record = {}; 38 | 39 | for (const match of matches) { 40 | const machineNode = match.captures.find( 41 | (cap) => cap.name === "xstate.machine", 42 | )?.node; 43 | if ( 44 | machineNode && 45 | machineNode.startIndex <= position && 46 | position < machineNode.endIndex 47 | ) { 48 | for (const capture of match.captures) { 49 | results[capture.name] = capture.node; 50 | } 51 | continue; 52 | } 53 | } 54 | 55 | return results; 56 | } 57 | 58 | /** 59 | * Find the machine at the given position 60 | */ 61 | export function getMachineConfigNodes( 62 | rootNode: Parser.SyntaxNode, 63 | position: number, 64 | ) { 65 | const { 66 | "xstate.machine": machine, 67 | "xstate.root.config": machineConfig, 68 | "xstate.setup.config": setupConfig, 69 | } = getMachineNodes(rootNode, position); 70 | 71 | if (!machine || !machineConfig || !setupConfig) return null; 72 | 73 | let location = null; 74 | if ( 75 | machineConfig.startIndex <= position && 76 | position < machineConfig.endIndex 77 | ) { 78 | location = "machineConfig" as const; 79 | } else if ( 80 | setupConfig.startIndex <= position && 81 | position < setupConfig.endIndex 82 | ) { 83 | location = "setupConfig" as const; 84 | } 85 | if (!location) return null; 86 | 87 | return { machine, machineConfig, setupConfig, location }; 88 | } 89 | 90 | type ImplementableType = "action" | "actor" | "guard" | "delay"; 91 | 92 | const setupQueryByImplementationType = { 93 | action: setupActionsQuery, 94 | actor: setupActorsQuery, 95 | guard: setupGuardsQuery, 96 | delay: setupDelaysQuery, 97 | }; 98 | 99 | const machineQueryByImplementationType = { 100 | action: machineActionsQuery, 101 | actor: machineActorsQuery, 102 | guard: machineGuardsQuery, 103 | delay: machineDelaysQuery, 104 | }; 105 | 106 | /** 107 | * Find the xstate implementation type at the given position 108 | * To be used with machine configuration 109 | */ 110 | export function getImplementableInMachine( 111 | machineNode: Parser.SyntaxNode, 112 | position: number, 113 | ): 114 | | { 115 | type: ImplementableType; 116 | node: Parser.SyntaxNode; 117 | text: string; 118 | } 119 | | { 120 | type: "unknown"; 121 | node: null; 122 | text: string; 123 | } { 124 | const actionNode = findMatchingNode( 125 | machineNode, 126 | position, 127 | machineActionsQuery, 128 | "xstate.action", 129 | "xstate.action.name", 130 | ); 131 | 132 | if (actionNode) 133 | return { 134 | type: "action", 135 | node: actionNode, 136 | text: actionNode.text, 137 | }; 138 | 139 | const actorNode = findMatchingNode( 140 | machineNode, 141 | position, 142 | machineActorsQuery, 143 | "xstate.actor", 144 | "xstate.actor.name", 145 | ); 146 | 147 | if (actorNode) 148 | return { 149 | type: "actor", 150 | node: actorNode, 151 | text: actorNode.text, 152 | }; 153 | 154 | const guardNode = findMatchingNode( 155 | machineNode, 156 | position, 157 | machineGuardsQuery, 158 | "xstate.guard", 159 | "xstate.guard.name", 160 | ); 161 | 162 | if (guardNode) 163 | return { 164 | type: "guard", 165 | node: guardNode, 166 | text: guardNode.text, 167 | }; 168 | 169 | const delayNode = findMatchingNode( 170 | machineNode, 171 | position, 172 | machineDelaysQuery, 173 | "xstate.delay", 174 | "xstate.delay.name", 175 | ); 176 | if (delayNode) 177 | return { 178 | type: "delay", 179 | node: delayNode, 180 | text: delayNode.text, 181 | }; 182 | 183 | return { type: "unknown", node: null, text: "" }; 184 | } 185 | 186 | /** 187 | * Find the implementation definition node for the given implementation type 188 | * and name 189 | * To be used within the setup configuration 190 | */ 191 | export function findImplementableInSetup( 192 | setupConfig: Parser.SyntaxNode, 193 | type: ImplementableType, 194 | implementationName: string, 195 | ) { 196 | const setupNode = findCaptureNodeWithText( 197 | setupConfig, 198 | setupQueryByImplementationType[type], 199 | `${type}.name`, 200 | implementationName, 201 | ); 202 | 203 | return setupNode; 204 | } 205 | 206 | const setupKeyToImplementableType = { 207 | actions: "action", 208 | actors: "actor", 209 | guards: "guard", 210 | delays: "delay", 211 | } as const; 212 | 213 | /** 214 | * Find the setup node at the given position and also return it's implementable type 215 | */ 216 | export function getImplementableInSetupInPosition( 217 | setupConfig: Parser.SyntaxNode, 218 | position: number, 219 | ): 220 | | { 221 | type: ImplementableType; 222 | node: Parser.SyntaxNode; 223 | text: string; 224 | } 225 | | { 226 | type: "unknown"; 227 | node: null; 228 | text: string; 229 | } { 230 | const parser = createParser(); 231 | const queryMatches = new Parser.Query( 232 | parser.getLanguage(), 233 | setupImplementableQuery, 234 | ); 235 | const matches = queryMatches.matches(setupConfig); 236 | 237 | for (const match of matches) { 238 | const keyNode = match.captures.find( 239 | (cap) => cap.name === "implementation.name", 240 | )?.node; 241 | if (keyNode) { 242 | if (position >= keyNode.startIndex && position < keyNode.endIndex) { 243 | const keyType = match.captures.find((cap) => cap.name === "setup.key") 244 | ?.node.text; 245 | const type = 246 | setupKeyToImplementableType[ 247 | keyType as keyof typeof setupKeyToImplementableType 248 | ]; 249 | if (type) { 250 | return { 251 | type, 252 | node: keyNode, 253 | text: keyNode.text, 254 | }; 255 | } 256 | } 257 | } 258 | } 259 | 260 | return { type: "unknown", node: null, text: "" }; 261 | } 262 | 263 | /** 264 | * Find all implementations of the given implementable type and name in the given machine 265 | */ 266 | export function findAllImplementablesInMachine( 267 | machineConfig: Parser.SyntaxNode, 268 | implementationType: ImplementableType, 269 | implementationName: string, 270 | ) { 271 | const parser = createParser(); 272 | const queryMatches = new Parser.Query( 273 | parser.getLanguage(), 274 | machineQueryByImplementationType[implementationType], 275 | ); 276 | const matches = queryMatches.matches(machineConfig); 277 | 278 | const implementations: Parser.SyntaxNode[] = []; 279 | for (const match of matches) { 280 | const keyNode = match.captures.find( 281 | (cap) => cap.name === `xstate.${implementationType}.name`, 282 | )?.node; 283 | if (keyNode && keyNode.text === implementationName) { 284 | implementations.push(keyNode); 285 | } 286 | } 287 | 288 | return implementations; 289 | } 290 | 291 | /** 292 | * Returns the transition (target) node at the given position 293 | */ 294 | export function getTransitionObjectAtPosition( 295 | rootNode: Parser.SyntaxNode, 296 | position: number, 297 | ) { 298 | const node = findMatchingNode( 299 | rootNode, 300 | position, 301 | transitionQuery, 302 | "transition.target", 303 | ); 304 | if (!node) return null; 305 | const text = node.firstNamedChild?.text; 306 | const { type, target } = getTransitionType(text); 307 | 308 | return { 309 | node, 310 | type, 311 | target, 312 | text, 313 | }; 314 | } 315 | 316 | export function getInitialStateObjectAtPosition( 317 | rootNode: Parser.SyntaxNode, 318 | position: number, 319 | ) { 320 | const node = findMatchingNode( 321 | rootNode, 322 | position, 323 | initialStateQuery, 324 | "initial.state", 325 | ); 326 | if (!node) return null; 327 | const text = node.firstNamedChild?.text ?? ""; 328 | 329 | return { 330 | node, 331 | text, 332 | }; 333 | } 334 | 335 | interface StateObject { 336 | node: Parser.SyntaxNode; 337 | name: string; 338 | id: string; 339 | path: string; 340 | // Not currently used but maybe useful later 341 | initialState: string; 342 | isInitialState: boolean; 343 | } 344 | 345 | /** 346 | * Finds all the descendant state nodes visible from the root node including itself 347 | * State paths will be nested with . separators relative to the root node 348 | */ 349 | export function getAllDescendantStateObjects(rootNode: Parser.SyntaxNode) { 350 | const parser = createParser(); 351 | const queryMatches = new Parser.Query(parser.getLanguage(), stateQuery); 352 | const matches = queryMatches.matches(rootNode); 353 | 354 | const stateObjects: StateObject[] = [ 355 | { 356 | node: rootNode, 357 | name: "", 358 | id: getStateId(rootNode), 359 | path: "", 360 | initialState: getInitialState(rootNode), 361 | isInitialState: true, 362 | }, 363 | ]; 364 | 365 | for (const match of matches) { 366 | const { 367 | ["xstate.state.name"]: stateNameNode, 368 | ["xstate.state.config"]: stateConfigNode, 369 | ["xstate.state"]: fullStateNode, 370 | } = getAllCapturesOfMatch(match); 371 | 372 | if (!stateNameNode || !stateConfigNode || !fullStateNode) continue; 373 | 374 | const stateName = stateNameNode.text; 375 | const parentState = stateObjects.findLast( 376 | (state) => 377 | state.node.startIndex <= fullStateNode.startIndex && 378 | fullStateNode.endIndex <= state.node.endIndex, 379 | ); 380 | const statePath = `${parentState?.path ?? ""}.${stateName}`; 381 | 382 | const stateId = getStateId(stateConfigNode); 383 | const initialState = getInitialState(stateConfigNode); 384 | 385 | stateObjects.push({ 386 | node: fullStateNode, 387 | name: stateName, 388 | path: statePath, 389 | id: stateId, 390 | initialState, 391 | isInitialState: stateName === parentState?.initialState, 392 | }); 393 | } 394 | 395 | return stateObjects; 396 | } 397 | 398 | /** 399 | * Filters the states objects to only include those with the current position. 400 | * The last one will be the current state 401 | */ 402 | export function getStateObjectsAtPosition( 403 | stateObject: StateObject[], 404 | position: number, 405 | ) { 406 | return stateObject.filter( 407 | (state) => 408 | state.node.startIndex <= position && position < state.node.endIndex, 409 | ); 410 | } 411 | 412 | /** 413 | * From a state config node, find the id by iterating through the object 414 | * properties 415 | */ 416 | function getStateId(stateConfigNode: Parser.SyntaxNode) { 417 | if (stateConfigNode.type !== "object") return ""; 418 | for (const pair of stateConfigNode.namedChildren) { 419 | const [key, value] = pair.namedChildren; 420 | if (!key || !value) continue; 421 | if (key.type === "property_identifier" && key.text === "id") { 422 | if (value.type === "string") { 423 | return value.namedChildren[0].text; 424 | } 425 | } 426 | } 427 | return ""; 428 | } 429 | 430 | function getInitialState(stateConfigNode: Parser.SyntaxNode) { 431 | if (stateConfigNode.type !== "object") return ""; 432 | for (const pair of stateConfigNode.namedChildren) { 433 | const [key, value] = pair.namedChildren; 434 | if (!key || !value) continue; 435 | if (key.type === "property_identifier" && key.text === "initial") { 436 | if (value.type === "string") { 437 | return value.namedChildren[0]?.text ?? ""; 438 | } 439 | } 440 | } 441 | return ""; 442 | } 443 | 444 | interface StateTarget { 445 | type: TransitionType; 446 | sortText: string; 447 | transitionName: string; 448 | node: Parser.SyntaxNode; 449 | } 450 | 451 | export function getAllStateTargets( 452 | currentStatePath: string, 453 | machineStateObjects: StateObject[], 454 | ) { 455 | const stateTargets: StateTarget[] = []; 456 | for (const state of machineStateObjects) { 457 | const isCurrentState = state.path === currentStatePath; 458 | // First figure out the ids 459 | if (state.id) { 460 | stateTargets.push({ 461 | type: "absolute", 462 | sortText: getStateSortText("absolute", state.id, isCurrentState), 463 | transitionName: `#${state.id}`, 464 | node: state.node, 465 | }); 466 | for (const childState of machineStateObjects) { 467 | if ( 468 | childState.path.startsWith(state.path) && 469 | childState.path !== state.path 470 | ) { 471 | const childStateAbsolutePath = `${state.id}${childState.path.slice( 472 | state.path.length, 473 | )}`; 474 | stateTargets.push({ 475 | type: "absolute", 476 | sortText: getStateSortText( 477 | "absolute", 478 | childStateAbsolutePath, 479 | childState.path === currentStatePath, 480 | ), 481 | transitionName: `#${childStateAbsolutePath}`, 482 | node: childState.node, 483 | }); 484 | } 485 | } 486 | } 487 | 488 | // The root state can only be reached with an id 489 | if (state.path === "") continue; 490 | 491 | // Handle child states 492 | if (state.path.startsWith(currentStatePath) && !isCurrentState) { 493 | const transitionName = state.path.slice(currentStatePath.length + 1); 494 | stateTargets.push({ 495 | type: "relativeChildren", 496 | sortText: getStateSortText("relativeChildren", transitionName), 497 | transitionName: `.${transitionName}`, 498 | node: state.node, 499 | }); 500 | } 501 | 502 | // Handle sibling states 503 | // The root state node has no siblings 504 | if (currentStatePath === "") continue; 505 | 506 | const parentStatePath = getParentStatePath(currentStatePath); 507 | if (state.path.startsWith(parentStatePath)) { 508 | const transitionName = state.path.slice(parentStatePath.length + 1); 509 | stateTargets.push({ 510 | type: "relative", 511 | sortText: getStateSortText("relative", transitionName, isCurrentState), 512 | transitionName, 513 | node: state.node, 514 | }); 515 | } 516 | } 517 | return stateTargets; 518 | } 519 | 520 | export function getAllDirectChildStateTargets( 521 | currentStatePath: string, 522 | machineStateObjects: StateObject[], 523 | ) { 524 | const stateTargets: StateTarget[] = []; 525 | for (const state of machineStateObjects) { 526 | const currentStateDepth = getStateDepth(currentStatePath); 527 | const stateDepth = getStateDepth(state.path); 528 | 529 | if ( 530 | state.path.startsWith(currentStatePath) && 531 | stateDepth === currentStateDepth + 1 532 | ) { 533 | const transitionName = state.path.slice(currentStatePath.length + 1); 534 | stateTargets.push({ 535 | type: "relativeChildren", 536 | sortText: state.node.startIndex.toString(), 537 | transitionName, 538 | node: state.node, 539 | }); 540 | } 541 | } 542 | return stateTargets; 543 | } 544 | 545 | function getStateDepth(statePath: string) { 546 | return statePath.split(".").length; 547 | } 548 | 549 | const stateSortTextMap = { 550 | relativeChildren: 1, 551 | absolute: 2, 552 | relative: 0, 553 | }; 554 | 555 | function getStateSortText( 556 | transitionType: Exclude, 557 | stateName: string, 558 | isCurrentState?: boolean, 559 | ) { 560 | return `${isCurrentState ? "z" : ""}${stateName.split(".").length - 1}${stateSortTextMap[transitionType]}`; 561 | } 562 | 563 | function getParentStatePath(statePath: string) { 564 | return statePath.split(".").slice(0, -1).join("."); 565 | } 566 | --------------------------------------------------------------------------------