├── .all-contributorsrc ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .editorconfig ├── .eslintignore ├── .eslintrc.json ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md ├── release-drafter.yml └── workflows │ ├── codeql-analysis.yml │ ├── node-ci.yml │ ├── prerelease.yml │ └── release-management.yml ├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc.json ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── config └── jest │ └── setup-jest.ts ├── example ├── example.svg └── example.tsx ├── jest.config.js ├── package.json ├── rollup.config.js ├── src ├── __tests__ │ ├── __snapshots__ │ │ ├── render-id.test.tsx.snap │ │ ├── render-to-dot.spec.tsx.snap │ │ └── render.test.tsx.snap │ ├── render-id.test.tsx │ ├── render-to-dot.spec.tsx │ └── render.test.tsx ├── components │ ├── ClusterPortal.tsx │ ├── Digraph.tsx │ ├── Edge.tsx │ ├── Graph.tsx │ ├── Node.tsx │ ├── Subgraph.tsx │ └── __tests__ │ │ ├── Digraph.spec.tsx │ │ ├── Graph.spec.tsx │ │ ├── Node.spec.tsx │ │ ├── __snapshots__ │ │ └── Node.spec.tsx.snap │ │ └── utils │ │ └── renderExpectToThrow.tsx ├── contexts │ ├── ClusterMap.ts │ ├── ContainerCluster.ts │ ├── CurrentCluster.ts │ └── GraphvizContext.ts ├── errors.ts ├── hooks │ ├── __tests__ │ │ ├── __snapshots__ │ │ │ └── use-rendered-id.spec.tsx.snap │ │ ├── use-container-cluster.spec.ts │ │ ├── use-current-cluster.spec.ts │ │ ├── use-digraph.spec.ts │ │ ├── use-edge.spec.ts │ │ ├── use-graph.spec.ts │ │ ├── use-graphviz-context.spec.ts │ │ ├── use-node.spec.ts │ │ ├── use-rendered-id.spec.tsx │ │ ├── use-subgraph.spec.ts │ │ └── utils │ │ │ └── wrapper.tsx │ ├── use-cluster-attributes.ts │ ├── use-cluster-map.ts │ ├── use-comment.ts │ ├── use-container-cluster.ts │ ├── use-current-cluster.ts │ ├── use-digraph.ts │ ├── use-edge.ts │ ├── use-graph.ts │ ├── use-graphviz-context.ts │ ├── use-has-attributes.ts │ ├── use-node.ts │ ├── use-rendered-id.ts │ └── use-subgraph.ts ├── index.ts ├── labels.ts ├── reconciler.ts ├── render-id.ts ├── render.ts └── types.ts ├── tsconfig.json └── yarn.lock /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "files": [ 3 | "README.md" 4 | ], 5 | "imageSize": 100, 6 | "commit": false, 7 | "contributors": [ 8 | { 9 | "login": "kamiazya", 10 | "name": "Yuki Yamazaki", 11 | "avatar_url": "https://avatars0.githubusercontent.com/u/35218186?v=4", 12 | "profile": "http://blog.kamiazya.tech/", 13 | "contributions": [ 14 | "code", 15 | "test", 16 | "ideas", 17 | "doc" 18 | ] 19 | }, 20 | { 21 | "login": "nagasawaryoya", 22 | "name": "nagasawaryoya", 23 | "avatar_url": "https://avatars.githubusercontent.com/u/53528726?v=4", 24 | "profile": "https://github.com/nagasawaryoya", 25 | "contributions": [ 26 | "code", 27 | "test" 28 | ] 29 | }, 30 | { 31 | "login": "tokidrill", 32 | "name": "YukiSasaki", 33 | "avatar_url": "https://avatars.githubusercontent.com/u/42460318?v=4", 34 | "profile": "https://github.com/tokidrill", 35 | "contributions": [ 36 | "code", 37 | "test" 38 | ] 39 | } 40 | ], 41 | "contributorsPerLine": 7, 42 | "projectName": "react", 43 | "projectOwner": "ts-graphviz", 44 | "repoType": "github", 45 | "repoHost": "https://github.com", 46 | "skipCi": true 47 | } 48 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.192.0/containers/typescript-node/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] Node.js version: 16, 14, 12 4 | ARG VARIANT="16-buster" 5 | FROM mcr.microsoft.com/vscode/devcontainers/typescript-node:0-${VARIANT} 6 | 7 | # [Optional] Uncomment this section to install additional OS packages. 8 | RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 9 | && apt-get -y install --no-install-recommends graphviz 10 | 11 | # [Optional] Uncomment if you want to install an additional version of node using nvm 12 | # ARG EXTRA_NODE_VERSION=10 13 | # RUN su node -c "source /usr/local/share/nvm/nvm.sh && nvm install ${EXTRA_NODE_VERSION}" 14 | 15 | # [Optional] Uncomment if you want to install more global node packages 16 | # RUN su node -c "npm install -g " 17 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.192.0/containers/typescript-node 3 | { 4 | "name": "ts-graphviz", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | // Update 'VARIANT' to pick a Node version: 12, 14, 16 8 | "args": { 9 | "VARIANT": "16" 10 | } 11 | }, 12 | // Set *default* container specific settings.json values on container create. 13 | "settings": { 14 | "editor.formatOnSave": false, 15 | "editor.formatOnPaste": false, 16 | "editor.formatOnType": false, 17 | "editor.codeActionsOnSave": { 18 | "source.fixAll.eslint": true 19 | }, 20 | "typescript.tsdk": "node_modules/typescript/lib" 21 | }, 22 | // Add the IDs of extensions you want installed when the container is created. 23 | "extensions": [ 24 | "EditorConfig.EditorConfig", 25 | "esbenp.prettier-vscode", 26 | "dbaeumer.vscode-eslint", 27 | "Orta.vscode-jest" 28 | ], 29 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 30 | // "forwardPorts": [], 31 | // Use 'postCreateCommand' to run commands after the container is created. 32 | "postCreateCommand": "yarn install", 33 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 34 | "remoteUser": "node" 35 | } 36 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "env": { 4 | "jest/globals": true 5 | }, 6 | "parserOptions": { 7 | "ecmaFeatures": { 8 | "jsx": true 9 | }, 10 | "useJSXTextNode": true 11 | }, 12 | "settings": { 13 | "react": { 14 | "version": "detect" 15 | }, 16 | "import/resolver": { 17 | "node": { 18 | "extensions": [ 19 | ".js", 20 | ".jsx", 21 | ".ts", 22 | ".tsx" 23 | ] 24 | } 25 | } 26 | }, 27 | "plugins": [ 28 | "@typescript-eslint", 29 | "prettier", 30 | "jest" 31 | ], 32 | "extends": [ 33 | "airbnb", 34 | "plugin:prettier/recommended", 35 | "plugin:@typescript-eslint/recommended", 36 | "prettier", 37 | "plugin:jest/recommended", 38 | "plugin:react-hooks/recommended" 39 | ], 40 | "rules": { 41 | "@typescript-eslint/no-explicit-any": "off", 42 | "no-use-before-define": [0], 43 | "@typescript-eslint/no-use-before-define": [1], 44 | "prettier/prettier": "error", 45 | "import/extensions": "off", 46 | "import/prefer-default-export": "off", 47 | "import/no-extraneous-dependencies": "off", 48 | "react/forbid-prop-types": "off", 49 | "react/jsx-wrap-multilines": "off", 50 | "react/prop-types": [ 51 | 2, 52 | { 53 | "ignore": [ 54 | "children" 55 | ] 56 | } 57 | ], 58 | "react/jsx-filename-extension": [ 59 | 1, 60 | { 61 | "extensions": [ 62 | ".tx", 63 | ".tsx" 64 | ] 65 | } 66 | ] 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## Describe the bug 11 | 12 | A clear and concise description of what the bug is. 13 | 14 | ## To Reproduce 15 | 16 | Steps to reproduce the behavior: 17 | 18 | ```typescript 19 | // Sample code here. 20 | ``` 21 | 22 | ## Expected behavior 23 | 24 | A clear and concise description of what you expected to happen. 25 | 26 | ## Additional context 27 | 28 | Add any other context about the problem here. 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when ... 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### What was a problem 4 | 5 | {Please write here} 6 | 7 | ### How this PR fixes the problem 8 | 9 | {Please write here} 10 | 11 | ### Check lists (check `x` in `[ ]` of list items) 12 | 13 | - [ ] Test passed 14 | - [ ] Coding style (indentation, etc) 15 | 16 | ### Additional Comments (if any) 17 | 18 | {Please write here} 19 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: v$NEXT_PATCH_VERSION 🌈 2 | tag-template: v$NEXT_PATCH_VERSION 3 | categories: 4 | - title: 🚀 Features 5 | labels: 6 | - feature 7 | - enhancement 8 | - title: 🐛 Bug Fixes 9 | labels: 10 | - fix 11 | - bugfix 12 | - bug 13 | - title: 🧰 Maintenance 14 | labels: 15 | - chore 16 | - docs 17 | - doc 18 | change-template: '- $TITLE @$AUTHOR (#$NUMBER)' 19 | template: | 20 | ## Changes 21 | 22 | $CHANGES 23 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '26 10 * * 4' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 37 | # Learn more: 38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 39 | 40 | steps: 41 | - name: Checkout repository 42 | uses: actions/checkout@v2 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /.github/workflows/node-ci.yml: -------------------------------------------------------------------------------- 1 | name: NodeCI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | name: Test on node ${{ matrix.node-version }} and ${{ matrix.os }} 8 | runs-on: ${{ matrix.os }} 9 | strategy: 10 | matrix: 11 | node-version: [12.x, 14.x] 12 | os: [ubuntu-latest] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Use Node.js ${{ matrix.node-version }} on ubuntu-latest 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - name: setup grapgviz 21 | uses: ts-graphviz/setup-graphviz@v1 22 | - name: Install dependencies 23 | run: yarn --frozen-lockfile --ignore-optional 24 | env: 25 | CI: 'true' 26 | - name: Lint 27 | run: yarn lint 28 | env: 29 | CI: 'true' 30 | - name: Test 31 | run: yarn test 32 | env: 33 | CI: 'true' 34 | - name: Build 35 | run: yarn build 36 | env: 37 | CI: 'true' 38 | 39 | publish: 40 | name: Publish to NPM 41 | runs-on: ubuntu-latest 42 | needs: 43 | - test 44 | steps: 45 | - uses: actions/checkout@master 46 | - uses: actions/setup-node@v1 47 | with: 48 | node-version: 12.x 49 | registry-url: https://registry.npmjs.org 50 | - name: Install dependencies 51 | run: yarn install --frozen-lockfile --ignore-optional 52 | if: contains(github.ref, 'tags/v') 53 | env: 54 | CI: 'true' 55 | - name: Build 56 | run: yarn build 57 | if: contains(github.ref, 'tags/v') 58 | - name: Publish to NPM 59 | run: npm publish 60 | env: 61 | NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }} 62 | if: contains(github.ref, 'tags/v') 63 | -------------------------------------------------------------------------------- /.github/workflows/prerelease.yml: -------------------------------------------------------------------------------- 1 | name: Prerelease 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: 'Version of the package to publish (e.g. 0.0.0-0)' 8 | required: true 9 | 10 | jobs: 11 | prerelease: 12 | name: Prerelease 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@master 16 | - uses: actions/setup-node@v1 17 | with: 18 | node-version: 14.x 19 | registry-url: https://registry.npmjs.org 20 | - name: Validate Version 21 | run: node -e 'if (!/\d+\.\d+\.\d\-\d+/.test("${{ github.event.inputs.version }}")) process.exit(1);' 22 | - name: Install dependencies 23 | run: yarn install --frozen-lockfile --ignore-optional 24 | env: 25 | CI: 'true' 26 | - name: Build 27 | run: yarn build 28 | - name: Fix version 29 | run: |- 30 | cp package.json tmp.json 31 | jq '.version|="${{ github.event.inputs.version }}"' tmp.json -M > package.json 32 | rm -f tmp.json 33 | - name: Publish to NPM 34 | run: npm publish --tag next 35 | env: 36 | NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }} 37 | -------------------------------------------------------------------------------- /.github/workflows/release-management.yml: -------------------------------------------------------------------------------- 1 | name: Release Management 2 | 3 | on: 4 | push: 5 | # branches to consider in the event; optional, defaults to all 6 | branches: 7 | - main 8 | 9 | jobs: 10 | update_draft_release: 11 | runs-on: ubuntu-latest 12 | steps: 13 | # Drafts your next Release notes as Pull Requests are merged into "main" 14 | - uses: toolmantim/release-drafter@v5.2.0 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/node 3 | # Edit at https://www.gitignore.io/?templates=node 4 | 5 | ### Node ### 6 | # Logs 7 | logs 8 | *.log 9 | npm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # TypeScript v1 declaration files 50 | typings/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Optional REPL history 62 | .node_repl_history 63 | 64 | # Output of 'npm pack' 65 | *.tgz 66 | 67 | # Yarn Integrity file 68 | .yarn-integrity 69 | 70 | # dotenv environment variables file 71 | .env 72 | .env.test 73 | 74 | # parcel-bundler cache (https://parceljs.org/) 75 | .cache 76 | 77 | # next.js build output 78 | .next 79 | 80 | # nuxt.js build output 81 | .nuxt 82 | 83 | # react / gatsby 84 | public/ 85 | 86 | # vuepress build output 87 | .vuepress/dist 88 | 89 | # Serverless directories 90 | .serverless/ 91 | 92 | # FuseBox cache 93 | .fusebox/ 94 | 95 | # DynamoDB Local files 96 | .dynamodb/ 97 | 98 | # End of https://www.gitignore.io/api/node 99 | 100 | # Created by https://www.gitignore.io/api/macos 101 | # Edit at https://www.gitignore.io/?templates=macos 102 | 103 | ### macOS ### 104 | # General 105 | .DS_Store 106 | .AppleDouble 107 | .LSOverride 108 | 109 | # Icon must end with two \r 110 | Icon 111 | 112 | # Thumbnails 113 | ._* 114 | 115 | # Files that might appear in the root of a volume 116 | .DocumentRevisions-V100 117 | .fseventsd 118 | .Spotlight-V100 119 | .TemporaryItems 120 | .Trashes 121 | .VolumeIcon.icns 122 | .com.apple.timemachine.donotpresent 123 | 124 | # Directories potentially created on remote AFP share 125 | .AppleDB 126 | .AppleDesktop 127 | Network Trash Folder 128 | Temporary Items 129 | .apdisk 130 | 131 | # End of https://www.gitignore.io/api/macos 132 | 133 | # Output Modules 134 | lib 135 | docs 136 | !src/**/* 137 | *.d.ts 138 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .editorconfig 2 | .eslintrc.json 3 | .github 4 | .gitignore 5 | .prettierignore 6 | .prettierrc.json 7 | .vscode 8 | config 9 | coverage 10 | docs 11 | jest.config.js 12 | LICENSE 13 | rollup.build.ts 14 | src 15 | tsconfig.json 16 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/prettierrc", 3 | "singleQuote": true, 4 | "semi": true, 5 | "trailingComma": "all", 6 | "printWidth": 120, 7 | "bracketSpacing": true, 8 | "endOfLine": "auto" 9 | } 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": false, 3 | "editor.formatOnPaste": false, 4 | "editor.formatOnType": false, 5 | "editor.codeActionsOnSave": { 6 | "source.fixAll.eslint": true 7 | }, 8 | "markdownlint.config": { 9 | "default": true, 10 | "MD041": false 11 | }, 12 | "typescript.tsdk": "node_modules/typescript/lib" 13 | } 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | The MIT License (MIT) 3 | 4 | Copyright (c) 2020 Yuki Yamazaki 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # This Repository is archived. 3 | # Moved to 4 | 5 | --- 6 | 7 | [![NodeCI](https://github.com/ts-graphviz/react/workflows/NodeCI/badge.svg)](https://github.com/ts-graphviz/react/actions?workflow=NodeCI) 8 | [![npm version](https://badge.fury.io/js/%40ts-graphviz%2Freact.svg)](https://badge.fury.io/js/%40ts-graphviz%2Freact) 9 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 10 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) 11 | [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) 12 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) 13 | [![All Contributors](https://img.shields.io/badge/all_contributors-3-orange.svg?style=flat-square)](#contributors-) 14 | 15 | 16 | 17 | # @ts-graphviz/react 18 | 19 | Graphviz-dot Renderer using React. 20 | 21 | ## Installation 22 | 23 | The module can then be installed using [npm](https://www.npmjs.com/): 24 | 25 | [![NPM](https://nodei.co/npm/@ts-graphviz/react.png)](https://nodei.co/npm/@ts-graphviz/react/) 26 | 27 | ```bash 28 | # yarn 29 | $ yarn add @ts-graphviz/react react 30 | # or npm 31 | $ npm install -S @ts-graphviz/react react 32 | ``` 33 | 34 | > Install [React](https://github.com/facebook/react/) as peerDependencies at the same time. 35 | 36 | ## Example 37 | 38 | ```jsx 39 | import React from 'react'; 40 | import { Digraph, Node, Subgraph, Edge, DOT, renderToDot } from '@ts-graphviz/react'; 41 | 42 | const Example = () => ( 43 | 53 | 58 | 59 | left 60 | middle 61 | right 62 | 63 | 64 | } 65 | /> 66 | 67 | 68 | 69 | 70 | A to B} /> 71 | 72 | ); 73 | 74 | const dot = renderToDot(); 75 | 76 | console.log(dot); 77 | ``` 78 | 79 | ### Output dot 80 | 81 | ```dot 82 | digraph { 83 | rankdir = "TB"; 84 | edge [ 85 | color = "blue", 86 | fontcolor = "blue", 87 | ]; 88 | node [ 89 | shape = "none", 90 | ]; 91 | "nodeA" [ 92 | shape = "none", 93 | label = <
leftmiddleright
>, 94 | ]; 95 | subgraph "cluster" { 96 | labeljust = "l"; 97 | label = "Cluster"; 98 | "nodeB" [ 99 | label = "This is label for nodeB.", 100 | ]; 101 | } 102 | // Edge from node A to B 103 | "nodeB" -> "nodeA":"m" [ 104 | label = <A to B>, 105 | ]; 106 | } 107 | ``` 108 | 109 | ![dot](./example/example.svg) 110 | 111 | ## See Also 112 | 113 | Graphviz-dot Test and Integration 114 | 115 | - [ts-graphviz](https://github.com/ts-graphviz/ts-graphviz) 116 | - Graphviz library for TypeScript. 117 | - [jest-graphviz](https://github.com/ts-graphviz/jest-graphviz) 118 | - Jest matchers that supports graphviz integration. 119 | - [setup-graphviz](https://github.com/ts-graphviz/setup-graphviz) 120 | - GitHub Action to set up Graphviz cross-platform(Linux, macOS, Windows). 121 | 122 | ## Contributors 123 | 124 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 |

