@asd14/vblocks 5.3.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ #!/bin/sh
2
+
3
+ # vblocks.sh - What every command of vblocks shares:
4
+ # - lib.sh, the folders, the styles of the output and the header
5
+
6
+ # The caller sets _SCRIPT_DIR to the folder of vblocks.sh, then sources it
7
+ : "${_SCRIPT_DIR:?the caller sets _SCRIPT_DIR before it sources vblocks.sh}"
8
+
9
+ _VB_DIR=$(dirname "$(dirname "$_SCRIPT_DIR")")
10
+
11
+ # tools/update-lib downloads lib.sh from @asd14/posix-utils. Never edit lib.sh
12
+ # here
13
+ # shellcheck source=lib.sh
14
+ . "$_SCRIPT_DIR/lib.sh"
15
+
16
+ # _log reads LOG_NAMESPACE, LOG_LEVEL and NO_LOG_TIME. VBlocks logs only errors,
17
+ # through _fail. The time adds no fact to an error
18
+ LOG_NAMESPACE="vblocks"
19
+ LOG_LEVEL="info"
20
+ NO_LOG_TIME="true"
21
+
22
+ # `cd` follows an exported CDPATH and prints the folder it picked, which
23
+ # `$(cd ... && pwd)` would capture
24
+ unset CDPATH
25
+
26
+ # ╭───
27
+ # │ Primitives
28
+ # ╰───
29
+
30
+ # _shorten_home <path>
31
+ #
32
+ # Print <path> with the home folder as "~".
33
+ _shorten_home() {
34
+ if [ -n "${HOME:-}" ]; then
35
+ case "$1" in
36
+ "$HOME"/*)
37
+ # shellcheck disable=SC2088 # a literal "~", for display
38
+ printf '~/%s\n' "${1#"$HOME"/}"
39
+ return 0
40
+ ;;
41
+ esac
42
+ fi
43
+
44
+ printf '%s\n' "$1"
45
+ }
46
+
47
+ # ╭───
48
+ # │ Domain primitives
49
+ # ╰───
50
+
51
+ # _export_version
52
+ #
53
+ # Read the version of VBlocks from its package.json, and export it as
54
+ # VB_VERSION: the commands pass it to the header, and the post-init hooks read
55
+ # it. Guard node before the call.
56
+ _export_version() {
57
+ VB_VERSION=$(node -p 'require(process.argv[1]).version' "$_VB_DIR/package.json")
58
+ export VB_VERSION
59
+ }
60
+
61
+ # _print_header <version> <title>
62
+ #
63
+ # Print the name of VBlocks and <version> in the top border, then <title>, then
64
+ # close the box. The lines after it hold the details. Print nothing unless
65
+ # _IS_TERMINAL is set. The header holds no fact a reader acts on.
66
+ _print_header() {
67
+ [ -n "$_IS_TERMINAL" ] || return 0
68
+
69
+ printf '╭───────────┤ %s\n' "${_GREEN} VBlocks v$1${_RESET}"
70
+ printf '│ %s\n' "$2"
71
+ printf '╰──┤\n'
72
+ }
73
+
74
+ # ╭───
75
+ # │ Bootstrap
76
+ # ╰───
77
+
78
+ # Style the summary and the file lists, and show the header, only when stdout
79
+ # and stderr are both terminals that show color. A pipe on either one, eg.
80
+ # `| tee` or an agent that reads the output, means plain text with only the
81
+ # facts
82
+ _IS_TERMINAL=""
83
+ _BOLD="" _GREEN="" _YELLOW="" _RED="" _GRAY="" _RESET=""
84
+ if _has_color 1 && _has_color 2; then
85
+ _IS_TERMINAL="true"
86
+ _BOLD=$(printf '\033[1m')
87
+ _GREEN=$(printf '\033[32m')
88
+ _YELLOW=$(printf '\033[33m')
89
+ _RED=$(printf '\033[31m')
90
+ _GRAY=$(printf '\033[90m')
91
+ _RESET=$(printf '\033[0m')
92
+ fi
@@ -0,0 +1,130 @@
1
+ #!/bin/sh
2
+
3
+ # webpack.sh - The primitives of serve and build: the --log-level guard, the
4
+ # configs, the summary and the Webpack run
5
+
6
+ # ╭───
7
+ # │ Primitives
8
+ # ╰───
9
+
10
+ # _pick_file <file> <default-file>
11
+ #
12
+ # Print <file> when it exists, otherwise <default-file>.
13
+ _pick_file() {
14
+ if [ -f "$1" ]; then
15
+ printf '%s\n' "$1"
16
+ else
17
+ printf '%s\n' "$2"
18
+ fi
19
+ }
20
+
21
+ # ╭───
22
+ # │ Domain primitives
23
+ # ╰───
24
+
25
+ # _guard_log_level <level>
26
+ #
27
+ # EXIT
28
+ # 2 <level> is empty or not one of --log-level: error, warn, info or verbose
29
+ _guard_log_level() {
30
+ gll_levels="error,warn,info,verbose"
31
+ case "$1" in
32
+ error | warn | info | verbose) ;;
33
+ "") _fail 2 -v available_levels "$gll_levels" "--log-level needs a level" ;;
34
+ *) _fail 2 -v level "$1" -v available_levels "$gll_levels" "Unknown level" ;;
35
+ esac
36
+ }
37
+
38
+ # _guard_mode <mode>
39
+ #
40
+ # EXIT
41
+ # 2 <mode> is empty or not one of --mode: development or production
42
+ _guard_mode() {
43
+ gm_modes="development,production"
44
+ case "$1" in
45
+ development | production) ;;
46
+ "") _fail 2 -v available_modes "$gm_modes" "--mode needs a mode" ;;
47
+ *) _fail 2 -v mode "$1" -v available_modes "$gm_modes" "Unknown mode" ;;
48
+ esac
49
+ }
50
+
51
+ # _pick_config <app-dir> <file>
52
+ #
53
+ # Print <file> in <app-dir> when it exists, otherwise the default of VBlocks in
54
+ # src/.
55
+ _pick_config() {
56
+ _pick_file "$1/$2" "$_VB_DIR/src/$2"
57
+ }
58
+
59
+ # _print_file_path <file> <app-dir>
60
+ #
61
+ # Print the path of <file>, its folder as $APP_DIR, or as $VBLOCKS_DIR in gray
62
+ # for a default of VBlocks.
63
+ _print_file_path() {
64
+ case "$1" in
65
+ "$2"/*) printf '%s\n' "\$APP_DIR/${1#"$2"/}" ;;
66
+ "$_VB_DIR"/*) printf '%s\n' "${_GRAY}\$VBLOCKS_DIR/${1#"$_VB_DIR"/}${_RESET}" ;;
67
+ *) printf '%s\n' "$1" ;;
68
+ esac
69
+ }
70
+
71
+ # _print_summary <app-dir> <webpack-config> <postcss-config> <swc-config> <robots-file> <favicon-file>
72
+ #
73
+ # Print the app folder, the VBlocks folder and the files Webpack runs with. An
74
+ # empty <robots-file> prints no Robots line.
75
+ _print_summary() {
76
+ # The icons of the tools and the files, only on a terminal
77
+ ps_webpack_icon="" ps_postcss_icon="" ps_swc_icon=""
78
+ ps_robots_icon="" ps_favicon_icon=""
79
+ if [ -n "$_IS_TERMINAL" ]; then
80
+ ps_webpack_icon=" "
81
+ ps_postcss_icon=" "
82
+ ps_swc_icon="󱡮 "
83
+ ps_robots_icon="󰚩 "
84
+ ps_favicon_icon=" "
85
+ fi
86
+
87
+ printf '%s\t%s\n' "${_BOLD}\$APP_DIR${_RESET}" "$(_shorten_home "$1")"
88
+ printf '%s\t%s\n' "${_BOLD}\$VBLOCKS_DIR${_RESET}" "${_GRAY}$(_shorten_home "$_VB_DIR")${_RESET}"
89
+ printf '\n'
90
+ printf '%s\t%s\n' "${ps_webpack_icon}${_BOLD}Webpack${_RESET}" "$(_print_file_path "$2" "$1")"
91
+ printf '%s\t%s\n' "${ps_postcss_icon}${_BOLD}PostCSS${_RESET}" "$(_print_file_path "$3" "$1")"
92
+ printf '%s\t%s\n' "${ps_swc_icon}${_BOLD}SWC${_RESET}" "$(_print_file_path "$4" "$1")"
93
+ if [ -n "$5" ]; then
94
+ printf '%s\t%s\n' "${ps_robots_icon}${_BOLD}Robots${_RESET}" "$(_print_file_path "$5" "$1")"
95
+ fi
96
+ printf '%s\t%s\n' "${ps_favicon_icon}${_BOLD}Favicon${_RESET}" "$(_print_file_path "$6" "$1")"
97
+ printf '\n'
98
+ }
99
+
100
+ # _run_webpack <action> <webpack-config> [<webpack option>...]
101
+ #
102
+ # Run `webpack <action>` with <webpack-config> and the options, through the
103
+ # webpack-cli of VBlocks.
104
+ #
105
+ # EXIT
106
+ # 2 Webpack rejected an option or the config
107
+ # 3 Webpack failed
108
+ _run_webpack() {
109
+ rw_action=$1
110
+ rw_config=$2
111
+ shift 2
112
+
113
+ # Run the webpack-cli of VBlocks, the version VBlocks depends on. npx
114
+ # would run the first one it finds from the current folder, or offer to
115
+ # install one
116
+ rw_cli_file=$(node -p \
117
+ 'require.resolve("webpack-cli/bin/cli.js", { paths: [process.argv[1]] })' \
118
+ "$_VB_DIR") || _fail 3 "Could not find the webpack-cli of VBlocks"
119
+
120
+ rw_status=0
121
+ node "$rw_cli_file" "$rw_action" --config "$rw_config" "$@" || rw_status=$?
122
+
123
+ # webpack-cli exits 1 when the build has errors, 2 when an option or the
124
+ # config is wrong
125
+ case "$rw_status" in
126
+ 0) return 0 ;;
127
+ 2) _fail 2 "Webpack rejected an option or the config" ;;
128
+ *) _fail 3 "Webpack failed" ;;
129
+ esac
130
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@asd14/vblocks",
4
- "version": "5.3.0",
4
+ "version": "6.0.0",
5
5
  "description": "Zero-config React builds, as a static site or a single HTML file",
6
6
  "keywords": [
7
7
  "react",
@@ -45,7 +45,7 @@
45
45
  "./package.json": "./package.json"
46
46
  },
47
47
  "bin": {
48
- "vblocks": "bin/vblocks.sh"
48
+ "vblocks": "bin/vblocks"
49
49
  },
50
50
  "scripts": {
51
51
  "----UTIL": "",
@@ -74,6 +74,25 @@ declare module "*.eot" {
74
74
  export default url
75
75
  }
76
76
 
77
+ /**
78
+ * The MDX document as a React component. `components` replaces the element
79
+ * MDX renders for a tag, eg. `{ h1: Title }`.
80
+ *
81
+ * @example
82
+ * import Intro from "./intro.mdx"
83
+ *
84
+ * <Intro components={{ h1: Title }} />
85
+ */
86
+ declare module "*.mdx" {
87
+ import type { ComponentType } from "react"
88
+
89
+ const MDXContent: ComponentType<{
90
+ components?: Record<string, ComponentType<Record<string, unknown>>>
91
+ }>
92
+
93
+ export default MDXContent
94
+ }
95
+
77
96
  /**
78
97
  * The `.env` variables Webpack writes into the bundle. The browser has no
79
98
  * other part of Node's `process`.
@@ -10,25 +10,15 @@ import MiniCssExtractPlugin from "mini-css-extract-plugin"
10
10
  import webpack from "webpack"
11
11
  import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer"
12
12
 
13
- // `bin/vblocks.sh` sets them to the PostCSS and SWC configs it picked, the
14
- // app's own or the default
15
- const VB_SWC_CONFIG = process.env["VB_SWC_CONFIG"]
16
- const VB_POSTCSS_CONFIG = process.env["VB_POSTCSS_CONFIG"]
17
-
18
- if (!VB_SWC_CONFIG)
19
- throw new Error("VB_SWC_CONFIG environment variable is not defined")
20
-
21
- if (!VB_POSTCSS_CONFIG)
22
- throw new Error("VB_POSTCSS_CONFIG environment variable is not defined")
23
-
24
13
  /**
25
14
  * Read the SWC config, set the browser targets it lacks, and turn on React
26
15
  * Refresh when `hasReactRefresh` is true
27
16
  *
17
+ * @param {string} path
28
18
  * @param {{ hasReactRefresh: boolean }} options
29
19
  */
30
- const loadSwcConfig = ({ hasReactRefresh }) => {
31
- const content = fs.readFileSync(VB_SWC_CONFIG, "utf8")
20
+ const loadSwcConfig = (path, { hasReactRefresh }) => {
21
+ const content = fs.readFileSync(path, "utf8")
32
22
  const config = /** @type {unknown} */ (JSON.parse(content))
33
23
  const typedConfig = /** @type {import("@swc/core").Config} */ (config)
34
24
 
@@ -81,8 +71,9 @@ const getCssModuleOptions = isProduction => ({
81
71
  * @param {"local" | "global"} options.classScope - `local` renames each class
82
72
  * to a unique name, for `*.module.css`. `global` keeps the names as written
83
73
  * @param {boolean} options.isProduction
74
+ * @param {string} options.postcssConfigPath
84
75
  */
85
- const getCssLoaders = ({ classScope, isProduction }) => [
76
+ const getCssLoaders = ({ classScope, isProduction, postcssConfigPath }) => [
86
77
  {
87
78
  loader: MiniCssExtractPlugin.loader,
88
79
  },
@@ -105,7 +96,7 @@ const getCssLoaders = ({ classScope, isProduction }) => [
105
96
  loader: "postcss-loader",
106
97
  options: {
107
98
  postcssOptions: {
108
- config: VB_POSTCSS_CONFIG,
99
+ config: postcssConfigPath,
109
100
  },
110
101
  },
111
102
  },
@@ -234,7 +225,7 @@ const inlineAssets = compiler => {
234
225
  ...tag,
235
226
  attributes: {
236
227
  rel,
237
- // `bin/vblocks.sh` only passes a `favicon.svg`
228
+ // `bin/vblocks.d/webpack.sh` only passes a `favicon.svg`
238
229
  href: `data:image/svg+xml;base64,${Buffer.from(takeAsset(href)).toString("base64")}`,
239
230
  },
240
231
  }
@@ -257,7 +248,9 @@ const inlineAssets = compiler => {
257
248
  * @typedef {Object} VBlocksEnvironment
258
249
  *
259
250
  * @property {string} entryDir - The app folder: `--prefix`, or the folder VBlocks runs in
260
- * @property {string} robotsPath - Path to the robots.txt copied to the output folder
251
+ * @property {string} postcssConfigPath - Path to the PostCSS config, the app's own or the default
252
+ * @property {string} swcConfigPath - Path to the SWC config, the app's own or the default
253
+ * @property {string} [robotsPath] - Path to the robots.txt copied to the output folder, missing in a single-file build
261
254
  * @property {string} faviconPath - Path to the favicon.svg copied to the output folder
262
255
  * @property {boolean} [single] - Build one standalone index.html, every asset inlined
263
256
  * @property {boolean} [analyze] - Run the bundle analyzer next to the dev server
@@ -286,7 +279,16 @@ const STATS_BY_LOG_LEVEL = /** @type {const} */ ({
286
279
  * @returns {WebpackConfiguration}
287
280
  */
288
281
  export default (
289
- { entryDir, robotsPath, faviconPath, single, analyze, logLevel = "warn" },
282
+ {
283
+ entryDir,
284
+ postcssConfigPath,
285
+ swcConfigPath,
286
+ robotsPath,
287
+ faviconPath,
288
+ single,
289
+ analyze,
290
+ logLevel = "warn",
291
+ },
290
292
  { mode }
291
293
  ) => {
292
294
  const isProduction = mode === "production"
@@ -294,7 +296,7 @@ export default (
294
296
  const isSingle = Boolean(single) && !isServe
295
297
  const isAnalyze = Boolean(analyze) && isServe
296
298
  const hasReactRefresh = isServe && mode === "development"
297
- const swcConfig = loadSwcConfig({ hasReactRefresh })
299
+ const swcConfig = loadSwcConfig(swcConfigPath, { hasReactRefresh })
298
300
 
299
301
  const paths = {
300
302
  appEntry: `${entryDir}/src/index.tsx`,
@@ -362,12 +364,20 @@ export default (
362
364
  },
363
365
  {
364
366
  test: /\.module\.css$/,
365
- use: getCssLoaders({ classScope: "local", isProduction }),
367
+ use: getCssLoaders({
368
+ classScope: "local",
369
+ isProduction,
370
+ postcssConfigPath,
371
+ }),
366
372
  },
367
373
  {
368
374
  test: /\.css$/,
369
375
  exclude: /\.module\.css$/,
370
- use: getCssLoaders({ classScope: "global", isProduction }),
376
+ use: getCssLoaders({
377
+ classScope: "global",
378
+ isProduction,
379
+ postcssConfigPath,
380
+ }),
371
381
  },
372
382
  {
373
383
  test: /\.(jpg|gif|png|svg)$/,
@@ -466,6 +476,7 @@ export default (
466
476
  }),
467
477
 
468
478
  !isSingle &&
479
+ paths.robots &&
469
480
  new CopyPlugin({
470
481
  patterns: [
471
482
  {
@@ -0,0 +1,10 @@
1
+ #!/bin/sh
2
+
3
+ # Runs in the app folder, after `vblocks init` copies the app files
4
+
5
+ set -eu
6
+
7
+ # Name the page in the browser tab.
8
+ # `sed -i` differs between GNU and BSD, so write a copy and move it over
9
+ sed 's|<title>.*</title>|<title>Hello World :: VBlocks</title>|' src/index.html >src/index.html.tmp
10
+ mv -- src/index.html.tmp src/index.html
@@ -0,0 +1,74 @@
1
+ import { diagramEdges, diagramNodes } from "./diagram"
2
+
3
+ const findLabel = (nodeId: string) =>
4
+ diagramNodes.find(node => node.id === nodeId)?.data.label ?? nodeId
5
+
6
+ type LabelListProps = {
7
+ title: string
8
+ labels: string[]
9
+ }
10
+
11
+ const LabelList = ({ title, labels }: LabelListProps) => (
12
+ <div className="mt-4">
13
+ <h3 className="text-xs font-semibold tracking-wide text-stone-500 uppercase">
14
+ {title}
15
+ </h3>
16
+ <ul className="mt-1 font-mono text-sm">
17
+ {labels.length === 0 ? (
18
+ <li className="text-stone-400">none</li>
19
+ ) : (
20
+ labels.map(label => <li key={label}>{label}</li>)
21
+ )}
22
+ </ul>
23
+ </div>
24
+ )
25
+
26
+ type DetailsProps = {
27
+ selectedId: string
28
+ }
29
+
30
+ /**
31
+ * The selected step, with the steps it reads from and writes to, or the
32
+ * selected edge
33
+ */
34
+ const Details = ({ selectedId }: DetailsProps) => {
35
+ const node = diagramNodes.find(item => item.id === selectedId)
36
+
37
+ if (node) {
38
+ return (
39
+ <section>
40
+ <h2 className="font-mono text-sm font-semibold">{node.data.label}</h2>
41
+ <p className="mt-1 text-sm text-stone-600">{node.data.detail}</p>
42
+ <LabelList
43
+ title="In"
44
+ labels={diagramEdges
45
+ .filter(edge => edge.target === node.id)
46
+ .map(edge => findLabel(edge.source))}
47
+ />
48
+ <LabelList
49
+ title="Out"
50
+ labels={diagramEdges
51
+ .filter(edge => edge.source === node.id)
52
+ .map(edge => findLabel(edge.target))}
53
+ />
54
+ </section>
55
+ )
56
+ }
57
+
58
+ const edge = diagramEdges.find(item => item.id === selectedId)
59
+
60
+ return (
61
+ <section>
62
+ <h2 className="font-mono text-sm font-semibold">
63
+ {edge
64
+ ? `${findLabel(edge.source)} → ${findLabel(edge.target)}`
65
+ : selectedId}
66
+ </h2>
67
+ <p className="mt-1 text-sm text-stone-600">
68
+ {edge ? "The output of one step, read by the next" : "A new edge"}
69
+ </p>
70
+ </section>
71
+ )
72
+ }
73
+
74
+ export { Details }
@@ -0,0 +1,148 @@
1
+ import { useCallback } from "react"
2
+ import {
3
+ addEdge,
4
+ Background,
5
+ Controls,
6
+ Handle,
7
+ MarkerType,
8
+ Position,
9
+ ReactFlow,
10
+ useEdgesState,
11
+ useNodesState,
12
+ type Edge,
13
+ type Node,
14
+ type NodeProps,
15
+ type NodeTypes,
16
+ type OnConnect,
17
+ type OnSelectionChangeFunc,
18
+ } from "@xyflow/react"
19
+
20
+ import { CELL_SIZE, toPixels } from "./utils/grid"
21
+
22
+ type StepNode = Node<{ label: string; detail: string }, "step">
23
+
24
+ /**
25
+ * The graph. Edit these two lists, this specimen draws the VBlocks build
26
+ */
27
+ const diagramNodes = toPixels<StepNode>([
28
+ {
29
+ id: "index.tsx",
30
+ type: "step",
31
+ position: { x: 0, y: 0 },
32
+ size: { width: 12, height: 4 },
33
+ data: { label: "src/index.tsx", detail: "The application entry point" },
34
+ },
35
+ {
36
+ id: "index.css",
37
+ type: "step",
38
+ position: { x: 14, y: 0 },
39
+ size: { width: 12, height: 4 },
40
+ data: { label: "src/index.css", detail: "The global CSS" },
41
+ },
42
+ {
43
+ id: "swc",
44
+ type: "step",
45
+ position: { x: 0, y: 7 },
46
+ size: { width: 12, height: 4 },
47
+ data: { label: "SWC", detail: "Compiles TypeScript and JSX" },
48
+ },
49
+ {
50
+ id: "postcss",
51
+ type: "step",
52
+ position: { x: 14, y: 7 },
53
+ size: { width: 12, height: 4 },
54
+ data: { label: "PostCSS", detail: "Runs Tailwind and cssnano" },
55
+ },
56
+ {
57
+ id: "index.html",
58
+ type: "step",
59
+ position: { x: 28, y: 7 },
60
+ size: { width: 12, height: 4 },
61
+ data: { label: "src/index.html", detail: "The HTML template" },
62
+ },
63
+ {
64
+ id: "webpack",
65
+ type: "step",
66
+ position: { x: 14, y: 14 },
67
+ size: { width: 12, height: 4 },
68
+ data: { label: "Webpack", detail: "Bundles the modules and the assets" },
69
+ },
70
+ {
71
+ id: "dist",
72
+ type: "step",
73
+ position: { x: 14, y: 21 },
74
+ size: { width: 12, height: 4 },
75
+ data: { label: "dist/index.html", detail: "The bundle" },
76
+ },
77
+ ])
78
+
79
+ const diagramEdges: Edge[] = [
80
+ { id: "index.tsx-swc", source: "index.tsx", target: "swc" },
81
+ { id: "index.css-postcss", source: "index.css", target: "postcss" },
82
+ { id: "swc-webpack", source: "swc", target: "webpack" },
83
+ { id: "postcss-webpack", source: "postcss", target: "webpack" },
84
+ { id: "index.html-webpack", source: "index.html", target: "webpack" },
85
+ { id: "webpack-dist", source: "webpack", target: "dist", animated: true },
86
+ ]
87
+
88
+ const Step = ({ data, selected }: NodeProps<StepNode>) => (
89
+ <div
90
+ className={`h-full w-full overflow-hidden rounded-md border bg-white px-4 py-2 shadow-sm ${selected ? "border-stone-900" : "border-stone-300"}`}>
91
+ <Handle type="target" position={Position.Top} />
92
+ <div className="font-mono text-sm font-semibold text-stone-900">
93
+ {data.label}
94
+ </div>
95
+ <div className="text-xs text-stone-500">{data.detail}</div>
96
+ <Handle type="source" position={Position.Bottom} />
97
+ </div>
98
+ )
99
+
100
+ const nodeTypes: NodeTypes = { step: Step }
101
+
102
+ type DiagramProps = {
103
+ onSelect: (entityId: string | undefined) => void
104
+ }
105
+
106
+ const Diagram = ({ onSelect }: DiagramProps) => {
107
+ const [nodes, , onNodesChange] = useNodesState(diagramNodes)
108
+ const [edges, setEdges, onEdgesChange] = useEdgesState(diagramEdges)
109
+
110
+ const onConnect: OnConnect = useCallback(
111
+ connection => {
112
+ setEdges(currentEdges => addEdge(connection, currentEdges))
113
+ },
114
+ [setEdges]
115
+ )
116
+
117
+ // Memoize it, as React Flow asks for onSelectionChange
118
+ const onSelectionChange: OnSelectionChangeFunc = useCallback(
119
+ selection => {
120
+ onSelect(selection.nodes[0]?.id ?? selection.edges[0]?.id)
121
+ },
122
+ [onSelect]
123
+ )
124
+
125
+ return (
126
+ <ReactFlow
127
+ nodes={nodes}
128
+ edges={edges}
129
+ nodeTypes={nodeTypes}
130
+ onNodesChange={onNodesChange}
131
+ onEdgesChange={onEdgesChange}
132
+ onConnect={onConnect}
133
+ onSelectionChange={onSelectionChange}
134
+ // Snap a dragged node to the dots of <Background>
135
+ snapToGrid
136
+ snapGrid={[CELL_SIZE, CELL_SIZE]}
137
+ defaultEdgeOptions={{ markerEnd: { type: MarkerType.ArrowClosed } }}
138
+ // Center the diagram at 100%, the fit-view button of <Controls> still
139
+ // fits it to the screen
140
+ fitView
141
+ fitViewOptions={{ minZoom: 1, maxZoom: 1 }}>
142
+ <Background gap={CELL_SIZE} />
143
+ <Controls />
144
+ </ReactFlow>
145
+ )
146
+ }
147
+
148
+ export { Diagram, diagramEdges, diagramNodes }