Yuki Yamazaki

💻 ⚠️ 🤔 📖

nagasawaryoya

💻 ⚠️

YukiSasaki

💻 ⚠️
136 | 137 | 138 | 139 | 140 | 141 | 142 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) 143 | specification. Contributions of any kind welcome! 144 | 145 | ## License 146 | 147 | This software is released under the MIT License, see [LICENSE](./LICENSE). 148 | -------------------------------------------------------------------------------- /config/jest/setup-jest.ts: -------------------------------------------------------------------------------- 1 | import 'jest-graphviz'; 2 | -------------------------------------------------------------------------------- /example/example.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | %3 11 | 12 | 13 | cluster 14 | 15 | Cluster 16 | 17 | 18 | 19 | nodeA 20 | 21 | left 22 | 23 | middle 24 | 25 | right 26 | 27 | 28 | 29 | nodeB 30 | This is label for nodeB. 31 | 32 | 33 | 34 | nodeB->nodeA:m 35 | 36 | 37 | A to B 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /example/example.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC } from 'react'; 2 | import { Digraph, Node, Subgraph, renderToDot, Edge, DOT } from '../src'; 3 | 4 | const Example: FC = () => ( 5 | 15 | 20 | 21 | left 22 | middle 23 | right 24 | 25 | 26 | } 27 | /> 28 | 29 | 30 | 31 | 32 | A to B} /> 33 | 34 | ); 35 | 36 | const dot = renderToDot(); 37 | 38 | // eslint-disable-next-line no-console 39 | console.log(dot); 40 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'jsdom', 4 | verbose: true, 5 | collectCoverage: true, 6 | setupFilesAfterEnv: ['/config/jest/setup-jest.ts'], 7 | roots: ['/src'], 8 | transform: { 9 | '^.+\\.tsx?$': 'ts-jest', 10 | }, 11 | testMatch: ['**/(__tests__|__specs__)/**/*.(spec|test).(ts|tsx)'], 12 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 13 | }; 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ts-graphviz/react", 3 | "version": "0.9.1", 4 | "license": "MIT", 5 | "author": "kamiazya ", 6 | "description": "Graphviz-dot Renderer for React.", 7 | "repository": { 8 | "type": "git", 9 | "url": "https://github.com/ts-graphviz/react.git" 10 | }, 11 | "bugs": { 12 | "url": "https://github.com/ts-graphviz/react/issues" 13 | }, 14 | "funding": { 15 | "type": "github", 16 | "url": "https://github.com/sponsors/kamiazya" 17 | }, 18 | "keywords": [ 19 | "graphviz", 20 | "dot", 21 | "react" 22 | ], 23 | "publishConfig": { 24 | "access": "public" 25 | }, 26 | "main": "./lib/index.js", 27 | "exports": { 28 | "import": "./lib/index.mjs", 29 | "default": "./lib/index.js" 30 | }, 31 | "types": "./lib/index.d.ts", 32 | "scripts": { 33 | "example": "ts-node example/example", 34 | "build": "rollup -c && prettier --write './lib/index.d.ts'", 35 | "test": "jest", 36 | "lint": "eslint -c .eslintrc.json --ext ts,tsx src", 37 | "format": "eslint -c .eslintrc.json --ext ts,tsx src --fix && prettier --write './src/**/*.(ts|tsx)'" 38 | }, 39 | "peerDependencies": { 40 | "react": ">=16.8.0 || >=17" 41 | }, 42 | "dependencies": { 43 | "prop-types": "^15.7.2", 44 | "react-dom": "^17.0.2", 45 | "react-reconciler": "^0.26.2", 46 | "ts-graphviz": "^0.16.0" 47 | }, 48 | "devDependencies": { 49 | "@testing-library/jest-dom": "^5.12.0", 50 | "@testing-library/react": "^11.2.7", 51 | "@testing-library/react-hooks": "^5.1.2", 52 | "@types/prop-types": "^15.7.3", 53 | "@types/react": "^17.0.5", 54 | "@types/react-dom": "^17.0.5", 55 | "@types/react-reconciler": "^0.26.1", 56 | "@typescript-eslint/eslint-plugin": "^4.23.0", 57 | "@typescript-eslint/parser": "^4.23.0", 58 | "eslint": "^7.26.0", 59 | "eslint-config-airbnb": "^18.2.1", 60 | "eslint-config-prettier": "^8.3.0", 61 | "eslint-plugin-import": "^2.23.1", 62 | "eslint-plugin-jest": "^24.3.6", 63 | "eslint-plugin-jsx-a11y": "^6.4.1", 64 | "eslint-plugin-prettier": "^3.4.0", 65 | "eslint-plugin-react": "^7.23.2", 66 | "eslint-plugin-react-hooks": "^4.2.0", 67 | "jest": "^26.6.3", 68 | "jest-graphviz": "^0.4.0", 69 | "prettier": "^2.3.0", 70 | "react": "^17.0.2", 71 | "react-test-renderer": "^17.0.2", 72 | "rollup": "^2.48.0", 73 | "rollup-plugin-delete": "^2.0.0", 74 | "rollup-plugin-dts": "^3.0.1", 75 | "rollup-plugin-terser": "^7.0.2", 76 | "rollup-plugin-typescript2": "^0.30.0", 77 | "ts-jest": "^26.5.6", 78 | "ts-node": "^9.1.1", 79 | "typescript": "^4.2.4" 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from 'rollup-plugin-typescript2'; 2 | import del from 'rollup-plugin-delete'; 3 | import dts from 'rollup-plugin-dts'; 4 | import { terser } from 'rollup-plugin-terser'; 5 | 6 | /** @type {import('rollup').RollupOptions[]} */ 7 | const options = [ 8 | { 9 | input: './src/index.ts', 10 | plugins: [ 11 | typescript({ 12 | tsconfigOverride: { 13 | compilerOptions: { 14 | module: 'ESNext', 15 | declaration: true, 16 | }, 17 | }, 18 | }), 19 | terser({ 20 | format: { 21 | comments: false, 22 | }, 23 | }), 24 | ], 25 | external: ['react', 'react-dom/server.js', 'ts-graphviz', 'prop-types', 'react-reconciler'], 26 | output: [ 27 | { 28 | format: 'cjs', 29 | file: './lib/index.js', 30 | }, 31 | { 32 | format: 'esm', 33 | file: './lib/index.mjs', 34 | }, 35 | ], 36 | }, 37 | { 38 | input: './lib/index.d.ts', 39 | plugins: [ 40 | del({ 41 | targets: ['lib/**/*.d.ts', '!lib/index.d.ts'], 42 | hook: 'buildEnd', 43 | }), 44 | dts(), 45 | ], 46 | output: [ 47 | { 48 | format: 'esm', 49 | file: './lib/index.d.ts', 50 | }, 51 | ], 52 | }, 53 | ]; 54 | 55 | export default options; 56 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/render-id.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renderId case 1`] = `"hoge"`; 4 | 5 | exports[`renderId case 2`] = `"<bold>"`; 6 | 7 | exports[`renderId case 3`] = `"<bold>"`; 8 | 9 | exports[`renderId case 4`] = `">"`; 10 | 11 | exports[`renderId case 5`] = `"<
leftmiddleright
>"`; 12 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/render-to-dot.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renderToDot render edge 1`] = ` 4 | digraph { 5 | "a" -> "b"; 6 | } 7 | `; 8 | 9 | exports[`renderToDot render subgraph 1`] = ` 10 | digraph { 11 | subgraph { 12 | "a" -> "b"; 13 | } 14 | } 15 | `; 16 | 17 | exports[`renderToDot render works 1`] = ` 18 | digraph { 19 | "a"; 20 | "b"; 21 | } 22 | `; 23 | -------------------------------------------------------------------------------- /src/__tests__/__snapshots__/render.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`renderToDot render to container subgraph test 1`] = ` 4 | digraph { 5 | subgraph "test" { 6 | "a" -> "b"; 7 | } 8 | } 9 | `; 10 | -------------------------------------------------------------------------------- /src/__tests__/render-id.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { DOT } from '../labels'; 3 | import { renderId } from '../render-id'; 4 | 5 | describe('renderId', () => { 6 | test('return undefined when give parameter is undefined', () => { 7 | expect(renderId(undefined)).toBeUndefined(); 8 | }); 9 | 10 | test.each([ 11 | 'hoge', 12 | '<bold>', 13 | bold, 14 | <> 15 | label 16 | port 17 | , 18 | 19 | 20 | left 21 | middle 22 | right 23 | 24 | , 25 | ])('case', (id) => { 26 | expect(renderId(id)).toMatchSnapshot(); 27 | }); 28 | }); 29 | -------------------------------------------------------------------------------- /src/__tests__/render-to-dot.spec.tsx: -------------------------------------------------------------------------------- 1 | // tslint:disable: jsx-no-multiline-js 2 | import React from 'react'; 3 | import 'jest-graphviz'; 4 | import { EdgeTargetLikeTuple } from 'ts-graphviz'; 5 | import { Edge } from '../components/Edge'; 6 | import { Subgraph } from '../components/Subgraph'; 7 | import { Digraph } from '../components/Digraph'; 8 | import { Node } from '../components/Node'; 9 | import { renderToDot } from '../render'; 10 | 11 | describe('renderToDot', () => { 12 | it('render works', () => { 13 | const dot = renderToDot( 14 | 15 | 16 | 17 | , 18 | ); 19 | expect(dot).toBeValidDotAndMatchSnapshot(); 20 | }); 21 | 22 | it('render edge', () => { 23 | const nodes: EdgeTargetLikeTuple = ['a', 'b']; 24 | const dot = renderToDot( 25 | 26 | 27 | , 28 | ); 29 | expect(dot).toBeValidDotAndMatchSnapshot(); 30 | }); 31 | 32 | it('render subgraph', () => { 33 | const nodes: EdgeTargetLikeTuple = ['a', 'b']; 34 | const dot = renderToDot( 35 | 36 | 37 | 38 | 39 | , 40 | ); 41 | expect(dot).toBeValidDotAndMatchSnapshot(); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /src/__tests__/render.test.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable jest/expect-expect */ 2 | import React from 'react'; 3 | import 'jest-graphviz'; 4 | import { digraph, EdgeTargetLikeTuple, toDot } from 'ts-graphviz'; 5 | import { Edge } from '../components/Edge'; 6 | import { Node } from '../components/Node'; 7 | import { renderExpectToThrow } from '../components/__tests__/utils/renderExpectToThrow'; 8 | import { NoContainerErrorMessage } from '../errors'; 9 | import { render } from '../render'; 10 | 11 | describe('renderToDot', () => { 12 | describe('no container error', () => { 13 | test('Fragment', () => { 14 | renderExpectToThrow(<>, NoContainerErrorMessage); 15 | }); 16 | 17 | test('Node', () => { 18 | renderExpectToThrow(, NoContainerErrorMessage); 19 | }); 20 | 21 | test('Edge', () => { 22 | renderExpectToThrow(, NoContainerErrorMessage); 23 | }); 24 | }); 25 | 26 | it('render to container subgraph test', () => { 27 | const nodes: EdgeTargetLikeTuple = ['a', 'b']; 28 | const G = digraph(); 29 | const subgraph = render(, G.subgraph('test')); 30 | expect(G.subgraph('test')).toEqual(subgraph); 31 | expect(toDot(G)).toBeValidDotAndMatchSnapshot(); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /src/components/ClusterPortal.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useContext, useMemo } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { CurrentCluster } from '../contexts/CurrentCluster'; 4 | import { ClusterMap } from '../contexts/ClusterMap'; 5 | import { useContainerCluster } from '../hooks/use-container-cluster'; 6 | import { ClusterPortalProps } from '../types'; 7 | 8 | /** 9 | * ClusterPortal component. 10 | */ 11 | export const ClusterPortal: FC = ({ children, id }) => { 12 | const container = useContainerCluster(); 13 | const map = useContext(ClusterMap); 14 | const cluster = useMemo(() => (id ? map.get(id) ?? container : container), [container, map, id]); 15 | return {children}; 16 | }; 17 | 18 | ClusterPortal.displayName = 'ClusterPortal'; 19 | ClusterPortal.defaultProps = { 20 | id: undefined, 21 | }; 22 | 23 | ClusterPortal.propTypes = { 24 | id: PropTypes.string, 25 | }; 26 | -------------------------------------------------------------------------------- /src/components/Digraph.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { ContainerCluster } from '../contexts/ContainerCluster'; 4 | import { CurrentCluster } from '../contexts/CurrentCluster'; 5 | import { useDigraph } from '../hooks/use-digraph'; 6 | import { useRenderedID } from '../hooks/use-rendered-id'; 7 | import { useContainerCluster } from '../hooks/use-container-cluster'; 8 | import { DuplicatedRootClusterErrorMessage } from '../errors'; 9 | import { useClusterMap } from '../hooks/use-cluster-map'; 10 | import { RootClusterProps } from '../types'; 11 | 12 | /** 13 | * `Digraph` component. 14 | */ 15 | export const Digraph: FC = ({ children, label, ...options }) => { 16 | const container = useContainerCluster(); 17 | if (container !== null) { 18 | throw Error(DuplicatedRootClusterErrorMessage); 19 | } 20 | const renderedLabel = useRenderedID(label); 21 | if (renderedLabel !== undefined) Object.assign(options, { label: renderedLabel }); 22 | const digraph = useDigraph(options); 23 | const clusters = useClusterMap(); 24 | useEffect(() => { 25 | if (digraph.id !== undefined) { 26 | clusters.set(digraph.id, digraph); 27 | } 28 | }, [clusters, digraph]); 29 | return ( 30 | 31 | {children} 32 | 33 | ); 34 | }; 35 | 36 | Digraph.displayName = 'Digraph'; 37 | 38 | Digraph.defaultProps = { 39 | id: undefined, 40 | comment: undefined, 41 | label: undefined, 42 | }; 43 | 44 | Digraph.propTypes = { 45 | id: PropTypes.string, 46 | comment: PropTypes.string, 47 | label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 48 | }; 49 | -------------------------------------------------------------------------------- /src/components/Edge.tsx: -------------------------------------------------------------------------------- 1 | import { VFC } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { useEdge } from '../hooks/use-edge'; 4 | import { useRenderedID } from '../hooks/use-rendered-id'; 5 | import { EdgeProps } from '../types'; 6 | 7 | /** 8 | * `Edge` component. 9 | */ 10 | export const Edge: VFC = ({ targets, label, ...options }) => { 11 | const renderedLabel = useRenderedID(label); 12 | if (renderedLabel !== undefined) Object.assign(options, { label: renderedLabel }); 13 | useEdge(targets, options); 14 | return null; 15 | }; 16 | 17 | Edge.displayName = 'Edge'; 18 | 19 | Edge.propTypes = { 20 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 21 | // @ts-ignore 22 | targets: PropTypes.array.isRequired, 23 | comment: PropTypes.string, 24 | label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 25 | }; 26 | 27 | Edge.defaultProps = { 28 | comment: undefined, 29 | label: undefined, 30 | }; 31 | -------------------------------------------------------------------------------- /src/components/Graph.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { ContainerCluster } from '../contexts/ContainerCluster'; 4 | import { CurrentCluster } from '../contexts/CurrentCluster'; 5 | import { useGraph } from '../hooks/use-graph'; 6 | import { useRenderedID } from '../hooks/use-rendered-id'; 7 | import { useContainerCluster } from '../hooks/use-container-cluster'; 8 | import { DuplicatedRootClusterErrorMessage } from '../errors'; 9 | import { useClusterMap } from '../hooks/use-cluster-map'; 10 | import { RootClusterProps } from '../types'; 11 | /** 12 | * `Graph` component. 13 | */ 14 | export const Graph: FC = ({ children, label, ...options }) => { 15 | const container = useContainerCluster(); 16 | if (container !== null) { 17 | throw Error(DuplicatedRootClusterErrorMessage); 18 | } 19 | const renderedLabel = useRenderedID(label); 20 | if (renderedLabel !== undefined) Object.assign(options, { label: renderedLabel }); 21 | const graph = useGraph(options); 22 | const clusters = useClusterMap(); 23 | useEffect(() => { 24 | if (graph.id !== undefined) { 25 | clusters.set(graph.id, graph); 26 | } 27 | }, [clusters, graph]); 28 | return ( 29 | 30 | {children} 31 | 32 | ); 33 | }; 34 | 35 | Graph.displayName = 'Graph'; 36 | 37 | Graph.defaultProps = { 38 | id: undefined, 39 | comment: undefined, 40 | label: undefined, 41 | }; 42 | 43 | Graph.propTypes = { 44 | id: PropTypes.string, 45 | comment: PropTypes.string, 46 | label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 47 | }; 48 | -------------------------------------------------------------------------------- /src/components/Node.tsx: -------------------------------------------------------------------------------- 1 | import { VFC } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { useNode } from '../hooks/use-node'; 4 | import { useRenderedID } from '../hooks/use-rendered-id'; 5 | import { NodeProps } from '../types'; 6 | 7 | /** 8 | * `Node` component. 9 | */ 10 | export const Node: VFC = ({ id, label, xlabel, ...options }) => { 11 | const renderedLabel = useRenderedID(label); 12 | const renderedXlabel = useRenderedID(xlabel); 13 | 14 | if (renderedLabel !== undefined) Object.assign(options, { label: renderedLabel }); 15 | if (renderedXlabel !== undefined) Object.assign(options, { xlabel: renderedXlabel }); 16 | useNode(id, options); 17 | return null; 18 | }; 19 | 20 | Node.displayName = 'Node'; 21 | 22 | Node.propTypes = { 23 | id: PropTypes.string.isRequired, 24 | comment: PropTypes.string, 25 | label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 26 | xlabel: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 27 | }; 28 | 29 | Node.defaultProps = { 30 | comment: undefined, 31 | label: undefined, 32 | xlabel: undefined, 33 | }; 34 | -------------------------------------------------------------------------------- /src/components/Subgraph.tsx: -------------------------------------------------------------------------------- 1 | import React, { FC, useEffect } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { CurrentCluster } from '../contexts/CurrentCluster'; 4 | import { useSubgraph } from '../hooks/use-subgraph'; 5 | import { useRenderedID } from '../hooks/use-rendered-id'; 6 | import { useClusterMap } from '../hooks/use-cluster-map'; 7 | import { SubgraphProps } from '../types'; 8 | /** 9 | * `Subgraph` component. 10 | */ 11 | export const Subgraph: FC = ({ children, label, ...options }) => { 12 | const renderedLabel = useRenderedID(label); 13 | if (renderedLabel !== undefined) Object.assign(options, { label: renderedLabel }); 14 | const subgraph = useSubgraph(options); 15 | const clusters = useClusterMap(); 16 | useEffect(() => { 17 | if (subgraph.id !== undefined) { 18 | clusters.set(subgraph.id, subgraph); 19 | } 20 | }, [subgraph, clusters]); 21 | return {children}; 22 | }; 23 | 24 | Subgraph.displayName = 'Subgraph'; 25 | 26 | Subgraph.propTypes = { 27 | id: PropTypes.string, 28 | comment: PropTypes.string, 29 | label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), 30 | }; 31 | 32 | Subgraph.defaultProps = { 33 | id: undefined, 34 | comment: undefined, 35 | label: undefined, 36 | }; 37 | -------------------------------------------------------------------------------- /src/components/__tests__/Digraph.spec.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Digraph } from '../Digraph'; 3 | import { DuplicatedRootClusterErrorMessage } from '../../errors'; 4 | import { renderExpectToThrow } from './utils/renderExpectToThrow'; 5 | 6 | describe('Digraph', () => { 7 | // eslint-disable-next-line jest/expect-expect 8 | test('An error occurs when duplicate ', () => { 9 | renderExpectToThrow( 10 | 11 | 12 | , 13 | DuplicatedRootClusterErrorMessage, 14 | ); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/components/__tests__/Graph.spec.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Graph } from '../Graph'; 3 | import { DuplicatedRootClusterErrorMessage } from '../../errors'; 4 | import { renderExpectToThrow } from './utils/renderExpectToThrow'; 5 | 6 | describe('Graph', () => { 7 | // eslint-disable-next-line jest/expect-expect 8 | test('An error occurs when duplicate ', () => { 9 | renderExpectToThrow( 10 | 11 | 12 | , 13 | DuplicatedRootClusterErrorMessage, 14 | ); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/components/__tests__/Node.spec.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import 'jest-graphviz'; 3 | import { Digraph } from '../Digraph'; 4 | import { Node } from '../Node'; 5 | import { DOT } from '../../labels'; 6 | import { renderToDot } from '../../render'; 7 | 8 | describe('Node', () => { 9 | test('pass without optional props and render correctly', () => { 10 | const dot = renderToDot( 11 | 12 | 13 | , 14 | ); 15 | expect(dot).toBeValidDotAndMatchSnapshot(); 16 | }); 17 | 18 | test('pass label with string and render correctly', () => { 19 | const dot = renderToDot( 20 | 21 | 22 | , 23 | ); 24 | expect(dot).toBeValidDotAndMatchSnapshot(); 25 | }); 26 | 27 | test('pass label with HTMLLike ReactElement and render correctly', () => { 28 | const dot = renderToDot( 29 | 30 | 34 | 35 | left 36 | middle 37 | right 38 | 39 | 40 | } 41 | /> 42 | , 43 | ); 44 | expect(dot).toBeValidDotAndMatchSnapshot(); 45 | }); 46 | 47 | test('pass xlabel with string and render correctly', () => { 48 | const dot = renderToDot( 49 | 50 | 51 | , 52 | ); 53 | expect(dot).toBeValidDotAndMatchSnapshot(); 54 | }); 55 | 56 | test('pass xlabel with HTMLLike ReactElement and render correctly', () => { 57 | const dot = renderToDot( 58 | 59 | 63 | 64 | left 65 | middle 66 | right 67 | 68 | 69 | } 70 | /> 71 | , 72 | ); 73 | expect(dot).toBeValidDotAndMatchSnapshot(); 74 | }); 75 | }); 76 | -------------------------------------------------------------------------------- /src/components/__tests__/__snapshots__/Node.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Node pass label with HTMLLike ReactElement and render correctly 1`] = ` 4 | digraph { 5 | "aaa" [ 6 | label = <
leftmiddleright
>, 7 | ]; 8 | } 9 | `; 10 | 11 | exports[`Node pass label with string and render correctly 1`] = ` 12 | digraph { 13 | "aaa" [ 14 | label = "label test", 15 | ]; 16 | } 17 | `; 18 | 19 | exports[`Node pass without optional props and render correctly 1`] = ` 20 | digraph { 21 | "aaa"; 22 | } 23 | `; 24 | 25 | exports[`Node pass xlabel with HTMLLike ReactElement and render correctly 1`] = ` 26 | digraph { 27 | "aaa" [ 28 | xlabel = <
leftmiddleright
>, 29 | ]; 30 | } 31 | `; 32 | 33 | exports[`Node pass xlabel with string and render correctly 1`] = ` 34 | digraph { 35 | "aaa" [ 36 | xlabel = "xlabel test", 37 | ]; 38 | } 39 | `; 40 | -------------------------------------------------------------------------------- /src/components/__tests__/utils/renderExpectToThrow.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable react/destructuring-assignment */ 2 | /* eslint-disable @typescript-eslint/explicit-function-return-type */ 3 | import React, { Component, ReactElement } from 'react'; 4 | import { render } from '../../../render'; 5 | 6 | export function renderExpectToThrow(element: ReactElement, ...expectedError: string[]): void { 7 | const errors: Error[] = []; 8 | class ErrorBoundary extends Component, { hasError: boolean }> { 9 | constructor(props: Record) { 10 | super(props); 11 | this.state = { hasError: false }; 12 | } 13 | 14 | static getDerivedStateFromError() { 15 | return { hasError: true }; 16 | } 17 | 18 | componentDidCatch(error: Error) { 19 | errors.push(error); 20 | } 21 | 22 | render() { 23 | if (this.state.hasError) { 24 | return <>; 25 | } 26 | return this.props.children; 27 | } 28 | } 29 | 30 | try { 31 | render({element}); 32 | } catch (e) { 33 | errors.push(e); 34 | } 35 | expect(errors.length).toBeGreaterThanOrEqual(expectedError.length); 36 | 37 | expect(errors.map((e) => e.message)).toEqual(expect.arrayContaining(expectedError)); 38 | } 39 | -------------------------------------------------------------------------------- /src/contexts/ClusterMap.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | 4 | export const ClusterMap = React.createContext>(new Map()); 5 | ClusterMap.displayName = 'ClusterMap'; 6 | -------------------------------------------------------------------------------- /src/contexts/ContainerCluster.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | 4 | export const ContainerCluster = React.createContext(null); 5 | ContainerCluster.displayName = 'ContainerCluster'; 6 | -------------------------------------------------------------------------------- /src/contexts/CurrentCluster.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | 4 | export const CurrentCluster = React.createContext(null); 5 | CurrentCluster.displayName = 'CurrentCluster'; 6 | -------------------------------------------------------------------------------- /src/contexts/GraphvizContext.ts: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | 4 | export interface IContext { 5 | container?: ICluster; 6 | } 7 | 8 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 9 | export const GraphvizContext = React.createContext(null!); 10 | GraphvizContext.displayName = 'GraphvizContext'; 11 | -------------------------------------------------------------------------------- /src/errors.ts: -------------------------------------------------------------------------------- 1 | export const EdgeTargetLengthErrorMessage = 'Edges must have at least 2 targets.'; 2 | export const NoGraphvizContextErrorMessage = 3 | 'Cannot call useGraphvizContext outside GraphvizContext.\nBasically, you need to use the render function provided by @ts-graphviz/react.'; 4 | export const NoClusterErrorMessage = 'useCluster must be called within a cluster such as Digraph, Graph, Subgraph.'; 5 | export const DuplicatedRootClusterErrorMessage = 'RootCluster is duplicated.\nUse only one of Digraph and Graph.'; 6 | 7 | export const NoContainerErrorMessage = 'There are no clusters of container(Subgraph, Digraph, Graph).'; 8 | -------------------------------------------------------------------------------- /src/hooks/__tests__/__snapshots__/use-rendered-id.spec.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`useRenderedID case 1`] = `"hoge"`; 4 | 5 | exports[`useRenderedID case 2`] = `"<bold>"`; 6 | 7 | exports[`useRenderedID case 3`] = `"<bold>"`; 8 | 9 | exports[`useRenderedID case 4`] = `"<
leftmiddleright
>"`; 10 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-container-cluster.spec.ts: -------------------------------------------------------------------------------- 1 | import { Digraph, Graph } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { digraph, graph, graphInSubgraph, digraphInSubgraph } from './utils/wrapper'; 4 | import { useContainerCluster } from '../use-container-cluster'; 5 | 6 | describe('useContainerCluster', () => { 7 | describe('get root cluster', () => { 8 | test('returns Diagram instance in digraph wrapper', () => { 9 | const { result } = renderHook(() => useContainerCluster(), { 10 | wrapper: digraph(), 11 | }); 12 | expect(result.current).toBeInstanceOf(Digraph); 13 | }); 14 | 15 | test('returns Graph instance in graph wrapper', () => { 16 | const { result } = renderHook(() => useContainerCluster(), { 17 | wrapper: graph(), 18 | }); 19 | expect(result.current).toBeInstanceOf(Graph); 20 | }); 21 | 22 | test('returns Graph instance in graphInSubgraph wrapper', () => { 23 | const { result } = renderHook(() => useContainerCluster(), { 24 | wrapper: graphInSubgraph(), 25 | }); 26 | expect(result.current).toBeInstanceOf(Graph); 27 | }); 28 | 29 | test('returns Digraph instance in digraphInSubgraph wrapper', () => { 30 | const { result } = renderHook(() => useContainerCluster(), { 31 | wrapper: digraphInSubgraph(), 32 | }); 33 | expect(result.current).toBeInstanceOf(Digraph); 34 | }); 35 | }); 36 | }); 37 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-current-cluster.spec.ts: -------------------------------------------------------------------------------- 1 | import { Digraph, Graph, Subgraph } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { useCurrentCluster } from '../use-current-cluster'; 4 | import { digraph, graph, graphInSubgraph, digraphInSubgraph } from './utils/wrapper'; 5 | import { NoClusterErrorMessage } from '../../errors'; 6 | 7 | describe('useCurrentCluster', () => { 8 | describe('get parent cluster', () => { 9 | test('returns Diagram instance in digraph wrapper', () => { 10 | const { result } = renderHook(() => useCurrentCluster(), { 11 | wrapper: digraph(), 12 | }); 13 | expect(result.current).toBeInstanceOf(Digraph); 14 | }); 15 | 16 | test('returns Graph instance in graph wrapper', () => { 17 | const { result } = renderHook(() => useCurrentCluster(), { 18 | wrapper: graph(), 19 | }); 20 | expect(result.current).toBeInstanceOf(Graph); 21 | }); 22 | 23 | test('returns Subgraph instance in graphInSubgraph wrapper', () => { 24 | const { result } = renderHook(() => useCurrentCluster(), { 25 | wrapper: graphInSubgraph(), 26 | }); 27 | expect(result.current).toBeInstanceOf(Subgraph); 28 | }); 29 | 30 | test('returns Subgraph instance in digraphInSubgraph wrapper', () => { 31 | const { result } = renderHook(() => useCurrentCluster(), { 32 | wrapper: digraphInSubgraph(), 33 | }); 34 | expect(result.current).toBeInstanceOf(Subgraph); 35 | }); 36 | }); 37 | 38 | test('An error occurs when called outside the cluster', () => { 39 | const { result } = renderHook(() => useCurrentCluster()); 40 | expect(result.error).toStrictEqual(Error(NoClusterErrorMessage)); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-digraph.spec.ts: -------------------------------------------------------------------------------- 1 | import { Digraph } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { context } from './utils/wrapper'; 4 | import { useDigraph } from '../use-digraph'; 5 | 6 | describe('useDigraph', () => { 7 | it('returns Digraph instance', () => { 8 | const { result } = renderHook(() => useDigraph(), { 9 | wrapper: context(), 10 | }); 11 | expect(result.current).toBeInstanceOf(Digraph); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-edge.spec.ts: -------------------------------------------------------------------------------- 1 | import { Edge, EdgeTargetLikeTuple } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { useEdge } from '../use-edge'; 4 | import { digraph, graph } from './utils/wrapper'; 5 | import { EdgeTargetLengthErrorMessage } from '../../errors'; 6 | 7 | describe('useEdge', () => { 8 | it('returns Edge instance in digraph wrapper', () => { 9 | const { result } = renderHook(() => useEdge(['a', 'b']), { 10 | wrapper: digraph(), 11 | }); 12 | expect(result.current).toBeInstanceOf(Edge); 13 | }); 14 | 15 | it('returns an Edge instance in a digraph wrapper for grouped edge targets', () => { 16 | const { result } = renderHook(() => useEdge(['a', ['b1', 'b2'], 'c']), { 17 | wrapper: digraph(), 18 | }); 19 | expect(result.current).toBeInstanceOf(Edge); 20 | }); 21 | 22 | it('returns Edge instance in graph wrapper', () => { 23 | const { result } = renderHook(() => useEdge(['a', 'b']), { 24 | wrapper: graph(), 25 | }); 26 | expect(result.current).toBeInstanceOf(Edge); 27 | }); 28 | 29 | it('returns an Edge instance in a graph wrapper for grouped edge targets', () => { 30 | const { result } = renderHook(() => useEdge(['a', ['b1', 'b2'], 'c']), { 31 | wrapper: graph(), 32 | }); 33 | expect(result.current).toBeInstanceOf(Edge); 34 | }); 35 | 36 | test('throw error if the target is less than 2', () => { 37 | const { result } = renderHook(() => useEdge(['a'] as any as EdgeTargetLikeTuple), { 38 | wrapper: graph(), 39 | }); 40 | expect(result.error).toStrictEqual(Error(EdgeTargetLengthErrorMessage)); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-graph.spec.ts: -------------------------------------------------------------------------------- 1 | import { Graph } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { context } from './utils/wrapper'; 4 | import { useGraph } from '../use-graph'; 5 | 6 | describe('useGraph', () => { 7 | it('returns Graph instance', () => { 8 | const { result } = renderHook(() => useGraph(), { 9 | wrapper: context(), 10 | }); 11 | expect(result.current).toBeInstanceOf(Graph); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-graphviz-context.spec.ts: -------------------------------------------------------------------------------- 1 | import { renderHook } from '@testing-library/react-hooks'; 2 | import { context } from './utils/wrapper'; 3 | import { useGraphvizContext } from '../use-graphviz-context'; 4 | import { NoGraphvizContextErrorMessage } from '../../errors'; 5 | 6 | describe('useGraphvizContext', () => { 7 | test('returns {}', () => { 8 | const { result } = renderHook(() => useGraphvizContext(), { 9 | wrapper: context(), 10 | }); 11 | expect(result.current).toStrictEqual({}); 12 | }); 13 | 14 | test('An error occurs when called outside the GraphvizContext', () => { 15 | const { result } = renderHook(() => useGraphvizContext()); 16 | expect(result.error).toStrictEqual(Error(NoGraphvizContextErrorMessage)); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-node.spec.ts: -------------------------------------------------------------------------------- 1 | import { Node } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | 4 | import { useNode } from '../use-node'; 5 | import { digraph } from './utils/wrapper'; 6 | 7 | describe('useNode', () => { 8 | it('returns Node instance', () => { 9 | const { result } = renderHook(() => useNode('hoge'), { 10 | wrapper: digraph(), 11 | }); 12 | expect(result.current).toBeInstanceOf(Node); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-rendered-id.spec.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { context } from './utils/wrapper'; 4 | import { useRenderedID } from '../use-rendered-id'; 5 | import { DOT } from '../../labels'; 6 | 7 | describe('useRenderedID', () => { 8 | test.each([ 9 | 'hoge', 10 | '<bold>', 11 | bold, 12 | 13 | 14 | left 15 | middle 16 | right 17 | 18 | , 19 | ])('case', (id) => { 20 | const { result } = renderHook(() => useRenderedID(id), { 21 | wrapper: context(), 22 | }); 23 | expect(result.current).toMatchSnapshot(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/hooks/__tests__/use-subgraph.spec.ts: -------------------------------------------------------------------------------- 1 | import { Subgraph } from 'ts-graphviz'; 2 | import { renderHook } from '@testing-library/react-hooks'; 3 | import { digraph, graph, graphInSubgraph, digraphInSubgraph } from './utils/wrapper'; 4 | import { useSubgraph } from '../use-subgraph'; 5 | 6 | describe('useSubgraph', () => { 7 | it('returns Subgraph instance in digraph warper', () => { 8 | const { result } = renderHook(() => useSubgraph(), { 9 | wrapper: digraph(), 10 | }); 11 | expect(result.current).toBeInstanceOf(Subgraph); 12 | }); 13 | 14 | it('returns Subgraph instance in graph warper', () => { 15 | const { result } = renderHook(() => useSubgraph(), { 16 | wrapper: graph(), 17 | }); 18 | expect(result.current).toBeInstanceOf(Subgraph); 19 | }); 20 | 21 | it('returns Subgraph instance in graphInSubgraph warper', () => { 22 | const { result } = renderHook(() => useSubgraph(), { 23 | wrapper: graphInSubgraph(), 24 | }); 25 | expect(result.current).toBeInstanceOf(Subgraph); 26 | }); 27 | 28 | it('returns Subgraph instance in digraphInSubgraph warper', () => { 29 | const { result } = renderHook(() => useSubgraph(), { 30 | wrapper: digraphInSubgraph(), 31 | }); 32 | expect(result.current).toBeInstanceOf(Subgraph); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /src/hooks/__tests__/utils/wrapper.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable react/jsx-props-no-spreading */ 2 | /* eslint-disable @typescript-eslint/explicit-function-return-type */ 3 | import React, { FC, ComponentProps } from 'react'; 4 | 5 | import { Digraph } from '../../../components/Digraph'; 6 | import { Graph } from '../../../components/Graph'; 7 | import { GraphvizContext } from '../../../contexts/GraphvizContext'; 8 | import { Subgraph } from '../../../components/Subgraph'; 9 | 10 | export const context = 11 | (): FC => 12 | ({ children }) => { 13 | return {children}; 14 | }; 15 | 16 | export const digraph = 17 | (props: ComponentProps = {}): FC => 18 | ({ children }) => { 19 | return ( 20 | 21 | {children} 22 | 23 | ); 24 | }; 25 | 26 | export const digraphInSubgraph = 27 | (props: ComponentProps = {}): FC => 28 | ({ children }) => { 29 | return ( 30 | 31 | 32 | {children} 33 | 34 | 35 | ); 36 | }; 37 | 38 | export const graph = 39 | (props: ComponentProps = {}): FC => 40 | ({ children }) => { 41 | return ( 42 | 43 | {children} 44 | 45 | ); 46 | }; 47 | 48 | export const graphInSubgraph = 49 | (props: ComponentProps = {}): FC => 50 | ({ children }) => { 51 | return ( 52 | 53 | 54 | {children} 55 | 56 | 57 | ); 58 | }; 59 | -------------------------------------------------------------------------------- /src/hooks/use-cluster-attributes.ts: -------------------------------------------------------------------------------- 1 | import { ICluster, AttributesObject } from 'ts-graphviz'; 2 | import { useEffect } from 'react'; 3 | import { ClusterCommonAttributesProps } from '../types'; 4 | 5 | export function useClusterAttributes( 6 | cluster: ICluster, 7 | attributes: AttributesObject, 8 | { edge, node, graph }: ClusterCommonAttributesProps, 9 | ): void { 10 | useEffect(() => { 11 | cluster.clear(); 12 | cluster.apply(attributes); 13 | }, [cluster, attributes]); 14 | useEffect(() => { 15 | cluster.attributes.node.clear(); 16 | cluster.attributes.node.apply(node ?? {}); 17 | }, [cluster, node]); 18 | 19 | useEffect(() => { 20 | cluster.attributes.edge.clear(); 21 | cluster.attributes.edge.apply(edge ?? {}); 22 | }, [cluster, edge]); 23 | 24 | useEffect(() => { 25 | cluster.attributes.graph.clear(); 26 | cluster.attributes.graph.apply(graph ?? {}); 27 | }, [cluster, graph]); 28 | } 29 | -------------------------------------------------------------------------------- /src/hooks/use-cluster-map.ts: -------------------------------------------------------------------------------- 1 | import { useContext } from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | import { ClusterMap } from '../contexts/ClusterMap'; 4 | 5 | export function useClusterMap(): Map { 6 | return useContext(ClusterMap); 7 | } 8 | -------------------------------------------------------------------------------- /src/hooks/use-comment.ts: -------------------------------------------------------------------------------- 1 | import { IHasComment } from 'ts-graphviz'; 2 | import { useEffect } from 'react'; 3 | 4 | export function useHasComment(target: IHasComment, comment?: string): void { 5 | useEffect(() => { 6 | // eslint-disable-next-line no-param-reassign 7 | target.comment = comment; 8 | }, [target, comment]); 9 | } 10 | -------------------------------------------------------------------------------- /src/hooks/use-container-cluster.ts: -------------------------------------------------------------------------------- 1 | import { useContext } from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | import { ContainerCluster } from '../contexts/ContainerCluster'; 4 | 5 | /** 6 | * Return the cluster of container. 7 | */ 8 | export function useContainerCluster(): ICluster | null { 9 | return useContext(ContainerCluster); 10 | } 11 | -------------------------------------------------------------------------------- /src/hooks/use-current-cluster.ts: -------------------------------------------------------------------------------- 1 | import { useContext } from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | import { CurrentCluster } from '../contexts/CurrentCluster'; 4 | import { NoClusterErrorMessage } from '../errors'; 5 | 6 | /** 7 | * Hook to get the current cluster(Digraph, Graph or Subgraph). 8 | * 9 | * @throws If it is out of the context of Cluster, it throws an exception. 10 | */ 11 | export function useCurrentCluster(): ICluster { 12 | const cluster = useContext(CurrentCluster); 13 | if (cluster === null) { 14 | throw Error(NoClusterErrorMessage); 15 | } 16 | return cluster; 17 | } 18 | -------------------------------------------------------------------------------- /src/hooks/use-digraph.ts: -------------------------------------------------------------------------------- 1 | import { useMemo, useEffect } from 'react'; 2 | import { Digraph, IRootCluster } from 'ts-graphviz'; 3 | import { useGraphvizContext } from './use-graphviz-context'; 4 | import { useClusterAttributes } from './use-cluster-attributes'; 5 | import { useHasComment } from './use-comment'; 6 | import { RootClusterOptions } from '../types'; 7 | 8 | /** 9 | * `useDigraph` is a hook that creates an instance of Digraph 10 | * according to the object given by props. 11 | */ 12 | export function useDigraph(options: RootClusterOptions = {}): IRootCluster { 13 | const { id, comment, edge, node, graph, ...attributes } = options; 14 | const context = useGraphvizContext(); 15 | const digraph = useMemo(() => { 16 | const g = new Digraph(id); 17 | context.container = g; 18 | g.comment = comment; 19 | g.apply(attributes); 20 | g.attributes.node.apply(node ?? {}); 21 | g.attributes.edge.apply(edge ?? {}); 22 | g.attributes.graph.apply(graph ?? {}); 23 | return g; 24 | }, [context, id, comment, edge, node, graph, attributes]); 25 | useHasComment(digraph, comment); 26 | useClusterAttributes(digraph, attributes, { edge, node, graph }); 27 | useEffect(() => { 28 | return (): void => { 29 | context.container = undefined; 30 | }; 31 | }, [context]); 32 | return digraph; 33 | } 34 | -------------------------------------------------------------------------------- /src/hooks/use-edge.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useMemo } from 'react'; 2 | import { EdgeTargetLikeTuple, IEdge } from 'ts-graphviz'; 3 | import { useCurrentCluster } from './use-current-cluster'; 4 | import { EdgeTargetLengthErrorMessage } from '../errors'; 5 | import { useHasComment } from './use-comment'; 6 | import { useHasAttributes } from './use-has-attributes'; 7 | import { EdgeOptions } from '../types'; 8 | 9 | /** 10 | * `useEdge` is a hook that creates an instance of Edge 11 | * according to the object given by props. 12 | */ 13 | export function useEdge(targets: EdgeTargetLikeTuple, props: EdgeOptions = {}): IEdge { 14 | const { comment, ...attributes } = props; 15 | const cluster = useCurrentCluster(); 16 | if (targets.length < 2) { 17 | throw Error(EdgeTargetLengthErrorMessage); 18 | } 19 | const edge = useMemo(() => { 20 | const e = cluster.createEdge(targets); 21 | e.comment = comment; 22 | e.attributes.apply(attributes); 23 | return e; 24 | }, [cluster, targets, comment, attributes]); 25 | useHasComment(edge, comment); 26 | useHasAttributes(edge, attributes); 27 | useEffect(() => { 28 | return (): void => { 29 | cluster.removeEdge(edge); 30 | }; 31 | }, [cluster, edge]); 32 | return edge; 33 | } 34 | -------------------------------------------------------------------------------- /src/hooks/use-graph.ts: -------------------------------------------------------------------------------- 1 | import { useMemo, useEffect } from 'react'; 2 | import { Graph, IRootCluster } from 'ts-graphviz'; 3 | import { useGraphvizContext } from './use-graphviz-context'; 4 | import { useClusterAttributes } from './use-cluster-attributes'; 5 | import { useHasComment } from './use-comment'; 6 | import { RootClusterOptions } from '../types'; 7 | 8 | /** 9 | * `useGraph` is a hook that creates an instance of Graph 10 | * according to the object given by props. 11 | */ 12 | export function useGraph(options: RootClusterOptions = {}): IRootCluster { 13 | const { id, comment, edge, node, graph, ...attributes } = options; 14 | const context = useGraphvizContext(); 15 | const memoGraph = useMemo(() => { 16 | const g = new Graph(id); 17 | context.container = g; 18 | g.comment = comment; 19 | g.apply(attributes); 20 | g.attributes.node.apply(node ?? {}); 21 | g.attributes.edge.apply(edge ?? {}); 22 | g.attributes.graph.apply(graph ?? {}); 23 | return g; 24 | }, [context, id, comment, edge, node, graph, attributes]); 25 | useHasComment(memoGraph, comment); 26 | useClusterAttributes(memoGraph, attributes, { edge, node, graph }); 27 | useEffect(() => { 28 | return (): void => { 29 | context.container = undefined; 30 | }; 31 | }, [context]); 32 | return memoGraph; 33 | } 34 | -------------------------------------------------------------------------------- /src/hooks/use-graphviz-context.ts: -------------------------------------------------------------------------------- 1 | import { useContext } from 'react'; 2 | import { ICluster } from 'ts-graphviz'; 3 | import { GraphvizContext } from '../contexts/GraphvizContext'; 4 | import { NoGraphvizContextErrorMessage } from '../errors'; 5 | 6 | export interface IContext { 7 | container?: ICluster; 8 | } 9 | 10 | export function useGraphvizContext(): IContext { 11 | const context = useContext(GraphvizContext); 12 | if (context === null) { 13 | throw Error(NoGraphvizContextErrorMessage); 14 | } 15 | return context; 16 | } 17 | -------------------------------------------------------------------------------- /src/hooks/use-has-attributes.ts: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { IHasAttributes, AttributesObject } from 'ts-graphviz'; 3 | 4 | export function useHasAttributes(target: IHasAttributes, attributes: AttributesObject): void { 5 | useEffect(() => { 6 | target.attributes.clear(); 7 | target.attributes.apply(attributes); 8 | }, [target, attributes]); 9 | } 10 | -------------------------------------------------------------------------------- /src/hooks/use-node.ts: -------------------------------------------------------------------------------- 1 | import { useEffect, useMemo } from 'react'; 2 | import { INode } from 'ts-graphviz'; 3 | import { NodeOptions } from '../types'; 4 | import { useCurrentCluster } from './use-current-cluster'; 5 | import { useHasComment } from './use-comment'; 6 | import { useHasAttributes } from './use-has-attributes'; 7 | 8 | /** 9 | * `useNode` is a hook that creates an instance of Node 10 | * according to the object given by props. 11 | */ 12 | export function useNode(id: string, options: NodeOptions = {}): INode { 13 | const { comment, ...attributes } = options; 14 | const cluster = useCurrentCluster(); 15 | const node = useMemo(() => { 16 | const n = cluster.createNode(id); 17 | n.attributes.apply(attributes); 18 | n.comment = comment; 19 | return n; 20 | }, [cluster, id, attributes, comment]); 21 | useHasComment(node, comment); 22 | useHasAttributes(node, attributes); 23 | useEffect(() => { 24 | return (): void => { 25 | cluster.removeNode(node); 26 | }; 27 | }, [cluster, node]); 28 | return node; 29 | } 30 | -------------------------------------------------------------------------------- /src/hooks/use-rendered-id.ts: -------------------------------------------------------------------------------- 1 | import { ReactElement, useMemo } from 'react'; 2 | import { renderId } from '../render-id'; 3 | 4 | export function useRenderedID(id?: ReactElement | string): string | undefined { 5 | return useMemo(() => renderId(id), [id]); 6 | } 7 | -------------------------------------------------------------------------------- /src/hooks/use-subgraph.ts: -------------------------------------------------------------------------------- 1 | import { useMemo, useEffect } from 'react'; 2 | import { Subgraph, ISubgraph } from 'ts-graphviz'; 3 | import { SubgraphOptions } from '../types'; 4 | import { useCurrentCluster } from './use-current-cluster'; 5 | import { useClusterAttributes } from './use-cluster-attributes'; 6 | import { useHasComment } from './use-comment'; 7 | import { useGraphvizContext } from './use-graphviz-context'; 8 | 9 | /** 10 | * `useSubgraph` is a hook that creates an instance of Subgraph 11 | * according to the object given by props. 12 | */ 13 | export function useSubgraph(props: SubgraphOptions = {}): ISubgraph { 14 | const { id, comment, edge, node, graph, ...attributes } = props; 15 | const context = useGraphvizContext(); 16 | const cluster = useCurrentCluster(); 17 | const subgraph = useMemo(() => { 18 | const g = new Subgraph(id); 19 | if (cluster !== null) { 20 | cluster.addSubgraph(g); 21 | } else if (!context.container) { 22 | context.container = g; 23 | } 24 | g.comment = comment; 25 | g.apply(attributes); 26 | g.attributes.node.apply(node ?? {}); 27 | g.attributes.edge.apply(edge ?? {}); 28 | g.attributes.graph.apply(graph ?? {}); 29 | return g; 30 | }, [context, cluster, id, comment, edge, node, graph, attributes]); 31 | useHasComment(subgraph, comment); 32 | useClusterAttributes(subgraph, attributes, { edge, node, graph }); 33 | useEffect(() => { 34 | return (): void => { 35 | cluster.removeSubgraph(subgraph); 36 | }; 37 | }, [cluster, subgraph]); 38 | return subgraph; 39 | } 40 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './types'; 2 | export * from './labels'; 3 | export * from './hooks/use-container-cluster'; 4 | export * from './hooks/use-current-cluster'; 5 | export * from './hooks/use-digraph'; 6 | export * from './hooks/use-graph'; 7 | export * from './hooks/use-subgraph'; 8 | export * from './hooks/use-edge'; 9 | export * from './hooks/use-node'; 10 | export * from './components/Graph'; 11 | export * from './components/Digraph'; 12 | export * from './components/Subgraph'; 13 | export * from './components/Node'; 14 | export * from './components/Edge'; 15 | export * from './components/ClusterPortal'; 16 | export * from './render'; 17 | -------------------------------------------------------------------------------- /src/labels.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | import { AttributesValue } from 'ts-graphviz'; 3 | 4 | type ValueOf = T[keyof T]; 5 | 6 | // eslint-disable-next-line @typescript-eslint/no-namespace 7 | export namespace labels { 8 | export type TableProps = { 9 | ALIGN?: 'CENTER' | 'LEFT' | 'RIGHT'; // "CENTER|LEFT|RIGHT" 10 | BGCOLOR?: AttributesValue; // "color" 11 | BORDER?: AttributesValue; // "value" 12 | CELLBORDER?: AttributesValue; // "value" 13 | CELLPADDING?: AttributesValue; // "value" 14 | CELLSPACING?: AttributesValue; // "value" 15 | COLOR?: AttributesValue; // "color" 16 | COLUMNS?: AttributesValue; // "value" 17 | FIXEDSIZE?: true; // "FALSE|TRUE" 18 | GRADIENTANGLE?: AttributesValue; // "value" 19 | HEIGHT?: AttributesValue; // "value" 20 | HREF?: AttributesValue; // "value" 21 | ID?: AttributesValue; // "value" 22 | PORT?: AttributesValue; // "portName" 23 | ROWS?: AttributesValue; // "value" 24 | SIDES?: AttributesValue; // "value" 25 | STYLE?: AttributesValue; // "value" 26 | TARGET?: AttributesValue; // "value" 27 | TITLE?: AttributesValue; // "value" 28 | TOOLTIP?: AttributesValue; // "value" 29 | VALIGN?: 'MIDDLE' | 'BOTTOM' | 'TOP'; // "MIDDLE|BOTTOM|TOP" 30 | WIDTH?: AttributesValue; // "value" 31 | }; 32 | 33 | type NoAttributes = Record; 34 | 35 | export type TrProps = NoAttributes; 36 | 37 | export type TdProps = { 38 | ALIGN?: 'CENTER' | 'LEFT' | 'RIGHT' | 'TEXT'; // "CENTER|LEFT|RIGHT|TEXT" 39 | BALIGN?: 'CENTER' | 'LEFT' | 'RIGHT'; // "CENTER|LEFT|RIGHT" 40 | BGCOLOR?: AttributesValue; // "color" 41 | BORDER?: AttributesValue; // "value" 42 | CELLPADDING?: AttributesValue; // "value" 43 | CELLSPACING?: AttributesValue; // "value" 44 | COLOR?: AttributesValue; // "color" 45 | COLSPAN?: AttributesValue; // "value" 46 | FIXEDSIZE?: boolean; // "FALSE|TRUE" 47 | GRADIENTANGLE?: AttributesValue; // "value" 48 | HEIGHT?: AttributesValue; // "value" 49 | HREF?: AttributesValue; // "value" 50 | ID?: AttributesValue; // "value" 51 | PORT?: AttributesValue; // "portName" 52 | ROWSPAN?: AttributesValue; // "value" 53 | SIDES?: AttributesValue; // "value" 54 | STYLE?: AttributesValue; // "value" 55 | TARGET?: AttributesValue; // "value" 56 | TITLE?: AttributesValue; // "value" 57 | TOOLTIP?: AttributesValue; // "value" 58 | VALIGN?: 'MIDDLE' | 'BOTTOM' | 'TOP'; // "MIDDLE|BOTTOM|TOP" 59 | WIDTH?: AttributesValue; // "value" 60 | }; 61 | 62 | export type FontProps = { 63 | COLOR?: AttributesValue; // "color" 64 | FACE?: AttributesValue; // "fontname" 65 | 'POINT-SIZE'?: AttributesValue; // "value" 66 | }; 67 | 68 | export type BrProps = { 69 | ALIGN?: 'CENTER' | 'LEFT' | 'RIGHT'; // "CENTER|LEFT|RIGHT" 70 | }; 71 | 72 | export type ImgProps = { 73 | SCALE?: boolean | 'WIDTH' | 'HEIGHT' | 'BOTH'; // "FALSE|TRUE|WIDTH|HEIGHT|BOTH" 74 | SRC?: AttributesValue; // "value" 75 | }; 76 | 77 | export type IProps = NoAttributes; 78 | 79 | export type BProps = NoAttributes; 80 | 81 | export type UProps = NoAttributes; 82 | 83 | export type OProps = NoAttributes; 84 | export type SubProps = NoAttributes; 85 | 86 | export type SupProps = NoAttributes; 87 | export type SProps = NoAttributes; 88 | export type HrProps = NoAttributes; 89 | export type VrProps = NoAttributes; 90 | } 91 | 92 | export const DOT = Object.freeze({ 93 | PORT: 'dot-port', 94 | TABLE: 'dot-table', 95 | TR: 'dot-tr', 96 | TD: 'dot-td', 97 | FONT: 'dot-font', 98 | BR: 'dot-br', 99 | IMG: 'dot-img', 100 | I: 'dot-i', 101 | B: 'dot-b', 102 | U: 'dot-u', 103 | O: 'dot-o', 104 | SUB: 'dot-sub', 105 | SUP: 'dot-sup', 106 | S: 'dot-s', 107 | HR: 'dot-hr', 108 | VR: 'dot-vr', 109 | } as const); 110 | 111 | export type DOT = ValueOf; 112 | 113 | declare global { 114 | // eslint-disable-next-line @typescript-eslint/no-namespace 115 | namespace JSX { 116 | interface IntrinsicElements { 117 | [DOT.PORT]: { children: string }; 118 | [DOT.TABLE]: React.PropsWithChildren; 119 | [DOT.TR]: React.PropsWithChildren; 120 | [DOT.TD]: React.PropsWithChildren; 121 | [DOT.FONT]: React.PropsWithChildren; 122 | [DOT.BR]: labels.BrProps; 123 | [DOT.IMG]: labels.ImgProps; 124 | [DOT.I]: React.PropsWithChildren; 125 | [DOT.B]: React.PropsWithChildren; 126 | [DOT.U]: React.PropsWithChildren; 127 | [DOT.O]: React.PropsWithChildren; 128 | [DOT.SUB]: React.PropsWithChildren; 129 | [DOT.SUP]: React.PropsWithChildren; 130 | [DOT.S]: React.PropsWithChildren; 131 | [DOT.HR]: labels.HrProps; 132 | [DOT.VR]: labels.VrProps; 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/reconciler.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ 2 | /* eslint-disable class-methods-use-this */ 3 | /* eslint-disable @typescript-eslint/no-unused-vars */ 4 | /* eslint-disable class-methods-use-this */ 5 | import { FC } from 'react'; 6 | import ReactReconciler from 'react-reconciler'; 7 | 8 | type Type = FC; 9 | type Props = any; 10 | type Container = Record; 11 | 12 | type Instance = any; 13 | type TextInstance = any; 14 | type SuspenseInstance = any; 15 | type HydratableInstance = any; 16 | type PublicInstance = any; 17 | type HostContext = any; 18 | type UpdatePayload = any; 19 | type ChildSet = any; 20 | type TimeoutHandle = any; 21 | type NoTimeout = any; 22 | 23 | type OpaqueHandle = ReactReconciler.Fiber; 24 | 25 | export class HostConfig 26 | implements 27 | ReactReconciler.HostConfig< 28 | Type, 29 | Props, 30 | Container, 31 | Instance, 32 | TextInstance, 33 | SuspenseInstance, 34 | HydratableInstance, 35 | PublicInstance, 36 | HostContext, 37 | UpdatePayload, 38 | ChildSet, // TODO Placeholder for undocumented API 39 | TimeoutHandle, 40 | NoTimeout 41 | > 42 | { 43 | preparePortalMount(containerInfo: Container): void { 44 | // NoOp 45 | } 46 | 47 | scheduleTimeout(fn: (...args: unknown[]) => unknown, delay?: number) { 48 | // NoOp 49 | } 50 | 51 | cancelTimeout(id: any): void { 52 | // NoOp 53 | } 54 | 55 | queueMicrotask(fn: () => void): void { 56 | // NoOp 57 | } 58 | 59 | cloneInstance?: any; 60 | 61 | cloneFundamentalInstance?: any; 62 | 63 | createContainerChildSet?: any; 64 | 65 | appendChildToContainerChildSet?: any; 66 | 67 | finalizeContainerChildren?: any; 68 | 69 | replaceContainerChildren?: any; 70 | 71 | cloneHiddenInstance?: any; 72 | 73 | cloneHiddenTextInstance?: any; 74 | 75 | public now = Date.now; 76 | 77 | public setTimeout = setTimeout; 78 | 79 | public clearTimeout = clearTimeout; 80 | 81 | public noTimeout: NoTimeout = -1; // TODO 82 | 83 | // Temporary workaround for scenario where multiple renderers concurrently 84 | // render using the same context objects. E.g. React DOM and React ART on the 85 | // same page. DOM is the primary renderer; ART is the secondary renderer. 86 | public isPrimaryRenderer = false; 87 | 88 | public supportsMutation = false; 89 | 90 | public supportsPersistence = false; 91 | 92 | public supportsHydration = false; 93 | 94 | public getPublicInstance(instance: Instance | TextInstance): PublicInstance { 95 | return instance; 96 | } 97 | 98 | public getRootHostContext(rootContainerInstance: Container): HostContext { 99 | return {}; 100 | } 101 | 102 | public getChildHostContext( 103 | parentHostContext: HostContext, 104 | type: Type, 105 | rootContainerInstance: Container, 106 | ): HostContext { 107 | return parentHostContext; 108 | } 109 | 110 | public prepareForCommit(containerInfo: Container): Record | null { 111 | return null; 112 | } 113 | 114 | public resetAfterCommit(containerInfo: Container): void { 115 | // containerInfo.setRoot 116 | } 117 | 118 | /** 119 | * Create component instance 120 | */ 121 | public createInstance( 122 | type: Type, 123 | props: Props, 124 | rootContainerInstance: Container, 125 | hostContext: HostContext, 126 | internalInstanceHandle: OpaqueHandle, 127 | ): Instance { 128 | // NoOp 129 | return type(props); 130 | } 131 | 132 | public appendInitialChild(parentInstance: Instance, child: Instance | TextInstance): void { 133 | parentInstance.appendChild(child); 134 | } 135 | 136 | public finalizeInitialChildren( 137 | parentInstance: Instance, 138 | type: Type, 139 | props: Props, 140 | rootContainerInstance: Container, 141 | hostContext: HostContext, 142 | ): boolean { 143 | return false; 144 | } 145 | 146 | public prepareUpdate( 147 | instance: Instance, 148 | type: Type, 149 | oldProps: Props, 150 | newProps: Props, 151 | rootContainerInstance: Container, 152 | hostContext: HostContext, 153 | ): null | UpdatePayload { 154 | return {}; 155 | } 156 | 157 | public shouldSetTextContent(type: Type, props: Props): boolean { 158 | return false; 159 | } 160 | 161 | public shouldDeprioritizeSubtree(type: Type, props: Props): boolean { 162 | return false; 163 | } 164 | 165 | public createTextInstance( 166 | text: string, 167 | rootContainerInstance: Container, 168 | hostContext: HostContext, 169 | internalInstanceHandle: OpaqueHandle, 170 | ): TextInstance { 171 | return text; 172 | } 173 | 174 | public scheduleDeferredCallback(callback: () => any, options?: { timeout: number }): any { 175 | // NoOp 176 | } 177 | 178 | public cancelDeferredCallback(callbackID: any): void { 179 | // NoOp 180 | } 181 | 182 | // ------------------- 183 | // Mutation 184 | // (optional) 185 | // ------------------- 186 | public appendChild(parentInstance: Instance, child: Instance | TextInstance): void { 187 | // NoOp 188 | if (parentInstance.appendChild) { 189 | parentInstance.appendChild(child); 190 | } 191 | } 192 | 193 | public appendChildToContainer(container: Container, child: Instance | TextInstance): void { 194 | // if (container.appendChild) { 195 | // container.appendChild(child); 196 | // } 197 | } 198 | 199 | public commitTextUpdate(textInstance: TextInstance, oldText: string, newText: string): void { 200 | // NoOp 201 | } 202 | 203 | public commitMount(instance: Instance, type: Type, newProps: Props, internalInstanceHandle: OpaqueHandle): void { 204 | // NoOp 205 | } 206 | 207 | public commitUpdate( 208 | instance: Instance, 209 | updatePayload: UpdatePayload, 210 | type: Type, 211 | oldProps: Props, 212 | newProps: Props, 213 | internalInstanceHandle: OpaqueHandle, 214 | ): void { 215 | // NoOp 216 | } 217 | 218 | public insertBefore( 219 | parentInstance: Instance, 220 | child: Instance | TextInstance, 221 | beforeChild: Instance | TextInstance, 222 | ): void { 223 | // NoOp 224 | } 225 | 226 | public insertInContainerBefore( 227 | container: Container, 228 | child: Instance | TextInstance, 229 | beforeChild: Instance | TextInstance, 230 | ): void { 231 | // NoOp 232 | } 233 | 234 | public removeChild(parentInstance: Instance, child: Instance | TextInstance): void { 235 | // NoOp 236 | } 237 | 238 | public removeChildFromContainer(container: Container, child: Instance | TextInstance): void { 239 | // NoOp 240 | } 241 | 242 | public resetTextContent(instance: Instance): void { 243 | // NoOp 244 | } 245 | } 246 | 247 | export const reconciler = ReactReconciler(new HostConfig()); 248 | -------------------------------------------------------------------------------- /src/render-id.ts: -------------------------------------------------------------------------------- 1 | import { ReactElement, isValidElement } from 'react'; 2 | import { renderToStaticMarkup } from 'react-dom/server.js'; 3 | 4 | export function renderId(id?: ReactElement | string): string | undefined { 5 | if (isValidElement(id)) { 6 | const htmlLike = renderToStaticMarkup(id) 7 | .replace(/(.+?)<\/dot-port>/gi, '<$1>') 8 | .replace(/<(\/?)dot-([a-z-]+)/gi, (_, $1, $2) => `<${$1}${$2.toUpperCase()}`); 9 | return `<${htmlLike}>`; 10 | } 11 | return id; 12 | } 13 | -------------------------------------------------------------------------------- /src/render.ts: -------------------------------------------------------------------------------- 1 | import { ReactElement, createElement } from 'react'; 2 | import { toDot, ICluster } from 'ts-graphviz'; 3 | 4 | import { reconciler } from './reconciler'; 5 | import { IContext, GraphvizContext } from './contexts/GraphvizContext'; 6 | import { ClusterMap } from './contexts/ClusterMap'; 7 | import { ContainerCluster } from './contexts/ContainerCluster'; 8 | import { CurrentCluster } from './contexts/CurrentCluster'; 9 | import { NoContainerErrorMessage } from './errors'; 10 | 11 | const noop = (): void => undefined; 12 | 13 | function clusterMap(cluster?: ICluster, map: Map = new Map()): Map { 14 | if (cluster) { 15 | if (cluster.id) { 16 | map.set(cluster.id, cluster); 17 | } 18 | cluster.subgraphs.forEach((s) => clusterMap(s, map)); 19 | } 20 | return map; 21 | } 22 | 23 | /** 24 | * Convert the given element to Graphviz model. 25 | * 26 | * @example Example of giving a cluster as a container with the second argument. 27 | * 28 | * ```tsx 29 | * import React, { FC } from 'react'; 30 | * import { digraph, toDot } from 'ts-graphviz'; 31 | * import { Node, Subgraph, render, Edge } from '@ts-graphviz/react'; 32 | * 33 | * const Example: FC = () => ( 34 | * <> 35 | * 36 | * 37 | * 38 | * 39 | * 40 | * 41 | * 42 | * ); 43 | * 44 | * const G = digraph((g) => render(, g)); 45 | * console.log(toDot(G)); 46 | * // digraph { 47 | * // "a"; 48 | * // subgraph "my_cluster" { 49 | * // "b"; 50 | * // } 51 | * // "b" -> "a"; 52 | * // } 53 | * ``` 54 | */ 55 | export function render(element: ReactElement, container?: ICluster): ICluster { 56 | const context: IContext = { container }; 57 | reconciler.updateContainer( 58 | createElement( 59 | GraphvizContext.Provider, 60 | { value: context }, 61 | createElement( 62 | ClusterMap.Provider, 63 | { value: clusterMap(container) }, 64 | createElement( 65 | ContainerCluster.Provider, 66 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion 67 | { value: container ?? null! }, 68 | container ? createElement(CurrentCluster.Provider, { value: container }, element) : element, 69 | ), 70 | ), 71 | ), 72 | reconciler.createContainer({}, 0, false, null), 73 | null, 74 | noop, 75 | ); 76 | if (!context.container) { 77 | throw Error(NoContainerErrorMessage); 78 | } 79 | return context.container; 80 | } 81 | 82 | /** 83 | * Converts the given element to DOT language and returns it. 84 | * 85 | * @example 86 | * 87 | * ```tsx 88 | * import React, { FC } from 'react'; 89 | * import { Digraph, Node, Subgraph, renderToDot, Edge } from '@ts-graphviz/react'; 90 | * 91 | * const Example: FC = () => ( 92 | * 93 | * 94 | * 95 | * 96 | * 97 | * 98 | * 99 | * ); 100 | * 101 | * const dot = renderToDot(); 102 | * console.log(dot); 103 | * // digraph { 104 | * // "a"; 105 | * // subgraph "my_cluster" { 106 | * // "b"; 107 | * // } 108 | * // "b" -> "a"; 109 | * // } 110 | * ``` 111 | * 112 | * @returns Rendered dot string 113 | */ 114 | export function renderToDot(element: ReactElement, container?: ICluster): string { 115 | return toDot(render(element, container)); 116 | } 117 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { ReactElement } from 'react'; 2 | import { 3 | EdgeAttributes, 4 | NodeAttributes, 5 | ClusterSubgraphAttributes, 6 | RootClusterAttributes, 7 | IHasComment, 8 | attribute, 9 | EdgeTargetLikeTuple, 10 | } from 'ts-graphviz'; 11 | 12 | /** Common attribute values of objects under cluster */ 13 | export interface ClusterCommonAttributesProps { 14 | /** Attribute value for Edges */ 15 | edge?: EdgeAttributes; 16 | /** Attribute value for Nodes */ 17 | node?: NodeAttributes; 18 | /** Attribute value for Graphs */ 19 | graph?: ClusterSubgraphAttributes; 20 | } 21 | 22 | /** Options for RootCluster */ 23 | export interface RootClusterOptions 24 | extends Omit, 25 | ClusterCommonAttributesProps, 26 | IHasComment { 27 | /** Cluster id */ 28 | id?: string; 29 | } 30 | 31 | /** Options for Subgraph */ 32 | export interface SubgraphOptions 33 | extends Omit, 34 | ClusterCommonAttributesProps, 35 | IHasComment { 36 | /** Cluster id */ 37 | id?: string; 38 | } 39 | 40 | /** Options for Edge */ 41 | export interface EdgeOptions extends Omit, IHasComment {} 42 | 43 | /** Options for Node */ 44 | export interface NodeOptions extends Omit, IHasComment {} 45 | 46 | /** Props for RootCluster component */ 47 | export interface RootClusterProps extends Omit { 48 | label?: ReactElement | string; 49 | } 50 | 51 | /** Props for Edge component */ 52 | export interface EdgeProps extends Omit { 53 | /** Edge targets */ 54 | targets: EdgeTargetLikeTuple; 55 | /** Edge label */ 56 | label?: ReactElement | string; 57 | } 58 | 59 | /** Props for Node component */ 60 | export interface NodeProps extends Omit { 61 | /** Node id */ 62 | id: string; 63 | /** Node label */ 64 | label?: ReactElement | string; 65 | /** Node xlabel */ 66 | xlabel?: ReactElement | string; 67 | } 68 | 69 | /** Props for Subgraph component */ 70 | export interface SubgraphProps extends Omit { 71 | /** Subgraph label */ 72 | label?: ReactElement | string; 73 | } 74 | 75 | /** Props for ClusterPortal component */ 76 | export interface ClusterPortalProps { 77 | /** 78 | * id of the cluster you want to target for the portal. 79 | * If not specified, target the cluster that is the container to the portal. 80 | */ 81 | id?: string; 82 | } 83 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES5", 4 | "jsx": "react", 5 | "strict": true, 6 | "rootDir": "src", 7 | "moduleResolution": "node", 8 | "lib": [ 9 | "dom", 10 | "esnext" 11 | ], 12 | "allowJs": false, 13 | "alwaysStrict": true, 14 | "strictNullChecks": true, 15 | "esModuleInterop": true, 16 | "forceConsistentCasingInFileNames": true, 17 | "declaration": true, 18 | "experimentalDecorators": true 19 | }, 20 | "include": [ 21 | "src/**/*.ts", 22 | "src/**/*.tsx" 23 | ], 24 | "exclude": [ 25 | "src/**/*.stories.tsx", 26 | "src/**/*.spec.ts", 27 | "src/**/*.spec.tsx", 28 | "src/**/*.test.ts", 29 | "src/**/*.test.tsx", 30 | "src/**/__tests__/**/*.ts" 31 | ] 32 | } 33 | --------------------------------------------------------------------------------