Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88df4f2888 | ||
|
|
1d9460c173 | ||
|
|
8d69982a0b | ||
|
|
fb40e3ece4 | ||
|
|
9591fcb8a7 | ||
|
|
f80811318b | ||
|
|
cb9fea6656 | ||
|
|
b1afdcb585 | ||
|
|
f00e4db3dc | ||
|
|
b9552faa30 | ||
|
|
77f35c4e9e | ||
|
|
2c8425ffb0 | ||
|
|
2a071bc7ab | ||
|
|
2a8a26687b | ||
|
|
979331b12d | ||
|
|
329a782052 | ||
|
|
da558fd52d | ||
|
|
8aeadefa88 | ||
|
|
2066059c35 | ||
|
|
473fe8d421 | ||
|
|
5d6ae7946b | ||
|
|
1c85ab93eb | ||
|
|
67228f24b4 | ||
|
|
613a44c4d4 | ||
|
|
5685670895 | ||
|
|
72f85a97e5 | ||
|
|
ab28ad8f2c | ||
|
|
05e00c572d | ||
|
|
458069afb6 | ||
|
|
b3e5009aec | ||
|
|
eeb0660d83 | ||
|
|
138e1a8273 | ||
|
|
1b12b79a0d | ||
|
|
621bb21d52 | ||
|
|
3f3c6fb851 | ||
|
|
802938ec1a | ||
|
|
3e43aee6e9 | ||
|
|
bf4a9f48eb | ||
|
|
86455413d0 | ||
|
|
0cbc58f8d1 | ||
|
|
92841e3f35 | ||
|
|
e892ee0e53 | ||
|
|
591a51dcc2 | ||
|
|
7ba91d9829 | ||
|
|
e12fb89ada | ||
|
|
25507cb57a | ||
|
|
9d3bbc2c46 | ||
|
|
25e674badd | ||
|
|
e5f30a4a56 |
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
<title>Site Builder</title>
|
<title>Site Builder</title>
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
|||||||
Generated
+217
@@ -8,6 +8,15 @@
|
|||||||
"name": "whp-site-builder",
|
"name": "whp-site-builder",
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.20.3",
|
||||||
|
"@codemirror/commands": "^6.10.4",
|
||||||
|
"@codemirror/lang-css": "^6.3.1",
|
||||||
|
"@codemirror/lang-html": "^6.4.11",
|
||||||
|
"@codemirror/lang-javascript": "^6.2.5",
|
||||||
|
"@codemirror/language": "^6.12.4",
|
||||||
|
"@codemirror/state": "^6.7.1",
|
||||||
|
"@codemirror/theme-one-dark": "^6.1.3",
|
||||||
|
"@codemirror/view": "^6.43.6",
|
||||||
"@craftjs/core": "^0.2.10",
|
"@craftjs/core": "^0.2.10",
|
||||||
"@craftjs/layers": "^0.2.7",
|
"@craftjs/layers": "^0.2.7",
|
||||||
"dompurify": "^3.4.5",
|
"dompurify": "^3.4.5",
|
||||||
@@ -373,6 +382,133 @@
|
|||||||
"specificity": "bin/cli.js"
|
"specificity": "bin/cli.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@codemirror/autocomplete": {
|
||||||
|
"version": "6.20.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz",
|
||||||
|
"integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/language": "^6.0.0",
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.17.0",
|
||||||
|
"@lezer/common": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/commands": {
|
||||||
|
"version": "6.10.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.10.4.tgz",
|
||||||
|
"integrity": "sha512-Ryk9y9T0FFVF0cUGhAknveAyUOl/A1qReTFi+qPKtOh2Z9F4AUBz3XOrYD4ZEgZirdugVzHvd/2/Wcwy5OliTg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/language": "^6.0.0",
|
||||||
|
"@codemirror/state": "^6.7.0",
|
||||||
|
"@codemirror/view": "^6.27.0",
|
||||||
|
"@lezer/common": "^1.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/lang-css": {
|
||||||
|
"version": "6.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
|
||||||
|
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.0.0",
|
||||||
|
"@codemirror/language": "^6.0.0",
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@lezer/common": "^1.0.2",
|
||||||
|
"@lezer/css": "^1.1.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/lang-html": {
|
||||||
|
"version": "6.4.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
|
||||||
|
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.0.0",
|
||||||
|
"@codemirror/lang-css": "^6.0.0",
|
||||||
|
"@codemirror/lang-javascript": "^6.0.0",
|
||||||
|
"@codemirror/language": "^6.4.0",
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.17.0",
|
||||||
|
"@lezer/common": "^1.0.0",
|
||||||
|
"@lezer/css": "^1.1.0",
|
||||||
|
"@lezer/html": "^1.3.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/lang-javascript": {
|
||||||
|
"version": "6.2.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",
|
||||||
|
"integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.0.0",
|
||||||
|
"@codemirror/language": "^6.6.0",
|
||||||
|
"@codemirror/lint": "^6.0.0",
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.17.0",
|
||||||
|
"@lezer/common": "^1.0.0",
|
||||||
|
"@lezer/javascript": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/language": {
|
||||||
|
"version": "6.12.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz",
|
||||||
|
"integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.23.0",
|
||||||
|
"@lezer/common": "^1.5.0",
|
||||||
|
"@lezer/highlight": "^1.0.0",
|
||||||
|
"@lezer/lr": "^1.0.0",
|
||||||
|
"style-mod": "^4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/lint": {
|
||||||
|
"version": "6.9.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.7.tgz",
|
||||||
|
"integrity": "sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.42.0",
|
||||||
|
"crelt": "^1.0.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/state": {
|
||||||
|
"version": "6.7.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.1.tgz",
|
||||||
|
"integrity": "sha512-9QzNDgE4EYDnAHfrTlR2lwiPciiOymLtwKK+8yHQzCc7GXhAP9xdEbEJFy2IWB1j9UGUl9BsgMmTo/ImA02T7A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@marijn/find-cluster-break": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/theme-one-dark": {
|
||||||
|
"version": "6.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
|
||||||
|
"integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/language": "^6.0.0",
|
||||||
|
"@codemirror/state": "^6.0.0",
|
||||||
|
"@codemirror/view": "^6.0.0",
|
||||||
|
"@lezer/highlight": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@codemirror/view": {
|
||||||
|
"version": "6.43.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.6.tgz",
|
||||||
|
"integrity": "sha512-EVunGSYN1wz1p75WY1s3Xg7t3i8Yol0kGZGizNdX9BUFgMFILYVe8/u6EVpo7Ff5PwbZuILb4QAq7IZoKzIEQA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@codemirror/state": "^6.7.0",
|
||||||
|
"crelt": "^1.0.6",
|
||||||
|
"style-mod": "^4.1.0",
|
||||||
|
"w3c-keyname": "^2.2.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@craftjs/core": {
|
"node_modules/@craftjs/core": {
|
||||||
"version": "0.2.12",
|
"version": "0.2.12",
|
||||||
"resolved": "https://registry.npmjs.org/@craftjs/core/-/core-0.2.12.tgz",
|
"resolved": "https://registry.npmjs.org/@craftjs/core/-/core-0.2.12.tgz",
|
||||||
@@ -1093,6 +1229,69 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@lezer/common": {
|
||||||
|
"version": "1.5.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz",
|
||||||
|
"integrity": "sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@lezer/css": {
|
||||||
|
"version": "1.3.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.4.tgz",
|
||||||
|
"integrity": "sha512-N+tn9tej2hPvyKgHEApMOQfHczDJCwxrRFS3SPn9QjYN+uwHvEDnCgKRrb3mxDYxRS8sKMM8fhC3+lc04Abz5Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@lezer/common": "^1.2.0",
|
||||||
|
"@lezer/highlight": "^1.0.0",
|
||||||
|
"@lezer/lr": "^1.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@lezer/highlight": {
|
||||||
|
"version": "1.2.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
|
||||||
|
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@lezer/common": "^1.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@lezer/html": {
|
||||||
|
"version": "1.3.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",
|
||||||
|
"integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@lezer/common": "^1.2.0",
|
||||||
|
"@lezer/highlight": "^1.0.0",
|
||||||
|
"@lezer/lr": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@lezer/javascript": {
|
||||||
|
"version": "1.5.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
|
||||||
|
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@lezer/common": "^1.2.0",
|
||||||
|
"@lezer/highlight": "^1.1.3",
|
||||||
|
"@lezer/lr": "^1.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@lezer/lr": {
|
||||||
|
"version": "1.4.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz",
|
||||||
|
"integrity": "sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@lezer/common": "^1.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@marijn/find-cluster-break": {
|
||||||
|
"version": "1.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz",
|
||||||
|
"integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@playwright/test": {
|
"node_modules/@playwright/test": {
|
||||||
"version": "1.59.1",
|
"version": "1.59.1",
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz",
|
||||||
@@ -1873,6 +2072,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/crelt": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/css-color-keywords": {
|
"node_modules/css-color-keywords": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz",
|
||||||
@@ -2686,6 +2891,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/style-mod": {
|
||||||
|
"version": "4.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
|
||||||
|
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/styled-components": {
|
"node_modules/styled-components": {
|
||||||
"version": "6.3.12",
|
"version": "6.3.12",
|
||||||
"resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.3.12.tgz",
|
"resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.3.12.tgz",
|
||||||
@@ -3096,6 +3307,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/w3c-keyname": {
|
||||||
|
"version": "2.2.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
|
||||||
|
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/w3c-xmlserializer": {
|
"node_modules/w3c-xmlserializer": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
|
||||||
|
|||||||
@@ -14,6 +14,15 @@
|
|||||||
"test:unit:watch": "vitest"
|
"test:unit:watch": "vitest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@codemirror/autocomplete": "^6.20.3",
|
||||||
|
"@codemirror/commands": "^6.10.4",
|
||||||
|
"@codemirror/lang-css": "^6.3.1",
|
||||||
|
"@codemirror/lang-html": "^6.4.11",
|
||||||
|
"@codemirror/lang-javascript": "^6.2.5",
|
||||||
|
"@codemirror/language": "^6.12.4",
|
||||||
|
"@codemirror/state": "^6.7.1",
|
||||||
|
"@codemirror/theme-one-dark": "^6.1.3",
|
||||||
|
"@codemirror/view": "^6.43.6",
|
||||||
"@craftjs/core": "^0.2.10",
|
"@craftjs/core": "^0.2.10",
|
||||||
"@craftjs/layers": "^0.2.7",
|
"@craftjs/layers": "^0.2.7",
|
||||||
"dompurify": "^3.4.5",
|
"dompurify": "^3.4.5",
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Editor } from '@craftjs/core';
|
import { Editor } from '@craftjs/core';
|
||||||
import { EditorShell } from './editor/EditorShell';
|
import { EditorShell } from './editor/EditorShell';
|
||||||
|
import { RenderNode } from './editor/RenderNode';
|
||||||
import { componentResolver } from './components/resolver';
|
import { componentResolver } from './components/resolver';
|
||||||
import { WhpConfig } from './types';
|
import { WhpConfig } from './types';
|
||||||
import { EditorConfigProvider } from './state/EditorConfigContext';
|
import { EditorConfigProvider } from './state/EditorConfigContext';
|
||||||
@@ -23,7 +24,7 @@ export const App: React.FC<AppProps> = ({ whpConfig }) => {
|
|||||||
return (
|
return (
|
||||||
<EditorConfigProvider config={whpConfig}>
|
<EditorConfigProvider config={whpConfig}>
|
||||||
<SiteDesignProvider>
|
<SiteDesignProvider>
|
||||||
<Editor resolver={componentResolver} enabled={true}>
|
<Editor resolver={componentResolver} enabled={true} onRender={RenderNode}>
|
||||||
<PageProvider>
|
<PageProvider>
|
||||||
<SitesmithProvider>
|
<SitesmithProvider>
|
||||||
<EditorShell />
|
<EditorShell />
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { ButtonLink } from './ButtonLink';
|
||||||
|
|
||||||
|
const toHtml = (ButtonLink as any).toHtml;
|
||||||
|
|
||||||
|
describe('ButtonLink.toHtml href sanitization (attacker-controlled `href` prop)', () => {
|
||||||
|
test('a javascript: URL is neutralized', () => {
|
||||||
|
const { html } = toHtml({ href: 'javascript:alert(1)', text: 'Click' }, '');
|
||||||
|
expect(html).not.toContain('javascript:alert');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a quote-breakout href does not escape the href attribute', () => {
|
||||||
|
const malicious = '"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ href: malicious, text: 'Click' }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal href still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ href: 'https://example.com', text: 'Click' }, '');
|
||||||
|
expect(html).toContain('href="https://example.com"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ButtonLink.toHtml target (boolean-gated, not raw interpolation)', () => {
|
||||||
|
test('an attribute-breakout value for target does not reach the output raw', () => {
|
||||||
|
const malicious = '_blank" onmouseover="alert(1)' as any;
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x', target: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('target="_blank" still adds rel=noopener noreferrer', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: 'x', target: '_blank' }, '');
|
||||||
|
expect(html).toContain('target="_blank"');
|
||||||
|
expect(html).toContain('rel="noopener noreferrer"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ButtonLink.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||||
|
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: '</a><img src=x onerror=alert(1)>' }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).toContain('<img');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: 'Tom & Jerry' }, '');
|
||||||
|
expect(html).toContain('Tom & Jerry');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal text value still renders unchanged', () => {
|
||||||
|
const { html } = toHtml({ href: '#', text: 'Click Me' }, '');
|
||||||
|
expect(html).toContain('>Click Me</a>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
||||||
|
|
||||||
interface ButtonLinkProps {
|
interface ButtonLinkProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
@@ -78,7 +78,7 @@ ButtonLink.craft = {
|
|||||||
textDecoration: 'none',
|
textDecoration: 'none',
|
||||||
...props.style,
|
...props.style,
|
||||||
});
|
});
|
||||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
const escapedText = escapeHtml(props.text || '');
|
||||||
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
|
const targetAttr = props.target === '_blank' ? ' target="_blank" rel="noopener noreferrer"' : '';
|
||||||
return {
|
return {
|
||||||
html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
|
html: `<a href="${escapeAttr(safeUrl(props.href || '#'))}"${targetAttr}${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</a>`,
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Divider } from './Divider';
|
||||||
|
|
||||||
|
const toHtml = (Divider as any).toHtml;
|
||||||
|
|
||||||
|
describe('Divider.toHtml normal rendering', () => {
|
||||||
|
test('renders thickness/color into the border-top style', () => {
|
||||||
|
const { html } = toHtml({ thickness: '2px', color: '#ff0000' }, '');
|
||||||
|
expect(html).toContain('border-top:2px solid #ff0000');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Divider.toHtml XSS hardening (thickness/color into style=)', () => {
|
||||||
|
test('a thickness value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '1px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ thickness: malicious as any, color: '#000' }, '');
|
||||||
|
// The quote must not survive unescaped -- otherwise it closes style=""
|
||||||
|
// early and "onmouseover" becomes a live, attacker-controlled attribute.
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a color value with a </style><script> breakout is neutralized', () => {
|
||||||
|
const malicious = '#000</style><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ thickness: '1px', color: malicious as any }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-string thickness (object) does not raw-splice into style=""', () => {
|
||||||
|
const malicious = { toString: () => '1px" onmouseover="alert(1)' };
|
||||||
|
const { html } = toHtml({ thickness: malicious as any, color: '#000' }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Footer } from './Footer';
|
||||||
|
|
||||||
|
const toHtml = (Footer as any).toHtml;
|
||||||
|
|
||||||
|
describe('Footer.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||||
|
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||||
|
const { html } = toHtml({ text: '</footer><img src=x onerror=alert(1)>' }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).toContain('<img');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||||
|
const { html } = toHtml({ text: 'Terms & Conditions' }, '');
|
||||||
|
expect(html).toContain('Terms & Conditions');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal copyright text value still renders unchanged', () => {
|
||||||
|
const { html } = toHtml({ text: '© 2026 MySite. All rights reserved.' }, '');
|
||||||
|
expect(html).toContain('© 2026 MySite. All rights reserved.');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
|
import { escapeHtml } from '../../utils/escape';
|
||||||
|
|
||||||
interface FooterProps {
|
interface FooterProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
@@ -107,6 +108,6 @@ Footer.craft = {
|
|||||||
textAlign: 'center',
|
textAlign: 'center',
|
||||||
...props.style,
|
...props.style,
|
||||||
});
|
});
|
||||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
const escapedText = escapeHtml(props.text || '');
|
||||||
return { html: `<footer${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</footer>` };
|
return { html: `<footer${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</footer>` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Heading } from './Heading';
|
||||||
|
|
||||||
|
const toHtml = (Heading as any).toHtml;
|
||||||
|
|
||||||
|
describe('Heading.toHtml level allowlist (adversarial re-review, same class as C1)', () => {
|
||||||
|
test('a malicious level value clamps to h2 -- no injected <img>, no broken-out tag', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', level: 'h2><img src=x onerror=alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).not.toContain('onerror');
|
||||||
|
expect(html.startsWith('<h2')).toBe(true);
|
||||||
|
expect(html.endsWith('</h2>')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a numeric out-of-range level (99) clamps to h2', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', level: 99 as any }, '');
|
||||||
|
expect(html.startsWith('<h2')).toBe(true);
|
||||||
|
expect(html.endsWith('</h2>')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-heading string level clamps to h2', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', level: 'script' as any }, '');
|
||||||
|
expect(html.startsWith('<h2')).toBe(true);
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal valid level (h4) still emits <h4', () => {
|
||||||
|
const { html } = toHtml({ text: 'x', level: 'h4' }, '');
|
||||||
|
expect(html).toContain('<h4');
|
||||||
|
expect(html).toContain('</h4>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('all valid levels h1-h6 still work', () => {
|
||||||
|
for (const level of ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']) {
|
||||||
|
const { html } = toHtml({ text: 'x', level }, '');
|
||||||
|
expect(html.startsWith(`<${level}`)).toBe(true);
|
||||||
|
expect(html.endsWith(`</${level}>`)).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Heading.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||||
|
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||||
|
const { html } = toHtml({ text: '</h2><img src=x onerror=alert(1)>', level: 'h2' }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).toContain('<img');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||||
|
const { html } = toHtml({ text: 'Fish & Chips', level: 'h2' }, '');
|
||||||
|
expect(html).toContain('Fish & Chips');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal text value still renders unchanged', () => {
|
||||||
|
const { html } = toHtml({ text: 'Hello world', level: 'h2' }, '');
|
||||||
|
expect(html).toBe('<h2>Hello world</h2>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,20 @@
|
|||||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
|
import { escapeHtml } from '../../utils/escape';
|
||||||
|
|
||||||
type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
type HeadingLevel = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
|
||||||
|
|
||||||
|
// `level` is settable via the AI `update_props` path and from deserialized
|
||||||
|
// saved state -- neither type-checked at runtime -- and is interpolated
|
||||||
|
// directly into the tag position (`React.createElement(level, ...)` /
|
||||||
|
// `<${tag}` in `toHtml`). A malicious value like `h2><img src=x
|
||||||
|
// onerror=alert(1)` (or a non-h1-6 string) must never reach that position
|
||||||
|
// unchecked. Anything not in this allowlist clamps to `'h2'`.
|
||||||
|
const ALLOWED_HEADING_LEVELS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const;
|
||||||
|
const sanitizeHeadingLevel = (level: unknown): HeadingLevel =>
|
||||||
|
(ALLOWED_HEADING_LEVELS as readonly unknown[]).includes(level) ? (level as HeadingLevel) : 'h2';
|
||||||
|
|
||||||
interface HeadingProps {
|
interface HeadingProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
level?: HeadingLevel;
|
level?: HeadingLevel;
|
||||||
@@ -30,6 +41,7 @@ export const Heading: UserComponent<HeadingProps> = ({
|
|||||||
selected: node.events.selected,
|
selected: node.events.selected,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const safeLevel = sanitizeHeadingLevel(level);
|
||||||
const elRef = useRef<HTMLElement | null>(null);
|
const elRef = useRef<HTMLElement | null>(null);
|
||||||
const editedTextRef = useRef<string | null>(null);
|
const editedTextRef = useRef<string | null>(null);
|
||||||
|
|
||||||
@@ -59,7 +71,7 @@ export const Heading: UserComponent<HeadingProps> = ({
|
|||||||
}
|
}
|
||||||
}, [text, selected]);
|
}, [text, selected]);
|
||||||
|
|
||||||
return React.createElement(level, {
|
return React.createElement(safeLevel, {
|
||||||
ref: (ref: HTMLElement | null): void => {
|
ref: (ref: HTMLElement | null): void => {
|
||||||
elRef.current = ref;
|
elRef.current = ref;
|
||||||
if (ref) connect(drag(ref));
|
if (ref) connect(drag(ref));
|
||||||
@@ -98,8 +110,8 @@ Heading.craft = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
(Heading as any).toHtml = (props: HeadingProps, _childrenHtml: string) => {
|
(Heading as any).toHtml = (props: HeadingProps, _childrenHtml: string) => {
|
||||||
const tag = props.level || 'h2';
|
const tag = sanitizeHeadingLevel(props.level);
|
||||||
const safeText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
const safeText = escapeHtml(props.text || '');
|
||||||
const styleStr = cssPropsToString(props.style);
|
const styleStr = cssPropsToString(props.style);
|
||||||
return { html: `<${tag}${styleStr ? ` style="${styleStr}"` : ''}>${safeText}</${tag}>` };
|
return { html: `<${tag}${styleStr ? ` style="${styleStr}"` : ''}>${safeText}</${tag}>` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -21,3 +21,46 @@ describe('purifyHtml', () => {
|
|||||||
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
expect(purifyHtml('<form><input name="x"></form>')).not.toContain('<form');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('purifyHtml iframe sandboxing (M-6)', () => {
|
||||||
|
test('forces a restrictive sandbox attribute onto every iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sandbox value omits allow-top-navigation (no top-level nav escape)', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
const sandbox = out.match(/sandbox="([^"]*)"/)![1];
|
||||||
|
expect(sandbox).not.toMatch(/allow-top-navigation/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate embeds (YouTube) still work and get sandboxed too', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://www.youtube.com/embed/abc" allowfullscreen></iframe>');
|
||||||
|
expect(out).toContain('youtube.com/embed/abc');
|
||||||
|
expect(out).toMatch(/<iframe[^>]*\bsandbox="[^"]+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adds referrerpolicy=no-referrer to iframes', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('referrerpolicy="no-referrer"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script/on* attributes are still stripped alongside the sandboxed iframe', () => {
|
||||||
|
const out = purifyHtml('<iframe src="https://example.com/" onload="alert(1)"></iframe><script>alert(2)</script>');
|
||||||
|
expect(out).not.toContain('onload');
|
||||||
|
expect(out).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('repeated calls do not leak/accumulate the hook (no duplicate sandbox attr, no cross-call state)', () => {
|
||||||
|
purifyHtml('<iframe src="https://a.example/"></iframe>');
|
||||||
|
purifyHtml('<iframe src="https://b.example/"></iframe>');
|
||||||
|
const out = purifyHtml('<iframe src="https://c.example/"></iframe>');
|
||||||
|
const sandboxMatches = out.match(/sandbox="/g) || [];
|
||||||
|
expect(sandboxMatches.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-iframe element sanitized alongside an iframe is not touched by the hook', () => {
|
||||||
|
const out = purifyHtml('<p>hi</p><iframe src="https://example.com/"></iframe>');
|
||||||
|
expect(out).toContain('<p>hi</p>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,4 +10,16 @@ describe('HtmlBlock.toHtml sanitizes raw code (A4.1)', () => {
|
|||||||
expect(html).not.toContain('onclick');
|
expect(html).not.toContain('onclick');
|
||||||
expect(html).toContain('<p>hi</p>');
|
expect(html).toContain('<p>hi</p>');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('does not wrap output in an unsanitized element carrying the style prop raw', () => {
|
||||||
|
// toHtml only ever returns the sanitized `code` blob -- there is no
|
||||||
|
// wrapper <div style="..."> in the exported HTML, so a malicious
|
||||||
|
// `style` prop (e.g. an attacker-controlled object with a breakout
|
||||||
|
// toString()) has nothing to splice into.
|
||||||
|
const malicious = { toString: () => 'color:red" onmouseover="alert(1)' } as any;
|
||||||
|
const { html } = toHtml({ code: '<p>hi</p>', style: malicious }, '');
|
||||||
|
expect(html).not.toMatch(/onmouseover/);
|
||||||
|
expect(html).not.toMatch(/<div/);
|
||||||
|
expect(html).toBe('<p>hi</p>');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -24,14 +24,42 @@ const PURIFY_CONFIG = {
|
|||||||
'href','src','alt','title','target','rel',
|
'href','src','alt','title','target','rel',
|
||||||
'width','height','class',
|
'width','height','class',
|
||||||
'allowfullscreen','allow','frameborder',
|
'allowfullscreen','allow','frameborder',
|
||||||
|
'sandbox','referrerpolicy',
|
||||||
],
|
],
|
||||||
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
|
||||||
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
|
||||||
FORBID_ATTR: [/^on/i],
|
FORBID_ATTR: [/^on/i],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// M-6: `<iframe>` is allowed (maps/video embeds are a legitimate use case)
|
||||||
|
// but an iframe with a `src` and NO `sandbox` attribute is a clickjacking/
|
||||||
|
// phishing vector (DOMPurify already strips <script>/on*=, but an
|
||||||
|
// unsandboxed iframe still gets full script execution, same-origin-ish
|
||||||
|
// access via document.domain tricks, top-level navigation, etc., inside
|
||||||
|
// itself). This hook force-sets a restrictive sandbox on every iframe that
|
||||||
|
// survives sanitization, keeping `allow-scripts`/`allow-same-origin`/
|
||||||
|
// `allow-popups`/`allow-forms` (needed for interactive maps/video/oauth
|
||||||
|
// popups) but deliberately omitting `allow-top-navigation` so an embedded
|
||||||
|
// page can never redirect/hijack the parent tab.
|
||||||
|
const IFRAME_SANDBOX_HOOK = (node: Element): void => {
|
||||||
|
if (node.nodeName === 'IFRAME') {
|
||||||
|
node.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms');
|
||||||
|
node.setAttribute('referrerpolicy', 'no-referrer');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export function purifyHtml(input: string): string {
|
export function purifyHtml(input: string): string {
|
||||||
|
// Hook is added immediately before sanitize() and removed immediately
|
||||||
|
// after, scoped tightly to this single call -- so it can never leak onto
|
||||||
|
// (or accumulate duplicate copies across) any other DOMPurify.sanitize()
|
||||||
|
// call elsewhere in the app, and repeated purifyHtml() calls never stack
|
||||||
|
// multiple copies of the same hook.
|
||||||
|
DOMPurify.addHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK);
|
||||||
|
try {
|
||||||
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
|
||||||
|
} finally {
|
||||||
|
DOMPurify.removeHook('afterSanitizeAttributes', IFRAME_SANDBOX_HOOK as any);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Icon } from './Icon';
|
||||||
|
|
||||||
|
const toHtml = (Icon as any).toHtml;
|
||||||
|
|
||||||
|
describe('Icon.toHtml normal rendering', () => {
|
||||||
|
test('renders icon class, size/color style, and link href', () => {
|
||||||
|
const { html } = toHtml({ icon: 'fa-star', size: '32px', color: '#3b82f6', link: 'https://example.com' }, '');
|
||||||
|
expect(html).toContain('class="fa fa-star"');
|
||||||
|
expect(html).toContain('font-size:32px');
|
||||||
|
expect(html).toContain('color:#3b82f6');
|
||||||
|
expect(html).toContain('href="https://example.com"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Icon.toHtml XSS hardening', () => {
|
||||||
|
test('an icon name with an attribute-breakout string is escaped, not raw-concatenated', () => {
|
||||||
|
const malicious = 'star"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ icon: malicious as any }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toMatch(/class="fa star"><script>/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a size value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '24px" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ size: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onerror="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a bgSize/bgColor breakout via background wrapper is neutralized', () => {
|
||||||
|
const malicious = '56px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ bgShape: 'circle', bgColor: '#fff', bgSize: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a javascript: link is neutralized to an empty href', () => {
|
||||||
|
const { html } = toHtml({ link: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('javascript:alert(1)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a link value with an attribute-breakout string cannot escape href=""', () => {
|
||||||
|
const malicious = 'https://example.com" onclick="alert(1)';
|
||||||
|
const { html } = toHtml({ link: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onclick="/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Logo } from './Logo';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Regression coverage for Logo.toHtml -- audited during the toHtml
|
||||||
|
* attribute-XSS sweep (see task-cssxss-brief.md) and found already fully
|
||||||
|
* sanitized (href/src via escapeAttr(safeUrl()), alt/text via escapeAttr /
|
||||||
|
* escapeHtml, imageWidth/fontSize/etc. routed through cssPropsToString which
|
||||||
|
* sanitizes every value regardless of declared type). No fix was required;
|
||||||
|
* these tests lock that behavior in against regressions.
|
||||||
|
*/
|
||||||
|
const toHtml = (Logo as any).toHtml;
|
||||||
|
|
||||||
|
describe('Logo.toHtml href sanitization (attacker-controlled `href` prop)', () => {
|
||||||
|
test('a javascript: URL is neutralized', () => {
|
||||||
|
const { html } = toHtml({ href: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('javascript:alert');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a quote-breakout href does not escape the anchor attribute', () => {
|
||||||
|
const malicious = '"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ href: malicious }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Logo.toHtml image src/alt sanitization (type="image")', () => {
|
||||||
|
test('a javascript: imageSrc is neutralized', () => {
|
||||||
|
const { html } = toHtml({ type: 'image', imageSrc: 'javascript:alert(1)', text: 'Logo' }, '');
|
||||||
|
expect(html).not.toContain('javascript:alert');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a quote-breakout alt (from `text`) does not escape the img attribute', () => {
|
||||||
|
const malicious = '"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ type: 'image', imageSrc: 'https://example.com/logo.png', text: malicious }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-numeric imageWidth (attribute-breakout attempt) does not escape the style attribute', () => {
|
||||||
|
const malicious = '1"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ type: 'image', imageSrc: 'https://example.com/logo.png', imageWidth: malicious }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Logo.toHtml text-logo styling sanitization', () => {
|
||||||
|
test('a quote-breakout color does not escape the span style attribute', () => {
|
||||||
|
const malicious = 'red" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ type: 'text', text: 'MySite', color: malicious }, '');
|
||||||
|
// The raw `"` must never survive un-escaped inside the style attribute
|
||||||
|
// value -- if it did, `onmouseover` would land as a REAL new HTML
|
||||||
|
// attribute (breakout) rather than being inert CSS-value garbage inside
|
||||||
|
// a properly-escaped style="...".
|
||||||
|
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal logo renders as expected', () => {
|
||||||
|
const { html } = toHtml({ type: 'text', text: 'MySite', href: '/' }, '');
|
||||||
|
expect(html).toContain('href="/"');
|
||||||
|
expect(html).toContain('MySite');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -104,7 +104,7 @@ Logo.craft = {
|
|||||||
let innerHtml: string;
|
let innerHtml: string;
|
||||||
if (props.type === 'image' && props.imageSrc) {
|
if (props.type === 'image' && props.imageSrc) {
|
||||||
const imgStyle = cssPropsToString({ width: props.imageWidth || '120px', height: 'auto', display: 'block' });
|
const imgStyle = cssPropsToString({ width: props.imageWidth || '120px', height: 'auto', display: 'block' });
|
||||||
innerHtml = `<img src="${escapeAttr(safeUrl(props.imageSrc))}" alt="${escapeAttr(props.text || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} />`;
|
innerHtml = `<img src="${escapeAttr(safeImageUrl(props.imageSrc))}" alt="${escapeAttr(props.text || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} />`;
|
||||||
} else {
|
} else {
|
||||||
const spanStyle = cssPropsToString({
|
const spanStyle = cssPropsToString({
|
||||||
fontWeight: props.fontWeight || '700',
|
fontWeight: props.fontWeight || '700',
|
||||||
|
|||||||
@@ -5,28 +5,84 @@ const toHtml = (Navbar as any).toHtml;
|
|||||||
|
|
||||||
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
describe('Navbar.toHtml hamburger accessibility (F2.3)', () => {
|
||||||
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
test('mobile toggle button has an accessible name, aria-expanded, and aria-controls', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
expect(html).toMatch(/class="navbar-hamburger"[^>]*aria-label="Toggle navigation menu"/);
|
||||||
expect(html).toMatch(/aria-expanded="false"/);
|
expect(html).toMatch(/aria-expanded="false"/);
|
||||||
expect(html).toMatch(/aria-controls="navbar-links"/);
|
expect(html).toMatch(/aria-controls="[^"]+"/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('aria-controls target id exists on the links container', () => {
|
test('aria-controls target id exists on the links container', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toContain('id="navbar-links"');
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
expect(html).toContain(`id="${controls}"`);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('toggle script flips aria-expanded on click', () => {
|
test('toggle script flips aria-expanded on click', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: true }, '');
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
expect(html).toMatch(/setAttribute\(['"]aria-expanded['"]/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('no mobile menu: no hamburger button emitted', () => {
|
test('no mobile menu: no hamburger button emitted', () => {
|
||||||
const { html } = toHtml({ showMobileMenu: false }, '');
|
const { html } = toHtml({ showMobileMenu: false }, '', 'node-nav1');
|
||||||
expect(html).not.toContain('navbar-hamburger');
|
expect(html).not.toContain('navbar-hamburger');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Navbar.toHtml node-scoped ids/hover styles (M-1: two navbars must not collide)', () => {
|
||||||
|
test('no bare unscoped id="navbar-links" is emitted', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html).not.toContain('id="navbar-links"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two different node ids produce different links-container ids', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav2');
|
||||||
|
const id1 = html1.match(/id="([^"]+)"/)![1];
|
||||||
|
const id2 = html2.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(id1).not.toBe(id2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('aria-controls always equals the actual links-container id', () => {
|
||||||
|
const { html } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const controls = html.match(/aria-controls="([^"]+)"/)![1];
|
||||||
|
const linksId = html.match(/id="([^"]+)"/)![1];
|
||||||
|
expect(controls).toBe(linksId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hover style selectors are scoped per-instance, not bare .navbar-link/.navbar-cta', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
// A selector rule that STARTS the line with .navbar-link:hover (i.e. not
|
||||||
|
// preceded by a per-instance ancestor class) would be the old, unscoped,
|
||||||
|
// globally-colliding form.
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-link:hover/m);
|
||||||
|
expect(html).not.toMatch(/^\s*\.navbar-cta:hover/m);
|
||||||
|
// still present, just scoped under a per-instance ancestor class
|
||||||
|
expect(html).toMatch(/\.navbar-link:hover/);
|
||||||
|
expect(html).toMatch(/\.[\w-]+ \.navbar-link:hover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two navbars with different hoverColor do not leak style onto each other (scoped selectors differ)', () => {
|
||||||
|
const { html: html1 } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ hoverColor: '#00ff00' }, '', 'node-nav2');
|
||||||
|
const scope1 = html1.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
const scope2 = html2.match(/<style>\s*\.([\w-]+)\s/)![1];
|
||||||
|
expect(scope1).not.toBe(scope2);
|
||||||
|
expect(html1).toContain(`.${scope1} .navbar-link:hover`);
|
||||||
|
expect(html2).toContain(`.${scope2} .navbar-link:hover`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal single navbar still renders its hover style (visual output preserved)', () => {
|
||||||
|
const { html } = toHtml({ hoverColor: '#ff0000' }, '', 'node-nav1');
|
||||||
|
expect(html).toMatch(/:hover\s*\{\s*color:\s*#ff0000/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('same node id -> identical output across calls (deterministic)', () => {
|
||||||
|
const { html: html1 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
const { html: html2 } = toHtml({ showMobileMenu: true }, '', 'node-nav1');
|
||||||
|
expect(html1).toBe(html2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
describe('Navbar.toHtml XSS hardening (hoverColor/backgroundColor/ctaColor into <style>)', () => {
|
||||||
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
test('a hoverColor value containing </style><script> is neutralized in the hover <style> block', () => {
|
||||||
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
const malicious = '#fff}</style><script>alert(1)</script><style>{';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties, useState } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, cssValue, scopeId } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -210,7 +210,7 @@ Navbar.craft = {
|
|||||||
|
|
||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string) => {
|
(Navbar as any).toHtml = (props: NavbarProps, _childrenHtml: string, nodeId?: string) => {
|
||||||
// Sanitized once here -- these are raw string-interpolation sinks below
|
// Sanitized once here -- these are raw string-interpolation sinks below
|
||||||
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
// (hoverCol/bgColor go into a <style> block, the worst case: </style>
|
||||||
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
// breakout -> arbitrary <script>), see task-cssxss-brief.md.
|
||||||
@@ -224,6 +224,19 @@ Navbar.craft = {
|
|||||||
const sticky = props.isSticky;
|
const sticky = props.isSticky;
|
||||||
const mobile = props.showMobileMenu;
|
const mobile = props.showMobileMenu;
|
||||||
const logoUrl = props.logoUrl || '/';
|
const logoUrl = props.logoUrl || '/';
|
||||||
|
const links0 = props.links || defaultLinks;
|
||||||
|
|
||||||
|
// M-1: deterministic AND unique per-instance scope, keyed on the Craft
|
||||||
|
// node id. Two Navbars on the same page previously emitted an identical
|
||||||
|
// fixed id="navbar-links" (invalid duplicate-id HTML, ambiguous
|
||||||
|
// aria-controls target) and unscoped `.navbar-link:hover`/`.navbar-cta:hover`
|
||||||
|
// rules in each instance's own <style> block -- since both blocks target
|
||||||
|
// the SAME global selector, the later one in the DOM silently overrides
|
||||||
|
// the earlier one's hover color/behavior for BOTH navbars. Scoping the
|
||||||
|
// links-container id and adding a per-instance class on the <nav> root
|
||||||
|
// (used to prefix the hover selectors) eliminates both collisions.
|
||||||
|
const scope = scopeId(nodeId, JSON.stringify(links0) + alignment + pad, 'nav');
|
||||||
|
const linksId = `${scope}_links`;
|
||||||
|
|
||||||
const navStyle = cssPropsToString({
|
const navStyle = cssPropsToString({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
@@ -239,7 +252,7 @@ Navbar.craft = {
|
|||||||
let logoHtml: string;
|
let logoHtml: string;
|
||||||
if (props.logoType === 'image' && props.logoImage) {
|
if (props.logoType === 'image' && props.logoImage) {
|
||||||
const imgStyle = cssPropsToString({ width: props.logoWidth || '120px', height: 'auto', display: 'block' });
|
const imgStyle = cssPropsToString({ width: props.logoWidth || '120px', height: 'auto', display: 'block' });
|
||||||
logoHtml = `<a href="${escapeAttr(safeUrl(logoUrl))}" style="text-decoration:none;display:flex;align-items:center;flex-shrink:0"><img src="${escapeAttr(safeUrl(props.logoImage))}" alt="${escapeAttr(props.logoText || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} /></a>`;
|
logoHtml = `<a href="${escapeAttr(safeUrl(logoUrl))}" style="text-decoration:none;display:flex;align-items:center;flex-shrink:0"><img src="${escapeAttr(safeImageUrl(props.logoImage))}" alt="${escapeAttr(props.logoText || 'Logo')}"${imgStyle ? ` style="${imgStyle}"` : ''} /></a>`;
|
||||||
} else {
|
} else {
|
||||||
const logoStyle = cssPropsToString({
|
const logoStyle = cssPropsToString({
|
||||||
fontWeight: '700',
|
fontWeight: '700',
|
||||||
@@ -272,21 +285,23 @@ Navbar.craft = {
|
|||||||
// via aria-expanded, kept in sync with the .navbar-open class by the
|
// via aria-expanded, kept in sync with the .navbar-open class by the
|
||||||
// inline onclick handler.
|
// inline onclick handler.
|
||||||
const hamburgerHtml = mobile
|
const hamburgerHtml = mobile
|
||||||
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="navbar-links" onclick="var m=this.parentElement.querySelector('.navbar-links');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
? `\n <button class="navbar-hamburger" aria-label="Toggle navigation menu" aria-expanded="false" aria-controls="${escapeAttr(linksId)}" onclick="var m=document.getElementById('${linksId}');var open=m.classList.toggle('navbar-open');this.setAttribute('aria-expanded', open ? 'true' : 'false');" style="display:none;background:none;border:none;cursor:pointer;padding:4px;flex-direction:column;gap:4px">
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
<span style="display:block;width:24px;height:2px;background-color:${escapeAttr(textCol)}"></span>
|
||||||
</button>`
|
</button>`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
// Hover CSS
|
// Hover CSS -- scoped under `.${scope}` (a class on the <nav> root, added
|
||||||
|
// below) so it can only ever match THIS instance's links/CTA, never bleed
|
||||||
|
// into or get overridden by another Navbar instance's rules.
|
||||||
const hoverCss = `<style>
|
const hoverCss = `<style>
|
||||||
.navbar-link:hover { color: ${hoverCol} !important; }
|
.${scope} .navbar-link:hover { color: ${hoverCol} !important; }
|
||||||
.navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
.${scope} .navbar-cta:hover { filter: brightness(1.1); }${mobile ? `
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
.navbar-hamburger { display: flex !important; }
|
.${scope} .navbar-hamburger { display: flex !important; }
|
||||||
.navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
.${scope} .navbar-links { display: none !important; position: absolute; top: 100%; left: 0; right: 0; flex-direction: column !important; background-color: ${bgColor}; padding: 12px 24px; gap: 12px !important; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
|
||||||
.navbar-links.navbar-open { display: flex !important; }
|
.${scope} .navbar-links.navbar-open { display: flex !important; }
|
||||||
}` : ''}
|
}` : ''}
|
||||||
</style>`;
|
</style>`;
|
||||||
|
|
||||||
@@ -309,9 +324,9 @@ Navbar.craft = {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
html: `${hoverCss}
|
html: `${hoverCss}
|
||||||
<nav${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
<nav class="${scope}"${navStyle ? ` style="${navStyle}${mobile ? ';position:relative' : ''}"` : ''}>
|
||||||
${logoHtml}${hamburgerHtml}
|
${logoHtml}${hamburgerHtml}
|
||||||
<div class="navbar-links" id="navbar-links" style="display:flex;align-items:center;gap:24px">
|
<div class="navbar-links" id="${linksId}" style="display:flex;align-items:center;gap:24px">
|
||||||
${linksHtmlWithClass}
|
${linksHtmlWithClass}
|
||||||
</div>
|
</div>
|
||||||
</nav>`,
|
</nav>`,
|
||||||
|
|||||||
@@ -11,3 +11,22 @@ describe('SearchBar.toHtml decorative icons (F2.5)', () => {
|
|||||||
icons.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
icons.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('SearchBar.toHtml XSS hardening (placeholder/buttonText/showButton)', () => {
|
||||||
|
test('a placeholder value with an attribute-breakout string cannot escape placeholder=""', () => {
|
||||||
|
const malicious = 'Search..." onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ placeholder: malicious }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a buttonText value with a script tag is escaped as text content, not raw HTML', () => {
|
||||||
|
const malicious = '<script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ buttonText: malicious, showButton: true }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-boolean showButton (string "false") still yields fixed, safe border-radius values', () => {
|
||||||
|
const { html } = toHtml({ showButton: 'false' as any }, '');
|
||||||
|
expect(html).toMatch(/border-radius:(8px 0 0 8px|8px)/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -14,3 +14,40 @@ describe('SocialLinks.toHtml accessibility (F2.5)', () => {
|
|||||||
expect(html).toMatch(/<i class="fa fa-twitter"[^>]*aria-hidden="true"/);
|
expect(html).toMatch(/<i class="fa fa-twitter"[^>]*aria-hidden="true"/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('SocialLinks.toHtml XSS hardening (iconSize/iconColor/iconBgColor/gap into style=)', () => {
|
||||||
|
test('an iconSize value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '20px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconSize: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an iconColor value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '#fff" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconColor: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an iconBgColor value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '#374151" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], iconShape: 'circle', iconBgColor: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a gap value with an attribute-breakout string cannot escape the wrapper style=""', () => {
|
||||||
|
const malicious = '10px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ links: [{ platform: 'facebook', url: '#' }], gap: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious platform key does not produce a raw class-attribute breakout', () => {
|
||||||
|
const malicious = 'x"><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ links: [{ platform: malicious, url: '#' }] }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a link url with a javascript: scheme is neutralized', () => {
|
||||||
|
const { html } = toHtml({ links: [{ platform: 'facebook', url: 'javascript:alert(1)' }] }, '');
|
||||||
|
expect(html).not.toContain('javascript:alert(1)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Spacer } from './Spacer';
|
||||||
|
|
||||||
|
const toHtml = (Spacer as any).toHtml;
|
||||||
|
|
||||||
|
describe('Spacer.toHtml normal rendering', () => {
|
||||||
|
test('renders height into the style attribute', () => {
|
||||||
|
const { html } = toHtml({ height: '80px' }, '');
|
||||||
|
expect(html).toContain('height:80px');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Spacer.toHtml XSS hardening (height into style=)', () => {
|
||||||
|
test('a height value with an attribute-breakout string cannot escape style=""', () => {
|
||||||
|
const malicious = '40px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ height: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/"\s+onmouseover="/);
|
||||||
|
expect(html).not.toMatch(/style="[^"]*"[^>]*onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a height value with a </style><script> breakout is neutralized', () => {
|
||||||
|
const malicious = '40px</style><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ height: malicious as any }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -40,3 +40,38 @@ describe('StarRating.toHtml XSS hardening (filledColor/emptyColor/size into styl
|
|||||||
expect(html).toContain('color:#ff9900');
|
expect(html).toContain('color:#ff9900');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('StarRating.toHtml XSS hardening (rating/maxStars into aria-label, F2.2 CONFIRMED sink)', () => {
|
||||||
|
test('a maxStars value with an attribute-breakout string is neutralized in aria-label', () => {
|
||||||
|
const malicious = '5" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ rating: 3, maxStars: malicious as any }, '');
|
||||||
|
expect(html).not.toMatch(/onmouseover/);
|
||||||
|
expect(html).not.toMatch(/aria-label="Rating: 3 out of 5" onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a rating value with an attribute-breakout string is neutralized in aria-label', () => {
|
||||||
|
const malicious = '4.5" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ rating: malicious as any, maxStars: 5 }, '');
|
||||||
|
expect(html).not.toMatch(/onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-numeric maxStars does not blow up the star loop (no NaN glyph count, no huge output)', () => {
|
||||||
|
const malicious = '5" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ rating: 3, maxStars: malicious as any }, '');
|
||||||
|
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||||
|
// Falls back to a sane default star count rather than looping 0 or NaN times.
|
||||||
|
expect(glyphs.length).toBeGreaterThan(0);
|
||||||
|
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an absurdly large maxStars is clamped to a sane maximum instead of looping unboundedly', () => {
|
||||||
|
const { html } = toHtml({ rating: 3, maxStars: 1e9 as any }, '');
|
||||||
|
const glyphs = html.match(/<i class="fa fa-star"/g) || [];
|
||||||
|
expect(glyphs.length).toBeLessThanOrEqual(50);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal numeric rating/maxStars still render the expected aria-label', () => {
|
||||||
|
const { html } = toHtml({ rating: 4.5, maxStars: 5 }, '');
|
||||||
|
expect(html).toMatch(/<span role="img" aria-label="Rating: 4\.5 out of 5"/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { cssValue } from '../../utils/escape';
|
import { cssValue, escapeAttr } from '../../utils/escape';
|
||||||
|
|
||||||
interface StarRatingProps {
|
interface StarRatingProps {
|
||||||
rating?: number;
|
rating?: number;
|
||||||
@@ -98,8 +98,19 @@ StarRating.craft = {
|
|||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(StarRating as any).toHtml = (props: StarRatingProps, _childrenHtml: string) => {
|
(StarRating as any).toHtml = (props: StarRatingProps, _childrenHtml: string) => {
|
||||||
const rating = props.rating ?? 4.5;
|
// `rating`/`maxStars` are declared `number` in TS but arrive unchecked at
|
||||||
const maxStars = props.maxStars || 5;
|
// runtime (AI update_props only validates node_id; deserialized saved
|
||||||
|
// state is untyped JSON) -- a string like `5" onmouseover="alert(1)`
|
||||||
|
// breaks out of the aria-label attribute below, and an uncoerced/unclamped
|
||||||
|
// maxStars can also blow up the star-glyph loop (NaN, absurd loop count,
|
||||||
|
// or -- observed -- a RangeError from string concatenation overflow with
|
||||||
|
// e.g. maxStars=1e9). Coerce to numbers with sane fallbacks/clamps first.
|
||||||
|
const ratingRaw = Number(props.rating);
|
||||||
|
const rating = Number.isFinite(ratingRaw) ? ratingRaw : 4.5;
|
||||||
|
const maxStarsRaw = Number(props.maxStars);
|
||||||
|
const maxStars = Number.isFinite(maxStarsRaw)
|
||||||
|
? Math.min(Math.max(Math.trunc(maxStarsRaw), 0), 50)
|
||||||
|
: 5;
|
||||||
// Sanitized -- raw string-interpolation sinks in the star glyphs below.
|
// Sanitized -- raw string-interpolation sinks in the star glyphs below.
|
||||||
const size = cssValue(props.size) || '24px';
|
const size = cssValue(props.size) || '24px';
|
||||||
const filledColor = cssValue(props.filledColor) || '#f59e0b';
|
const filledColor = cssValue(props.filledColor) || '#f59e0b';
|
||||||
@@ -125,7 +136,12 @@ StarRating.craft = {
|
|||||||
// The star glyphs convey nothing to assistive tech on their own -- wrap
|
// The star glyphs convey nothing to assistive tech on their own -- wrap
|
||||||
// in role="img" with a textual equivalent, and hide the decorative glyphs
|
// in role="img" with a textual equivalent, and hide the decorative glyphs
|
||||||
// themselves (aria-hidden above) so AT doesn't announce each icon.
|
// themselves (aria-hidden above) so AT doesn't announce each icon.
|
||||||
|
// Belt-and-suspenders: rating/maxStars are already coerced to numbers
|
||||||
|
// above, but the assembled label is still run through escapeAttr() in
|
||||||
|
// case a decimal/negative/Infinity edge case produces odd (though no
|
||||||
|
// longer dangerous) text.
|
||||||
|
const ariaLabel = escapeAttr(`Rating: ${rating} out of ${maxStars}`);
|
||||||
return {
|
return {
|
||||||
html: `<span role="img" aria-label="Rating: ${rating} out of ${maxStars}"${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>${starsHtml}</span>`,
|
html: `<span role="img" aria-label="${ariaLabel}"${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>${starsHtml}</span>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { TextBlock } from './TextBlock';
|
||||||
|
|
||||||
|
const toHtml = (TextBlock as any).toHtml;
|
||||||
|
|
||||||
|
describe('TextBlock.toHtml text escaping (attacker-controlled `text` prop)', () => {
|
||||||
|
test('a tag-breakout attempt in text is neutralized (no injected element)', () => {
|
||||||
|
const { html } = toHtml({ text: '</p><img src=x onerror=alert(1)>' }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).toContain('<img');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ampersand is escaped for well-formed text content (consistency with escapeHtml)', () => {
|
||||||
|
const { html } = toHtml({ text: 'Tom & Jerry' }, '');
|
||||||
|
expect(html).toContain('Tom & Jerry');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal text value still renders unchanged', () => {
|
||||||
|
const { html } = toHtml({ text: 'Hello world' }, '');
|
||||||
|
expect(html).toBe('<p>Hello world</p>');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
|
import { escapeHtml } from '../../utils/escape';
|
||||||
|
|
||||||
interface TextBlockProps {
|
interface TextBlockProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
@@ -95,6 +96,6 @@ TextBlock.craft = {
|
|||||||
|
|
||||||
(TextBlock as any).toHtml = (props: TextBlockProps, _childrenHtml: string) => {
|
(TextBlock as any).toHtml = (props: TextBlockProps, _childrenHtml: string) => {
|
||||||
const styleStr = cssPropsToString(props.style);
|
const styleStr = cssPropsToString(props.style);
|
||||||
const escapedText = (props.text || '').replace(/</g, '<').replace(/>/g, '>');
|
const escapedText = escapeHtml(props.text || '');
|
||||||
return { html: `<p${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</p>` };
|
return { html: `<p${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</p>` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -110,3 +110,19 @@ describe('ContactForm.toHtml accessibility (F2.1)', () => {
|
|||||||
expect(ids1).toEqual(ids2);
|
expect(ids1).toEqual(ids2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ContactForm.toHtml field type attribute sanitization', () => {
|
||||||
|
test('malicious field.type cannot break out of the input attribute; falls back to type="text"', () => {
|
||||||
|
const fields = [{ type: 'text"><img src=x onerror=alert(1)>' as any, label: 'Name', name: 'name', placeholder: 'Your name', required: false }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).not.toContain('onerror=');
|
||||||
|
expect(html).toContain('type="text"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate email field type still passes through unchanged', () => {
|
||||||
|
const fields = [{ type: 'email' as const, label: 'Email', name: 'email', placeholder: 'you@example.com', required: false }];
|
||||||
|
const { html } = toHtml({ fields }, '');
|
||||||
|
expect(html).toContain('type="email"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||||
import { escapeHtml, escapeAttr, slugId, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, slugId, cssValue, sanitizeInputType } from '../../utils/escape';
|
||||||
|
|
||||||
interface ContactFormField {
|
interface ContactFormField {
|
||||||
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
|
type: 'text' | 'email' | 'tel' | 'textarea' | 'select';
|
||||||
@@ -196,7 +196,7 @@ ContactForm.craft = {
|
|||||||
const opts = (field.options || []).map((o) => `<option value="${escapeAttr(o)}">${escapeHtml(o)}</option>`).join('');
|
const opts = (field.options || []).map((o) => `<option value="${escapeAttr(o)}">${escapeHtml(o)}</option>`).join('');
|
||||||
inputHtml = `<select id="${escapeAttr(fieldId)}" name="${escapeAttr(field.name)}" style="${inputStyleStr};cursor:pointer"${reqAttr}><option value="">${escapeHtml(field.placeholder || 'Select...')}</option>${opts}</select>`;
|
inputHtml = `<select id="${escapeAttr(fieldId)}" name="${escapeAttr(field.name)}" style="${inputStyleStr};cursor:pointer"${reqAttr}><option value="">${escapeHtml(field.placeholder || 'Select...')}</option>${opts}</select>`;
|
||||||
} else {
|
} else {
|
||||||
inputHtml = `<input id="${escapeAttr(fieldId)}" type="${field.type}" name="${escapeAttr(field.name)}" placeholder="${escapeAttr(field.placeholder)}" style="${inputStyleStr}"${reqAttr} />`;
|
inputHtml = `<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(field.type)}" name="${escapeAttr(field.name)}" placeholder="${escapeAttr(field.placeholder)}" style="${inputStyleStr}"${reqAttr} />`;
|
||||||
}
|
}
|
||||||
return `<div style="display:flex;flex-direction:column;gap:6px">${labelHtml}${inputHtml}</div>`;
|
return `<div style="display:flex;flex-direction:column;gap:6px">${labelHtml}${inputHtml}</div>`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { FormButton } from './FormButton';
|
||||||
|
|
||||||
|
const toHtml = (FormButton as any).toHtml;
|
||||||
|
|
||||||
|
describe('FormButton.toHtml', () => {
|
||||||
|
test('normal text renders as-is', () => {
|
||||||
|
const { html } = toHtml({ text: 'Send it' }, '');
|
||||||
|
expect(html).toContain('>Send it<');
|
||||||
|
expect(html).toContain('type="submit"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('type="submit" is a hardcoded literal, not prop-driven', () => {
|
||||||
|
const { html } = toHtml({ text: 'Submit' }, '');
|
||||||
|
expect(html).toMatch(/<button type="submit"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('text content is escaped for <, >, &, and " (consistent with escapeHtml)', () => {
|
||||||
|
const { html } = toHtml({ text: '<script>alert(1)</script> & "quoted"' }, '');
|
||||||
|
expect(html).not.toContain('<script>');
|
||||||
|
expect(html).toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).toContain('&');
|
||||||
|
expect(html).toContain('"quoted"');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
|
import { escapeHtml } from '../../utils/escape';
|
||||||
|
|
||||||
interface FormButtonProps {
|
interface FormButtonProps {
|
||||||
text?: string;
|
text?: string;
|
||||||
@@ -74,7 +75,7 @@ FormButton.craft = {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
...props.style,
|
...props.style,
|
||||||
});
|
});
|
||||||
const escapedText = (props.text || 'Submit').replace(/</g, '<').replace(/>/g, '>');
|
const escapedText = escapeHtml(props.text || 'Submit');
|
||||||
return {
|
return {
|
||||||
html: `<button type="submit"${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</button>`,
|
html: `<button type="submit"${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</button>`,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -39,3 +39,16 @@ describe('FormContainer.toHtml relay wiring', () => {
|
|||||||
expect(mid1).not.toBe(mid2);
|
expect(mid1).not.toBe(mid2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('FormContainer.toHtml method attribute sanitization', () => {
|
||||||
|
test('malicious method value cannot break out of the attribute; falls back to POST', () => {
|
||||||
|
const { html } = toHtml({ action: '/legacy', method: 'POST"><script>alert(1)</script>' }, '');
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
expect(html).toContain('method="POST"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate GET method still passes through unchanged (non-relay path)', () => {
|
||||||
|
const { html } = toHtml({ action: '/legacy', method: 'GET' }, '');
|
||||||
|
expect(html).toContain('method="GET"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useNode, Element, UserComponent } from '@craftjs/core';
|
|||||||
import { Container } from '../layout/Container';
|
import { Container } from '../layout/Container';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
import { relayFormWiring } from '../../utils/form-relay-wiring';
|
||||||
|
import { sanitizeFormMethod } from '../../utils/escape';
|
||||||
|
|
||||||
interface FormContainerProps {
|
interface FormContainerProps {
|
||||||
action?: string;
|
action?: string;
|
||||||
@@ -74,7 +75,7 @@ FormContainer.craft = {
|
|||||||
...props.style,
|
...props.style,
|
||||||
});
|
});
|
||||||
const { useRelay, marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, props.action, nodeId);
|
const { useRelay, marker, actionAttr, honeypot } = relayFormWiring(props.recipientEmail, props.thankYouUrl, props.action, nodeId);
|
||||||
const method = useRelay ? 'POST' : (props.method || 'POST'); // relay requires POST
|
const method = useRelay ? 'POST' : sanitizeFormMethod(props.method); // relay requires POST
|
||||||
const body = honeypot + childrenHtml; // honeypot as first child
|
const body = honeypot + childrenHtml; // honeypot as first child
|
||||||
return {
|
return {
|
||||||
html: `${marker}<form action="${actionAttr}" method="${method}"${styleStr ? ` style="${styleStr}"` : ''}>${body}</form>`,
|
html: `${marker}<form action="${actionAttr}" method="${method}"${styleStr ? ` style="${styleStr}"` : ''}>${body}</form>`,
|
||||||
|
|||||||
@@ -58,3 +58,17 @@ describe('InputField.toHtml deterministic + unique ids (thread node id, resolves
|
|||||||
expect(id1).toBe(id2);
|
expect(id1).toBe(id2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('InputField.toHtml type attribute sanitization', () => {
|
||||||
|
test('malicious type value cannot break out of the attribute; falls back to type="text"', () => {
|
||||||
|
const { html } = toHtml({ label: 'Name', name: 'name', type: 'text" autofocus onfocus="alert(1)' as any }, '');
|
||||||
|
expect(html).not.toContain('onfocus=');
|
||||||
|
expect(html).not.toContain('autofocus');
|
||||||
|
expect(html).toContain('type="text"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate number type still passes through unchanged', () => {
|
||||||
|
const { html } = toHtml({ label: 'Age', name: 'age', type: 'number' as const }, '');
|
||||||
|
expect(html).toContain('type="number"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, scopeId } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, scopeId, sanitizeInputType } from '../../utils/escape';
|
||||||
|
|
||||||
interface InputFieldProps {
|
interface InputFieldProps {
|
||||||
label?: string;
|
label?: string;
|
||||||
@@ -111,7 +111,7 @@ InputField.craft = {
|
|||||||
return {
|
return {
|
||||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||||
${labelHtml}
|
${labelHtml}
|
||||||
<input id="${escapeAttr(fieldId)}" type="${props.type || 'text'}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
|
<input id="${escapeAttr(fieldId)}" type="${sanitizeInputType(props.type)}" name="${escapeAttr(props.name || 'field')}" placeholder="${escapeAttr(props.placeholder || '')}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box" />
|
||||||
</div>`,
|
</div>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { SubscribeForm } from './SubscribeForm';
|
||||||
|
|
||||||
|
const toHtml = (SubscribeForm as any).toHtml;
|
||||||
|
|
||||||
|
describe('SubscribeForm.toHtml hardcoded attributes stay hardcoded (no raw prop breakout)', () => {
|
||||||
|
test('form method is always POST regardless of any injected props', () => {
|
||||||
|
const { html } = toHtml({ heading: 'Join us', method: 'GET"><script>alert(1)</script>' } as any, '');
|
||||||
|
expect(html).toContain('<form method="POST"');
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('email input type is always "email" regardless of any injected props', () => {
|
||||||
|
const { html } = toHtml({ type: 'text"><img src=x onerror=alert(1)>' } as any, '');
|
||||||
|
expect(html).toContain('<input type="email"');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).not.toContain('onerror=');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('layout enum only ever feeds one of two fixed literal style strings, never raw', () => {
|
||||||
|
const { html: inlineHtml } = toHtml({ layout: 'inline' }, '');
|
||||||
|
const { html: stackedHtml } = toHtml({ layout: 'stacked' }, '');
|
||||||
|
expect(inlineHtml).toContain('flex-direction:row');
|
||||||
|
expect(stackedHtml).toContain('flex-direction:column');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('malicious layout value cannot inject raw CSS/attribute breakout (falls through the isInline boolean check to the stacked literal)', () => {
|
||||||
|
const { html } = toHtml({ layout: '"><script>alert(1)</script>' as any }, '');
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
expect(html).toContain('flex-direction:column');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal render still produces expected structure', () => {
|
||||||
|
const { html } = toHtml({ heading: 'Subscribe', placeholder: 'you@example.com', buttonText: 'Go' }, '');
|
||||||
|
expect(html).toContain('Subscribe');
|
||||||
|
expect(html).toContain('placeholder="you@example.com"');
|
||||||
|
expect(html).toContain('>Go<');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -50,3 +50,16 @@ describe('TextareaField.toHtml deterministic + unique ids (thread node id, resol
|
|||||||
expect(id1).toBe(id2);
|
expect(id1).toBe(id2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('TextareaField.toHtml rows attribute sanitization', () => {
|
||||||
|
test('malicious rows value cannot break out of the attribute; falls back to a numeric rows', () => {
|
||||||
|
const { html } = toHtml({ label: 'Message', name: 'message', rows: '4"><script>alert(1)</script>' as any }, '');
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
expect(html).toMatch(/rows="\d+"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legitimate numeric rows still passes through unchanged', () => {
|
||||||
|
const { html } = toHtml({ label: 'Message', name: 'message', rows: 8 }, '');
|
||||||
|
expect(html).toContain('rows="8"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -97,6 +97,11 @@ TextareaField.craft = {
|
|||||||
...props.style,
|
...props.style,
|
||||||
});
|
});
|
||||||
const reqAttr = props.required ? ' required' : '';
|
const reqAttr = props.required ? ' required' : '';
|
||||||
|
// `rows` is declared as a TS `number` but arrives unchecked (AI update_props
|
||||||
|
// path only validates node_id; deserialized saved-state JSON is untyped at
|
||||||
|
// runtime), so a string like `4"><script>...` must be coerced to a real
|
||||||
|
// number before interpolation, not trusted as already-numeric.
|
||||||
|
const rows = Number(props.rows) || 4;
|
||||||
// Deterministic AND unique id: scoped on the Craft node id so the
|
// Deterministic AND unique id: scoped on the Craft node id so the
|
||||||
// <label for> always matches the <textarea id> AND two TextareaField
|
// <label for> always matches the <textarea id> AND two TextareaField
|
||||||
// instances that share the same (often default) `name` -- e.g. two
|
// instances that share the same (often default) `name` -- e.g. two
|
||||||
@@ -113,7 +118,7 @@ TextareaField.craft = {
|
|||||||
return {
|
return {
|
||||||
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
html: `<div${wrapStyle ? ` style="${wrapStyle}"` : ''}>
|
||||||
${labelHtml}
|
${labelHtml}
|
||||||
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${props.rows || 4}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
<textarea id="${escapeAttr(fieldId)}" name="${escapeAttr(props.name || 'message')}" placeholder="${escapeAttr(props.placeholder || '')}" rows="${escapeAttr(String(rows))}"${reqAttr}${ariaLabelAttr} style="padding:10px 12px;border:1px solid #d4d4d8;border-radius:6px;font-size:14px;color:#18181b;background-color:#ffffff;width:100%;box-sizing:border-box;resize:vertical;font-family:inherit"></textarea>
|
||||||
</div>`,
|
</div>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { BackgroundSection } from './BackgroundSection';
|
||||||
|
|
||||||
|
const toHtml = (BackgroundSection as any).toHtml;
|
||||||
|
|
||||||
|
describe('BackgroundSection.toHtml anchorId', () => {
|
||||||
|
test('escapes a malicious anchorId (attribute breakout attempt)', () => {
|
||||||
|
const { html } = toHtml({ anchorId: 'x" onmouseover="alert(1)' }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal anchorId still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ anchorId: 'my-bg-section' }, 'child');
|
||||||
|
expect(html).toContain('id="my-bg-section"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('BackgroundSection.toHtml style-value XSS hardening', () => {
|
||||||
|
test('a malicious bgImage cannot break out of the outer style attribute via url(...)', () => {
|
||||||
|
const malicious = 'javascript:alert(1)) foo{background:red}</style><script>alert(1)</script';
|
||||||
|
const { html } = toHtml({ bgImage: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('javascript:alert(1)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious bgColor cannot break out of the outer style attribute', () => {
|
||||||
|
const malicious = 'red" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ bgColor: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious overlayColor cannot break out of the overlay style attribute', () => {
|
||||||
|
const malicious = 'red" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ overlayColor: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a wrong-typed overlayOpacity (string, not number) cannot break out of the overlay style attribute', () => {
|
||||||
|
const malicious = '0.4" onmouseover="alert(1)' as any;
|
||||||
|
const { html } = toHtml({ overlayOpacity: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious innerMaxWidth cannot break out of the inner style attribute', () => {
|
||||||
|
const malicious = '1200px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ innerMaxWidth: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal props still render correctly', () => {
|
||||||
|
const { html } = toHtml({ bgImage: 'https://example.com/bg.jpg', bgColor: '#1e293b', overlayColor: '#000000', overlayOpacity: 0.4, innerMaxWidth: '1200px' }, 'child');
|
||||||
|
expect(html).toContain("url('https://example.com/bg.jpg')");
|
||||||
|
expect(html).toContain('background-color:#1e293b');
|
||||||
|
expect(html).toContain('opacity:0.4');
|
||||||
|
expect(html).toContain('max-width:1200px');
|
||||||
|
expect(html).toContain('child');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -33,3 +33,33 @@ describe('Container.toHtml cssId/cssClass', () => {
|
|||||||
expect(html).toContain('id="anchor-id"');
|
expect(html).toContain('id="anchor-id"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Container.toHtml tag allowlist (adversarial re-review, same class as C1)', () => {
|
||||||
|
test('a malicious tag value falls back to div -- no injected <img>, no broken-out attrs', () => {
|
||||||
|
const { html } = toHtml({ tag: 'div><img src=x onerror=alert(1)' }, 'child');
|
||||||
|
expect(html).not.toContain('<img');
|
||||||
|
expect(html).not.toContain('onerror');
|
||||||
|
expect(html.startsWith('<div')).toBe(true);
|
||||||
|
expect(html.endsWith('</div>')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a tag value outside the known-safe set falls back to div', () => {
|
||||||
|
const { html } = toHtml({ tag: 'script' }, 'child');
|
||||||
|
expect(html.startsWith('<div')).toBe(true);
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a valid tag (section) still emits <section', () => {
|
||||||
|
const { html } = toHtml({ tag: 'section' }, 'child');
|
||||||
|
expect(html).toContain('<section');
|
||||||
|
expect(html).toContain('</section>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('all other allowlisted tags still work', () => {
|
||||||
|
for (const tag of ['div', 'article', 'header', 'footer', 'main']) {
|
||||||
|
const { html } = toHtml({ tag }, 'child');
|
||||||
|
expect(html.startsWith(`<${tag}`)).toBe(true);
|
||||||
|
expect(html.endsWith(`</${tag}>`)).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -3,6 +3,19 @@ import { useNode, UserComponent } from '@craftjs/core';
|
|||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeAttr } from '../../utils/escape';
|
import { escapeAttr } from '../../utils/escape';
|
||||||
|
|
||||||
|
// The only tag names Container actually supports (matches the TS union
|
||||||
|
// below and the `tag` default in `.craft.props`). `tag` is settable via the
|
||||||
|
// AI `update_props` path and from deserialized saved state -- neither is
|
||||||
|
// type-checked at runtime -- so a malicious value like
|
||||||
|
// `div><img src=x onerror=alert(1)` must never reach the `<${tag}` template
|
||||||
|
// position in `toHtml`/the live render. Anything not in this allowlist
|
||||||
|
// falls back to `'div'`.
|
||||||
|
const ALLOWED_CONTAINER_TAGS = ['div', 'section', 'article', 'header', 'footer', 'main'] as const;
|
||||||
|
export type ContainerTag = (typeof ALLOWED_CONTAINER_TAGS)[number];
|
||||||
|
|
||||||
|
export const sanitizeContainerTag = (tag: unknown): ContainerTag =>
|
||||||
|
(ALLOWED_CONTAINER_TAGS as readonly unknown[]).includes(tag) ? (tag as ContainerTag) : 'div';
|
||||||
|
|
||||||
interface ContainerProps {
|
interface ContainerProps {
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
tag?: 'div' | 'section' | 'article' | 'header' | 'footer' | 'main';
|
tag?: 'div' | 'section' | 'article' | 'header' | 'footer' | 'main';
|
||||||
@@ -42,6 +55,7 @@ export const Container: UserComponent<ContainerProps> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const { connectors: { connect, drag } } = useNode();
|
const { connectors: { connect, drag } } = useNode();
|
||||||
|
|
||||||
|
const safeTag = sanitizeContainerTag(tag);
|
||||||
const needsBoxedWrapper = contentWidth === 'boxed';
|
const needsBoxedWrapper = contentWidth === 'boxed';
|
||||||
const flexStyles = flexAlignFromTextAlign(style.textAlign);
|
const flexStyles = flexAlignFromTextAlign(style.textAlign);
|
||||||
|
|
||||||
@@ -58,7 +72,7 @@ export const Container: UserComponent<ContainerProps> = ({
|
|||||||
const idValue = cssId || anchorId || undefined;
|
const idValue = cssId || anchorId || undefined;
|
||||||
|
|
||||||
const el = React.createElement(
|
const el = React.createElement(
|
||||||
tag,
|
safeTag,
|
||||||
{
|
{
|
||||||
ref: (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); },
|
ref: (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); },
|
||||||
style: outerStyle,
|
style: outerStyle,
|
||||||
@@ -97,7 +111,7 @@ Container.craft = {
|
|||||||
/* ---------- HTML export ---------- */
|
/* ---------- HTML export ---------- */
|
||||||
|
|
||||||
(Container as any).toHtml = (props: ContainerProps, childrenHtml: string) => {
|
(Container as any).toHtml = (props: ContainerProps, childrenHtml: string) => {
|
||||||
const tag = props.tag || 'div';
|
const tag = sanitizeContainerTag(props.tag);
|
||||||
const isBoxed = props.contentWidth === 'boxed';
|
const isBoxed = props.contentWidth === 'boxed';
|
||||||
const flexStyles = flexAlignFromTextAlign(props.style?.textAlign);
|
const flexStyles = flexAlignFromTextAlign(props.style?.textAlign);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { Section } from './Section';
|
||||||
|
|
||||||
|
const toHtml = (Section as any).toHtml;
|
||||||
|
|
||||||
|
describe('Section.toHtml anchorId', () => {
|
||||||
|
test('escapes a malicious anchorId (attribute breakout attempt)', () => {
|
||||||
|
const { html } = toHtml({ anchorId: 'x" onmouseover="alert(1)' }, 'child');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal anchorId still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ anchorId: 'my-section' }, 'child');
|
||||||
|
expect(html).toContain('id="my-section"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Section.toHtml childrenHtml passthrough', () => {
|
||||||
|
test('children are preserved', () => {
|
||||||
|
const { html } = toHtml({}, '<p>hello</p>');
|
||||||
|
expect(html).toContain('<p>hello</p>');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Section.toHtml shape divider color/height XSS hardening', () => {
|
||||||
|
test('a malicious topDividerColor cannot break out of the SVG style attribute', () => {
|
||||||
|
const malicious = 'red" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ topDivider: 'wave', topDividerColor: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious topDividerColor cannot inject a </style><script> breakout', () => {
|
||||||
|
const malicious = 'red</style><script>alert(1)</script>';
|
||||||
|
const { html } = toHtml({ topDivider: 'wave', topDividerColor: malicious }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious bottomDividerHeight cannot break out of the wrapper style attribute', () => {
|
||||||
|
const malicious = '50px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ bottomDivider: 'angle', bottomDividerHeight: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal divider color/height still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ topDivider: 'wave', topDividerColor: '#123456', topDividerHeight: '80px' }, '');
|
||||||
|
expect(html).toContain('fill:#123456');
|
||||||
|
expect(html).toContain('height:80px');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('divider shape "none" emits no divider markup', () => {
|
||||||
|
const { html } = toHtml({ topDivider: 'none' }, 'child');
|
||||||
|
expect(html).not.toContain('<svg');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an unrecognized divider shape value emits no divider markup and no injected content', () => {
|
||||||
|
const malicious = 'wave"><script>alert(1)</script>' as any;
|
||||||
|
const { html } = toHtml({ topDivider: malicious }, 'child');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('<svg');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a prototype-property-name divider shape (__proto__) does not leak [object Object]/function source into the SVG path', () => {
|
||||||
|
const { html } = toHtml({ topDivider: '__proto__' as any }, 'child');
|
||||||
|
expect(html).not.toContain('[object');
|
||||||
|
expect(html).not.toContain('native code');
|
||||||
|
expect(html).not.toContain('<svg');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a prototype-property-name divider shape (toString) does not leak Object.prototype.toString source into the SVG path', () => {
|
||||||
|
const { html } = toHtml({ topDivider: 'toString' as any }, 'child');
|
||||||
|
expect(html).not.toContain('[object');
|
||||||
|
expect(html).not.toContain('native code');
|
||||||
|
expect(html).not.toContain('<svg');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -38,7 +38,14 @@ const ShapeDivider: React.FC<{
|
|||||||
position: 'top' | 'bottom';
|
position: 'top' | 'bottom';
|
||||||
}> = ({ shape, color, height, position }) => {
|
}> = ({ shape, color, height, position }) => {
|
||||||
if (!shape || shape === 'none') return null;
|
if (!shape || shape === 'none') return null;
|
||||||
const path = DIVIDER_PATHS[shape];
|
// `shape` is attacker-controlled (AI update_props / deserialized state) and
|
||||||
|
// not runtime-type-checked. A plain-object index lookup with a string key
|
||||||
|
// like '__proto__', 'toString', or 'constructor' returns an INHERITED
|
||||||
|
// Object.prototype value (not undefined), which would otherwise leak
|
||||||
|
// "[object Object]" / a function's source text into the SVG `d` attribute
|
||||||
|
// below. hasOwnProperty restricts the lookup to the real allowlisted keys.
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(DIVIDER_PATHS, shape)) return null;
|
||||||
|
const path = DIVIDER_PATHS[shape as Exclude<DividerShape, 'none'>];
|
||||||
if (!path) return null;
|
if (!path) return null;
|
||||||
|
|
||||||
const isTop = position === 'top';
|
const isTop = position === 'top';
|
||||||
@@ -162,7 +169,10 @@ function buildDividerHtml(
|
|||||||
position: 'top' | 'bottom',
|
position: 'top' | 'bottom',
|
||||||
): string {
|
): string {
|
||||||
if (!shape || shape === 'none') return '';
|
if (!shape || shape === 'none') return '';
|
||||||
const path = DIVIDER_PATHS[shape];
|
// See the matching hasOwnProperty guard in <ShapeDivider> above -- same
|
||||||
|
// prototype-pollution-shaped lookup, same fix.
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(DIVIDER_PATHS, shape)) return '';
|
||||||
|
const path = DIVIDER_PATHS[shape as Exclude<DividerShape, 'none'>];
|
||||||
if (!path) return '';
|
if (!path) return '';
|
||||||
|
|
||||||
const isTop = position === 'top';
|
const isTop = position === 'top';
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* ImageBlock only needs useNode from @craftjs/core. Mock it following the
|
||||||
|
DOM-harness pattern in src/components/basic/Footer.editguard.test.tsx (no
|
||||||
|
@testing-library/react in this repo) so we can render the real component
|
||||||
|
tree and inspect the emitted <img src> without a real <Editor>. */
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useNode: (collect?: (node: any) => any) => {
|
||||||
|
const node = { events: { selected: false } };
|
||||||
|
return {
|
||||||
|
connectors: { connect: (el: any) => el, drag: (el: any) => el },
|
||||||
|
actions: { setProp: vi.fn() },
|
||||||
|
...(collect ? collect(node) : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { ImageBlock } from './ImageBlock';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock render falls back to the placeholder for an explicit empty src (Bug 1)', () => {
|
||||||
|
test('src="" (explicit, overrides the default parameter) still renders a non-empty placeholder src', () => {
|
||||||
|
render(<ImageBlock src="" alt="Image" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).not.toBe('');
|
||||||
|
expect(img.getAttribute('src')).toMatch(/^data:image\/svg\+xml/);
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('src=undefined (default parameter path) still renders the placeholder (unchanged behavior)', () => {
|
||||||
|
render(<ImageBlock alt="Image" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).not.toBe('');
|
||||||
|
expect(img.getAttribute('src')).toMatch(/^data:image\/svg\+xml/);
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a real src is rendered unchanged', () => {
|
||||||
|
render(<ImageBlock src="https://example.com/photo.jpg" alt="A photo" />);
|
||||||
|
const img = container.querySelector('img')!;
|
||||||
|
expect(img.getAttribute('src')).toBe('https://example.com/photo.jpg');
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { ImageBlock } from './ImageBlock';
|
||||||
|
|
||||||
|
const toHtml = (ImageBlock as any).toHtml;
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml src/alt XSS hardening', () => {
|
||||||
|
test('a javascript: src never reaches the output', () => {
|
||||||
|
const { html } = toHtml({ src: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious src cannot break out of the src attribute', () => {
|
||||||
|
const malicious = 'https://example.com/x.jpg" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ src: malicious }, '');
|
||||||
|
expect(html).not.toContain('onerror="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious alt cannot break out of the alt attribute', () => {
|
||||||
|
const malicious = 'x" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/x.jpg', alt: malicious }, '');
|
||||||
|
expect(html).not.toContain('onerror="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a placeholder/empty src emits no output', () => {
|
||||||
|
const { html } = toHtml({ src: '' }, '');
|
||||||
|
expect(html).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal image still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg', alt: 'A photo' }, '');
|
||||||
|
expect(html).toContain('src="https://example.com/photo.jpg"');
|
||||||
|
expect(html).toContain('alt="A photo"');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import React, { CSSProperties, useCallback, useRef } from 'react';
|
import React, { CSSProperties, useCallback, useRef } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeAttr, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
const PLACEHOLDER_SRC = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3Cdefs%3E%3ClinearGradient id='bg' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0%25' stop-color='%23f1f5f9'/%3E%3Cstop offset='100%25' stop-color='%23e2e8f0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23bg)' width='400' height='300' rx='12'/%3E%3Crect x='2' y='2' width='396' height='296' rx='10' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-dasharray='8 4'/%3E%3Cg transform='translate(200,110)'%3E%3Crect x='-28' y='-28' width='56' height='56' rx='12' fill='%23cbd5e1' opacity='0.5'/%3E%3Cpath d='M-12 8 L-4 -2 L2 4 L8 -6 L16 8Z' fill='%2394a3b8'/%3E%3Ccircle cx='-6' cy='-10' r='5' fill='%2394a3b8'/%3E%3C/g%3E%3Ctext x='200' y='160' text-anchor='middle' fill='%2364748b' font-family='Inter,sans-serif' font-size='15' font-weight='500'%3EDrop image here%3C/text%3E%3Ctext x='200' y='182' text-anchor='middle' fill='%2394a3b8' font-family='Inter,sans-serif' font-size='12'%3Eor click to upload%3C/text%3E%3C/svg%3E";
|
export const PLACEHOLDER_SRC = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3Cdefs%3E%3ClinearGradient id='bg' x1='0' y1='0' x2='0' y2='1'%3E%3Cstop offset='0%25' stop-color='%23f1f5f9'/%3E%3Cstop offset='100%25' stop-color='%23e2e8f0'/%3E%3C/linearGradient%3E%3C/defs%3E%3Crect fill='url(%23bg)' width='400' height='300' rx='12'/%3E%3Crect x='2' y='2' width='396' height='296' rx='10' fill='none' stroke='%23cbd5e1' stroke-width='2' stroke-dasharray='8 4'/%3E%3Cg transform='translate(200,110)'%3E%3Crect x='-28' y='-28' width='56' height='56' rx='12' fill='%23cbd5e1' opacity='0.5'/%3E%3Cpath d='M-12 8 L-4 -2 L2 4 L8 -6 L16 8Z' fill='%2394a3b8'/%3E%3Ccircle cx='-6' cy='-10' r='5' fill='%2394a3b8'/%3E%3C/g%3E%3Ctext x='200' y='160' text-anchor='middle' fill='%2364748b' font-family='Inter,sans-serif' font-size='15' font-weight='500'%3EDrop image here%3C/text%3E%3Ctext x='200' y='182' text-anchor='middle' fill='%2394a3b8' font-family='Inter,sans-serif' font-size='12'%3Eor click to upload%3C/text%3E%3C/svg%3E";
|
||||||
|
|
||||||
interface ImageBlockProps {
|
interface ImageBlockProps {
|
||||||
src?: string;
|
src?: string;
|
||||||
@@ -66,7 +66,7 @@ export const ImageBlock: UserComponent<ImageBlockProps> = ({
|
|||||||
imgRef.current = ref;
|
imgRef.current = ref;
|
||||||
if (ref) connect(drag(ref));
|
if (ref) connect(drag(ref));
|
||||||
}}
|
}}
|
||||||
src={src}
|
src={src || PLACEHOLDER_SRC}
|
||||||
alt={alt || 'Image'}
|
alt={alt || 'Image'}
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
@@ -95,5 +95,5 @@ ImageBlock.craft = {
|
|||||||
}
|
}
|
||||||
const s = cssPropsToString({ display: 'block', maxWidth: '100%', ...props.style });
|
const s = cssPropsToString({ display: 'block', maxWidth: '100%', ...props.style });
|
||||||
const alt = props.alt ? ` alt="${escapeAttr(props.alt)}"` : ' alt=""';
|
const alt = props.alt ? ` alt="${escapeAttr(props.alt)}"` : ' alt=""';
|
||||||
return { html: `<img src="${escapeAttr(safeUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
return { html: `<img src="${escapeAttr(safeImageUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -27,3 +27,41 @@ describe('MapEmbed.toHtml iframe src ampersand encoding (F-export review Minor)'
|
|||||||
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
||||||
|
test('a malicious address cannot break out of the src or title attribute', () => {
|
||||||
|
const malicious = 'X" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ address: malicious }, '');
|
||||||
|
expect(html).not.toContain('onerror="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a wrong-typed zoom (string with attribute-breakout chars) cannot break out of the src attribute', () => {
|
||||||
|
const malicious = '14"><script>alert(1)</script>' as any;
|
||||||
|
const { html } = toHtml({ address: 'X', zoom: malicious }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('"><script');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a wrong-typed zoom is coerced to a safe numeric value in the exported URL (defense in depth beyond escaping)', () => {
|
||||||
|
const malicious = '14"><script>alert(1)</script>' as any;
|
||||||
|
const { html } = toHtml({ address: 'X', zoom: malicious }, '');
|
||||||
|
const srcMatch = html.match(/<iframe src="([^"]+)"/);
|
||||||
|
expect(srcMatch).toBeTruthy();
|
||||||
|
// Decode the entity-escaped src back to a plain string and confirm the
|
||||||
|
// `z=` param is a bare, well-formed number -- not the raw attacker string.
|
||||||
|
const decoded = srcMatch![1].replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
expect(decoded).toMatch(/[&?]z=\d+(&|$)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious height cannot break out of the iframe style attribute', () => {
|
||||||
|
const malicious = '400px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ address: 'X', height: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal zoom/height still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ address: 'X', zoom: 10, height: '300px' }, '');
|
||||||
|
expect(html).toContain('z=10');
|
||||||
|
expect(html).toContain('height:300px');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -12,7 +12,15 @@ interface MapEmbedProps {
|
|||||||
|
|
||||||
function buildMapUrl(address: string, zoom: number): string {
|
function buildMapUrl(address: string, zoom: number): string {
|
||||||
const encoded = encodeURIComponent(address);
|
const encoded = encodeURIComponent(address);
|
||||||
return `https://maps.google.com/maps?q=${encoded}&z=${zoom}&output=embed`;
|
// `zoom` is declared as `number` but is not runtime-type-checked (AI
|
||||||
|
// update_props / deserialized state can hand us anything). The final src
|
||||||
|
// string is still run through escapeAttr(safeUrl(...)) at the toHtml call
|
||||||
|
// site, which already blocks attribute-breakout -- but Number-coercing
|
||||||
|
// here too keeps the emitted URL a well-formed `z=<digits>` query param
|
||||||
|
// instead of smuggling arbitrary attacker text into it.
|
||||||
|
const z = Number(zoom);
|
||||||
|
const safeZoom = Number.isFinite(z) ? z : 14;
|
||||||
|
return `https://maps.google.com/maps?q=${encoded}&z=${safeZoom}&output=embed`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MapEmbed: UserComponent<MapEmbedProps> = ({
|
export const MapEmbed: UserComponent<MapEmbedProps> = ({
|
||||||
|
|||||||
@@ -72,6 +72,38 @@ describe('VideoBlock.toHtml iframe accessibility (F2.4)', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.toHtml overlay/innerMaxWidth XSS hardening (background mode)', () => {
|
||||||
|
test('a malicious overlayColor cannot break out of the overlay style attribute', () => {
|
||||||
|
const malicious = 'red" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, overlayColor: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a wrong-typed overlayOpacity (string, not number) cannot break out of the overlay style attribute', () => {
|
||||||
|
const malicious = '50" onmouseover="alert(1)' as any;
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, overlayOpacity: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious innerMaxWidth cannot break out of the inner style attribute', () => {
|
||||||
|
const malicious = '1200px" onmouseover="alert(1)';
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', isBackground: true, innerMaxWidth: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious style.borderRadius cannot break out of the style attribute (normal mode, iframe wrapper)', () => {
|
||||||
|
const malicious = { borderRadius: '8px" onmouseover="alert(1)' } as any;
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', style: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious style.borderRadius cannot break out of the style attribute (direct file <video>)', () => {
|
||||||
|
const malicious = { borderRadius: '8px" onmouseover="alert(1)' } as any;
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', style: malicious }, '');
|
||||||
|
expect(html).not.toContain('onmouseover="alert(1)"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('VideoBlock.toHtml iframe src ampersand encoding (F-export review Minor)', () => {
|
describe('VideoBlock.toHtml iframe src ampersand encoding (F-export review Minor)', () => {
|
||||||
test('embed params joined with literal & are HTML-entity-encoded in the emitted src attribute', () => {
|
test('embed params joined with literal & are HTML-entity-encoded in the emitted src attribute', () => {
|
||||||
// autoplay+muted+controls=false forces buildEmbedParams to concatenate
|
// autoplay+muted+controls=false forces buildEmbedParams to concatenate
|
||||||
|
|||||||
@@ -91,3 +91,51 @@ describe('ContentSlider.toHtml autoplay silences aria-live and is pausable (F-ex
|
|||||||
expect(html).not.toMatch(/visibilitychange/);
|
expect(html).not.toMatch(/visibilitychange/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.toHtml renders slide.imageSrc as a background-image (INT)', () => {
|
||||||
|
test('a slide with imageSrc set exports a background-image referencing it', () => {
|
||||||
|
const slidesWithImage = [
|
||||||
|
{ type: 'image' as const, imageSrc: 'https://example.com/photo.jpg', heading: 'One' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ slides: slidesWithImage }, '');
|
||||||
|
expect(html).toContain("background-image:url('https://example.com/photo.jpg')");
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a slide with no imageSrc falls back to bgColor (no broken/empty background-image url)', () => {
|
||||||
|
const slidesNoImage = [
|
||||||
|
{ type: 'image' as const, imageSrc: '', heading: 'One', bgColor: '#123456' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ slides: slidesNoImage }, '');
|
||||||
|
expect(html).not.toContain('background-image:url(');
|
||||||
|
expect(html).toContain('background-color:#123456');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a slide with a data:image/svg+xml imageSrc exports a non-empty background-image url (safeImageUrl, not safeUrl)', () => {
|
||||||
|
const svgDataUri = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const slidesWithSvg = [
|
||||||
|
{ type: 'image' as const, imageSrc: svgDataUri, heading: 'One' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ slides: slidesWithSvg }, '');
|
||||||
|
expect(html).toContain(`background-image:url('${svgDataUri}')`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be coerced before it reaches the inline <script> numeric context', () => {
|
||||||
|
test('a malicious interval string cannot inject arbitrary JS into the autoplay setInterval call', () => {
|
||||||
|
const malicious = '5000);alert(document.domain);//';
|
||||||
|
const { html } = toHtml({ slides, autoplay: true, interval: malicious }, '');
|
||||||
|
expect(html).not.toContain('alert(document.domain)');
|
||||||
|
// the setInterval call must still be well-formed with a plain numeral delay
|
||||||
|
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},\d+\);/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-numeric interval falls back to a safe default delay', () => {
|
||||||
|
const { html } = toHtml({ slides, autoplay: true, interval: 'not-a-number' }, '');
|
||||||
|
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},5000\);/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a normal numeric interval still renders as the exact configured delay', () => {
|
||||||
|
const { html } = toHtml({ slides, autoplay: true, interval: 3000 }, '');
|
||||||
|
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
|
import React, { CSSProperties, useState, useEffect, useRef, useCallback } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl, scopeId, cssValue } from '../../utils/escape';
|
||||||
|
|
||||||
interface Slide {
|
interface Slide {
|
||||||
type: 'image' | 'content';
|
type: 'image' | 'content';
|
||||||
@@ -250,11 +250,24 @@ ContentSlider.craft = {
|
|||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
const items = slides.length > 0 ? slides : defaultSlides;
|
const items = slides.length > 0 ? slides : defaultSlides;
|
||||||
|
// Number() coercion: `interval` is declared `number` in TS but is NOT
|
||||||
|
// type-checked at runtime -- it arrives raw via the AI `update_props`
|
||||||
|
// path or a deserialized saved-state blob and is interpolated directly
|
||||||
|
// into the inline <script>'s `setInterval(fn, ${interval})` call below as
|
||||||
|
// a bare JS numeral (no quotes around it). A string like
|
||||||
|
// `5000);alert(1);//` would previously close the setInterval() call and
|
||||||
|
// splice arbitrary JS into the page's own <script> tag -- worse than an
|
||||||
|
// HTML attribute breakout, since it runs unconditionally on page load.
|
||||||
|
// Number() of anything non-numeric collapses safely to NaN, so we fall
|
||||||
|
// back to the 5000ms default rather than ever interpolating a
|
||||||
|
// non-numeral.
|
||||||
|
const intervalNum = Number(interval);
|
||||||
|
const safeInterval = Number.isFinite(intervalNum) && intervalNum > 0 ? intervalNum : 5000;
|
||||||
// Deterministic AND unique id, scoped on the Craft node id, for this
|
// Deterministic AND unique id, scoped on the Craft node id, for this
|
||||||
// slider's slide/dot element ids and inline-script globals -- so two
|
// slider's slide/dot element ids and inline-script globals -- so two
|
||||||
// ContentSlider instances (e.g. both left at default slides) don't
|
// ContentSlider instances (e.g. both left at default slides) don't
|
||||||
// collide and end up driving each other's rotation.
|
// collide and end up driving each other's rotation.
|
||||||
const uid = scopeId(nodeId, JSON.stringify(items) + interval, 'cs');
|
const uid = scopeId(nodeId, JSON.stringify(items) + safeInterval, 'cs');
|
||||||
|
|
||||||
const sectionStyle = cssPropsToString({
|
const sectionStyle = cssPropsToString({
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
@@ -270,7 +283,7 @@ ContentSlider.craft = {
|
|||||||
// sink (a malicious value could break out of the style="..." attribute).
|
// sink (a malicious value could break out of the style="..." attribute).
|
||||||
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
|
const safeBgColor = cssValue(slide.bgColor) || '#3b82f6';
|
||||||
const bgStyle = hasBgImage
|
const bgStyle = hasBgImage
|
||||||
? `background-image:url('${escapeAttr(safeUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
|
? `background-image:url('${escapeAttr(safeImageUrl(slide.imageSrc!))}');background-size:cover;background-position:center`
|
||||||
: slide.bgColor?.startsWith('linear-gradient')
|
: slide.bgColor?.startsWith('linear-gradient')
|
||||||
? `background-image:${safeBgColor}`
|
? `background-image:${safeBgColor}`
|
||||||
: `background-color:${safeBgColor}`;
|
: `background-color:${safeBgColor}`;
|
||||||
@@ -339,7 +352,7 @@ ContentSlider.craft = {
|
|||||||
window["${uid}_prev"]=function(){ markManualNav(); show(current-1); };
|
window["${uid}_prev"]=function(){ markManualNav(); show(current-1); };
|
||||||
${autoplayActive ? `
|
${autoplayActive ? `
|
||||||
var timer=null;
|
var timer=null;
|
||||||
function start(){ if(!timer && document.visibilityState!=="hidden"){ timer=setInterval(function(){show(current+1);},${interval}); } }
|
function start(){ if(!timer && document.visibilityState!=="hidden"){ timer=setInterval(function(){show(current+1);},${safeInterval}); } }
|
||||||
function stop(){ if(timer){ clearInterval(timer); timer=null; } }
|
function stop(){ if(timer){ clearInterval(timer); timer=null; } }
|
||||||
var root=document.getElementById(uid);
|
var root=document.getElementById(uid);
|
||||||
if(root){
|
if(root){
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { FeaturesGrid } from './FeaturesGrid';
|
||||||
|
|
||||||
|
const toHtml = (FeaturesGrid as any).toHtml;
|
||||||
|
|
||||||
|
describe('FeaturesGrid.toHtml image sink uses safeImageUrl (data:image/svg+xml allowed)', () => {
|
||||||
|
test('feat.image as a data:image/svg+xml value emits a non-empty <img src>', () => {
|
||||||
|
const svgDataUri = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const features = [
|
||||||
|
{ title: 'Feature', description: 'Desc', icon: '⚡', image: svgDataUri, imageAlt: 'alt' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ features }, '');
|
||||||
|
expect(html).toContain(`<img src="${svgDataUri}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('feat.buttonUrl stays on safeUrl (data:image/svg+xml blocked as a navigation target)', () => {
|
||||||
|
const features = [
|
||||||
|
{ title: 'Feature', description: 'Desc', icon: '⚡', buttonText: 'Go', buttonUrl: 'data:image/svg+xml,<svg onload=alert(1)>' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ features }, '');
|
||||||
|
expect(html).toMatch(/<a href=""/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
interface FeatureItem {
|
interface FeatureItem {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -116,7 +116,7 @@ FeaturesGrid.craft = {
|
|||||||
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
const idAttr = props.anchorId ? ` id="${escapeAttr(props.anchorId)}"` : '';
|
||||||
const cards = (props.features || defaultFeatures).map((feat) => {
|
const cards = (props.features || defaultFeatures).map((feat) => {
|
||||||
const media = feat.image
|
const media = feat.image
|
||||||
? `<img src="${escapeAttr(safeUrl(feat.image))}" alt="${escapeAttr(feat.imageAlt || feat.title || '')}" style="max-width:100%;height:auto;margin-bottom:16px;border-radius:8px">`
|
? `<img src="${escapeAttr(safeImageUrl(feat.image))}" alt="${escapeAttr(feat.imageAlt || feat.title || '')}" style="max-width:100%;height:auto;margin-bottom:16px;border-radius:8px">`
|
||||||
: `<div style="font-size:36px;margin-bottom:16px">${escapeHtml(feat.icon)}</div>`;
|
: `<div style="font-size:36px;margin-bottom:16px">${escapeHtml(feat.icon)}</div>`;
|
||||||
const button = feat.buttonText
|
const button = feat.buttonText
|
||||||
? `\n <a href="${escapeAttr(safeUrl(feat.buttonUrl || '#'))}" style="display:inline-block;margin-top:16px;padding:10px 24px;background:#3b82f6;color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600">${escapeHtml(feat.buttonText)}</a>`
|
? `\n <a href="${escapeAttr(safeUrl(feat.buttonUrl || '#'))}" style="display:inline-block;margin-top:16px;padding:10px 24px;background:#3b82f6;color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600">${escapeHtml(feat.buttonText)}</a>`
|
||||||
|
|||||||
@@ -93,3 +93,59 @@ describe('Gallery.toHtml deterministic + unique scope ids (thread node id, no Ma
|
|||||||
expect(html1).toBe(html2);
|
expect(html1).toBe(html2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml default SVG placeholder images survive export (Bug 2 regression)', () => {
|
||||||
|
test('a default data:image/svg+xml image emits a non-empty img src, not src=""', () => {
|
||||||
|
const { html } = toHtml({}, ''); // no images prop -> component default SVG placeholders
|
||||||
|
expect(html).not.toContain('src=""');
|
||||||
|
expect(html).toMatch(/src="data:image\/svg\+xml[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an explicit data:image/svg+xml gallery image src is preserved (not stripped to empty)', () => {
|
||||||
|
const svg = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const { html } = toHtml({ images: [{ src: svg, alt: 'a' }] }, '');
|
||||||
|
expect(html).toContain(`src="${svg}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lightbox data-lb-src also preserves data:image/svg+xml (still an image context)', () => {
|
||||||
|
const svg = 'data:image/svg+xml,%3Csvg%2F%3E';
|
||||||
|
const { html } = toHtml({ images: [{ src: svg, alt: 'a' }], lightbox: true }, '');
|
||||||
|
expect(html).toContain(`data-lb-src="${svg}"`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a javascript: gallery image src still yields an empty src (safeImageUrl still blocks it)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: 'javascript:alert(1)', alt: 'a' }] }, '');
|
||||||
|
expect(html).toContain('src=""');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml lightbox focus management (M-2)', () => {
|
||||||
|
const props = { images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true };
|
||||||
|
|
||||||
|
test('overlay includes a focusable close control with an accessible name and tabindex', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// A close control: a button (or the dialog container) with an accessible
|
||||||
|
// name (aria-label) and an explicit tabindex so it's keyboard-focusable.
|
||||||
|
expect(html).toMatch(/aria-label="[^"]*[Cc]lose[^"]*"[^>]*tabindex="-?\d+"|tabindex="-?\d+"[^>]*aria-label="[^"]*[Cc]lose[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script saves document.activeElement on open (for focus restore)', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/document\.activeElement/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script moves focus to the close control / dialog on open', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
expect(html).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('script restores the previously-saved focus on close', () => {
|
||||||
|
const { html } = toHtml(props, '', 'node-gal1');
|
||||||
|
// The close function references a stored "last focused element" variable
|
||||||
|
// and calls .focus() on it, not just moving focus INTO the dialog.
|
||||||
|
const closeFnMatch = html.match(/function\s+\w+_close\s*\(\)\s*\{[^}]*\}/);
|
||||||
|
expect(closeFnMatch).not.toBeNull();
|
||||||
|
expect(closeFnMatch![0]).toMatch(/\.focus\(\)/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import React, { CSSProperties } from 'react';
|
import React, { CSSProperties } from 'react';
|
||||||
import { useNode, UserComponent } from '@craftjs/core';
|
import { useNode, UserComponent } from '@craftjs/core';
|
||||||
import { cssPropsToString } from '../../utils/style-helpers';
|
import { cssPropsToString } from '../../utils/style-helpers';
|
||||||
import { escapeHtml, escapeAttr, safeUrl, scopeId, cssValue } from '../../utils/escape';
|
import { escapeHtml, escapeAttr, safeImageUrl, scopeId, cssValue } from '../../utils/escape';
|
||||||
|
|
||||||
interface GalleryImage {
|
interface GalleryImage {
|
||||||
src: string;
|
src: string;
|
||||||
@@ -154,10 +154,10 @@ Gallery.craft = {
|
|||||||
// inline onclick with an interpolated src -- a single delegated click
|
// inline onclick with an interpolated src -- a single delegated click
|
||||||
// listener below reads it, so a src containing a quote can't break out
|
// listener below reads it, so a src containing a quote can't break out
|
||||||
// of a per-item event-handler string.
|
// of a per-item event-handler string.
|
||||||
const lbAttr = lightbox ? ` data-lb-src="${escapeAttr(safeUrl(img.src || ''))}" role="button" tabindex="0"` : '';
|
const lbAttr = lightbox ? ` data-lb-src="${escapeAttr(safeImageUrl(img.src || ''))}" role="button" tabindex="0"` : '';
|
||||||
const itemStyle = lightbox ? 'cursor:pointer;position:relative;overflow:hidden;border-radius:8px' : 'position:relative;overflow:hidden;border-radius:8px';
|
const itemStyle = lightbox ? 'cursor:pointer;position:relative;overflow:hidden;border-radius:8px' : 'position:relative;overflow:hidden;border-radius:8px';
|
||||||
return `<div${lbAttr} style="${itemStyle}">
|
return `<div${lbAttr} style="${itemStyle}">
|
||||||
<img src="${escapeAttr(safeUrl(img.src || ''))}" alt="${escapeAttr(img.alt)}" style="width:100%;height:200px;object-fit:cover;display:block;border-radius:8px;background-color:#f1f5f9" />
|
<img src="${escapeAttr(safeImageUrl(img.src || ''))}" alt="${escapeAttr(img.alt)}" style="width:100%;height:200px;object-fit:cover;display:block;border-radius:8px;background-color:#f1f5f9" />
|
||||||
${caption}
|
${caption}
|
||||||
</div>`;
|
</div>`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
@@ -166,16 +166,37 @@ Gallery.craft = {
|
|||||||
let gridIdAttr = '';
|
let gridIdAttr = '';
|
||||||
if (lightbox) {
|
if (lightbox) {
|
||||||
gridIdAttr = ` id="${galleryId}_grid"`;
|
gridIdAttr = ` id="${galleryId}_grid"`;
|
||||||
|
// M-2: focus management for the lightbox dialog.
|
||||||
|
// - OPEN: stash `document.activeElement` (the thumbnail that triggered
|
||||||
|
// the open) in a module-scoped var, then move focus onto the close
|
||||||
|
// button -- so a screen-reader/keyboard user lands inside the dialog
|
||||||
|
// instead of focus staying on (or silently falling back to <body>)
|
||||||
|
// behind the now-visible overlay.
|
||||||
|
// - Tab trap: while the overlay is open, every Tab keypress is
|
||||||
|
// intercepted and refocuses the close button (the dialog's only
|
||||||
|
// focusable control besides Escape/click-to-close), so focus can
|
||||||
|
// never wander out into the page content hidden behind the overlay.
|
||||||
|
// - CLOSE (Escape, backdrop click, or the close button): restore focus
|
||||||
|
// to the element stashed on open.
|
||||||
lightboxHtml = `
|
lightboxHtml = `
|
||||||
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
<div id="${galleryId}_overlay" role="dialog" aria-modal="true" aria-label="Image preview" onclick="${galleryId}_close()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);z-index:9999;justify-content:center;align-items:center;cursor:pointer">
|
||||||
|
<button type="button" id="${galleryId}_closebtn" aria-label="Close preview" tabindex="-1" onclick="event.stopPropagation();${galleryId}_close()" style="position:absolute;top:16px;right:16px;width:36px;height:36px;border-radius:50%;border:none;background:rgba(255,255,255,0.15);color:#ffffff;font-size:20px;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center">×</button>
|
||||||
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
<img id="${galleryId}_img" src="" alt="" style="max-width:90%;max-height:90%;object-fit:contain;border-radius:8px" />
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
function ${galleryId}_close(){document.getElementById('${galleryId}_overlay').style.display='none';}
|
var ${galleryId}_lastFocus = null;
|
||||||
|
function ${galleryId}_close(){
|
||||||
|
document.getElementById('${galleryId}_overlay').style.display='none';
|
||||||
|
if(${galleryId}_lastFocus && ${galleryId}_lastFocus.focus) ${galleryId}_lastFocus.focus();
|
||||||
|
${galleryId}_lastFocus = null;
|
||||||
|
}
|
||||||
function ${galleryId}_open(src){
|
function ${galleryId}_open(src){
|
||||||
|
${galleryId}_lastFocus = document.activeElement;
|
||||||
var o = document.getElementById('${galleryId}_overlay');
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
document.getElementById('${galleryId}_img').src = src;
|
document.getElementById('${galleryId}_img').src = src;
|
||||||
o.style.display = 'flex';
|
o.style.display = 'flex';
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
}
|
}
|
||||||
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
document.getElementById('${galleryId}_grid').addEventListener('click', function(e){
|
||||||
var t = e.target.closest('[data-lb-src]');
|
var t = e.target.closest('[data-lb-src]');
|
||||||
@@ -190,7 +211,14 @@ document.getElementById('${galleryId}_grid').addEventListener('keydown', functio
|
|||||||
${galleryId}_open(t.getAttribute('data-lb-src'));
|
${galleryId}_open(t.getAttribute('data-lb-src'));
|
||||||
});
|
});
|
||||||
document.addEventListener('keydown', function(e){
|
document.addEventListener('keydown', function(e){
|
||||||
if(e.key==='Escape'){ ${galleryId}_close(); }
|
var o = document.getElementById('${galleryId}_overlay');
|
||||||
|
if(!o || o.style.display==='none') return;
|
||||||
|
if(e.key==='Escape'){ ${galleryId}_close(); return; }
|
||||||
|
if(e.key==='Tab'){
|
||||||
|
e.preventDefault();
|
||||||
|
var c = document.getElementById('${galleryId}_closebtn');
|
||||||
|
if(c) c.focus();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
</script>`;
|
</script>`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import { HeroSimple } from './HeroSimple';
|
||||||
|
|
||||||
|
const toHtml = (HeroSimple as any).toHtml;
|
||||||
|
|
||||||
|
describe('HeroSimple.toHtml textAlign enum sink (attacker-controlled prop, not enforced at runtime)', () => {
|
||||||
|
test('malicious textAlign value cannot break out of the content div style attribute', () => {
|
||||||
|
const { html } = toHtml({
|
||||||
|
heading: 'Hi',
|
||||||
|
subtitle: 'There',
|
||||||
|
textAlign: 'center;"><script>alert(1)</script>',
|
||||||
|
}, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('center;">');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unrecognized textAlign value falls back to a safe default rather than being echoed raw', () => {
|
||||||
|
const { html } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'not-a-real-value' as any }, '');
|
||||||
|
expect(html).not.toContain('text-align:not-a-real-value');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('valid textAlign values are preserved', () => {
|
||||||
|
const { html: left } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'left' }, '');
|
||||||
|
expect(left).toContain('text-align:left');
|
||||||
|
const { html: right } = toHtml({ heading: 'Hi', subtitle: 'There', textAlign: 'right' }, '');
|
||||||
|
expect(right).toContain('text-align:right');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal default render is sane', () => {
|
||||||
|
const { html } = toHtml({ heading: 'Welcome', subtitle: 'Sub text' }, '');
|
||||||
|
expect(html).toContain('Welcome');
|
||||||
|
expect(html).toContain('Sub text');
|
||||||
|
expect(html).toContain('text-align:center');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -229,7 +229,13 @@ HeroSimple.craft = {
|
|||||||
videoHtml = `<video src="${escapeAttr(safeUrl(props.bgVideo))}" autoplay muted loop playsinline style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover;z-index:0"></video>`;
|
videoHtml = `<video src="${escapeAttr(safeUrl(props.bgVideo))}" autoplay muted loop playsinline style="position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover;z-index:0"></video>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const textAlign = props.textAlign || 'center';
|
// Allowlisted -- `textAlign` is declared as a 'left'|'center'|'right' union
|
||||||
|
// but arrives unchecked via AI update_props / deserialized state; it is
|
||||||
|
// interpolated raw into the content div's style attribute below, so any
|
||||||
|
// other value must collapse to a known-safe default rather than being
|
||||||
|
// echoed into the markup.
|
||||||
|
const ALLOWED_TEXT_ALIGN = ['left', 'center', 'right'];
|
||||||
|
const textAlign = ALLOWED_TEXT_ALIGN.includes(props.textAlign as string) ? (props.textAlign as string) : 'center';
|
||||||
const justifyBtn = textAlign === 'center' ? 'center' : textAlign === 'right' ? 'flex-end' : 'flex-start';
|
const justifyBtn = textAlign === 'center' ? 'center' : textAlign === 'right' ? 'flex-end' : 'flex-start';
|
||||||
|
|
||||||
const ctas = normalizeCtas(props);
|
const ctas = normalizeCtas(props);
|
||||||
|
|||||||
@@ -47,3 +47,29 @@ describe('NumberCounter.toHtml deterministic + unique scope ids (thread node id,
|
|||||||
expect(wrapId1).not.toBe(wrapId2);
|
expect(wrapId1).not.toBe(wrapId2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('NumberCounter.toHtml counter.number is NOT runtime-type-checked -- must be sanitized before it reaches data-target', () => {
|
||||||
|
test('a malicious counter.number cannot break out of the data-target attribute to inject a <script> tag', () => {
|
||||||
|
const malicious = [
|
||||||
|
{ number: '150"><script>alert(1)</script>', suffix: '+', label: 'Evil' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ counters: malicious }, '', 'node-nc-evil1');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('"><script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious counter.number cannot break out of the data-target attribute to inject an onmouseover handler', () => {
|
||||||
|
const malicious = [
|
||||||
|
{ number: '150" onmouseover="alert(1)', suffix: '+', label: 'Evil' },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ counters: malicious }, '', 'node-nc-evil2');
|
||||||
|
expect(html).not.toContain('onmouseover=');
|
||||||
|
expect(html).not.toMatch(/data-target="150" onmouseover/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal numeric counter.number values still render as data-target="150"', () => {
|
||||||
|
const normal = [{ number: 150, suffix: '+', label: 'Projects' }];
|
||||||
|
const { html } = toHtml({ counters: normal }, '', 'node-nc-normal');
|
||||||
|
expect(html).toContain('data-target="150"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -140,8 +140,20 @@ NumberCounter.craft = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const countersHtml = items.map((counter, i) => {
|
const countersHtml = items.map((counter, i) => {
|
||||||
|
// Number() coercion + escapeAttr: `counter.number` is declared `number`
|
||||||
|
// per-item inside an array prop, but is NOT type-checked at runtime --
|
||||||
|
// it arrives raw via the AI `update_props` path or a deserialized
|
||||||
|
// saved-state blob and was previously interpolated straight into this
|
||||||
|
// data-target attribute, letting a string like `150"><script>...`
|
||||||
|
// break out of the attribute and inject markup. Number() collapses any
|
||||||
|
// non-numeric value safely to NaN (then 0), and escapeAttr is kept as
|
||||||
|
// defense-in-depth in case Number()'s string coercion output ever
|
||||||
|
// contains a stray character (it can't today, but the sink should never
|
||||||
|
// rely solely on the coercion).
|
||||||
|
const numberVal = Number(counter.number);
|
||||||
|
const safeNumber = Number.isFinite(numberVal) ? numberVal : 0;
|
||||||
return `<div style="display:flex;flex-direction:column;align-items:center;gap:8px">
|
return `<div style="display:flex;flex-direction:column;align-items:center;gap:8px">
|
||||||
<span id="${uid}_n${i}" data-target="${counter.number}" data-suffix="${escapeAttr(counter.suffix)}" style="font-size:${numberSize};font-weight:700;color:${numberColor};line-height:1.1;font-family:Inter,sans-serif">0${escapeHtml(counter.suffix)}</span>
|
<span id="${uid}_n${i}" data-target="${escapeAttr(String(safeNumber))}" data-suffix="${escapeAttr(counter.suffix)}" style="font-size:${numberSize};font-weight:700;color:${numberColor};line-height:1.1;font-family:Inter,sans-serif">0${escapeHtml(counter.suffix)}</span>
|
||||||
<span style="font-size:15px;color:${labelColor};font-family:Inter,sans-serif;font-weight:500">${escapeHtml(counter.label)}</span>
|
<span style="font-size:15px;color:${labelColor};font-family:Inter,sans-serif;font-weight:500">${escapeHtml(counter.label)}</span>
|
||||||
</div>`;
|
</div>`;
|
||||||
}).join('\n ');
|
}).join('\n ');
|
||||||
|
|||||||
@@ -46,3 +46,28 @@ describe('Testimonials.toHtml decorative star icons (F2.5)', () => {
|
|||||||
stars.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
stars.forEach((tag: string) => expect(tag).toContain('aria-hidden="true"'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('Testimonials.toHtml rating aria-label sink (attacker-controlled `rating`, typed number but unchecked)', () => {
|
||||||
|
test('malicious rating value cannot break out of the star row aria-label attribute', () => {
|
||||||
|
const malicious = [
|
||||||
|
{ quote: 'Q', name: 'N', title: 'T', rating: '5"><script>alert(1)</script>' as any },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ testimonials: malicious, layout: 'grid' }, '');
|
||||||
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
|
expect(html).not.toContain('5"><script>');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('non-numeric rating falls back to a safe numeric value', () => {
|
||||||
|
const malicious = [
|
||||||
|
{ quote: 'Q', name: 'N', title: 'T', rating: 'not-a-number' as any },
|
||||||
|
];
|
||||||
|
const { html } = toHtml({ testimonials: malicious, layout: 'grid' }, '');
|
||||||
|
expect(html).toMatch(/aria-label="Rating: 0 out of 5"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normal numeric rating still renders correctly', () => {
|
||||||
|
const { html } = toHtml({ testimonials, layout: 'grid' }, '');
|
||||||
|
expect(html).toContain('aria-label="Rating: 5 out of 5"');
|
||||||
|
expect(html).toContain('aria-label="Rating: 4 out of 5"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -41,10 +41,16 @@ function renderStars(count: number, color: string): React.ReactNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function starsHtml(count: number, color: string): string {
|
function starsHtml(count: number, color: string): string {
|
||||||
|
// `count` is `Testimonial.rating`, typed `number` but arrives unchecked via
|
||||||
|
// AI update_props / deserialized state -- coerce to a real number before
|
||||||
|
// it's interpolated into the aria-label attribute below (both the loop
|
||||||
|
// comparison and the escapeAttr(String(...)) call are safe against any
|
||||||
|
// non-numeric/garbage value).
|
||||||
|
const safeCount = Number(count) || 0;
|
||||||
const stars = [1, 2, 3, 4, 5].map((i) =>
|
const stars = [1, 2, 3, 4, 5].map((i) =>
|
||||||
`<i class="fa ${i <= count ? 'fa-star' : 'fa-star-o'}" style="color:${color};font-size:14px" aria-hidden="true"></i>`
|
`<i class="fa ${i <= safeCount ? 'fa-star' : 'fa-star-o'}" style="color:${color};font-size:14px" aria-hidden="true"></i>`
|
||||||
).join('');
|
).join('');
|
||||||
return `<div style="display:flex;gap:2px;justify-content:center;margin-bottom:12px" role="img" aria-label="Rating: ${count} out of 5">${stars}</div>`;
|
return `<div style="display:flex;gap:2px;justify-content:center;margin-bottom:12px" role="img" aria-label="${escapeAttr(`Rating: ${safeCount} out of 5`)}">${stars}</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Testimonials: UserComponent<TestimonialsProps> = ({
|
export const Testimonials: UserComponent<TestimonialsProps> = ({
|
||||||
|
|||||||
@@ -94,3 +94,68 @@ export const DEVICE_WIDTHS: Record<string, string> = {
|
|||||||
tablet: '768px',
|
tablet: '768px',
|
||||||
mobile: '375px',
|
mobile: '375px',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* ---------- ENH-Foundation shared presets ----------
|
||||||
|
Consumed by the reusable StylePanel controls in
|
||||||
|
src/panels/right/styles/shared.tsx (SizeControl, AspectRatioControl,
|
||||||
|
BorderControl, etc). Kept in the `{ label, value }` shape used throughout
|
||||||
|
this file so they drop straight into PresetButtonGrid / ColorSwatchGrid. */
|
||||||
|
|
||||||
|
// Width/height preset row used by SizeControl (image + video sizing).
|
||||||
|
export const SIZE_PRESETS = [
|
||||||
|
{ label: '25%', value: '25%' },
|
||||||
|
{ label: '50%', value: '50%' },
|
||||||
|
{ label: '75%', value: '75%' },
|
||||||
|
{ label: '100%', value: '100%' },
|
||||||
|
{ label: 'Auto', value: 'auto' },
|
||||||
|
{ label: 'Full', value: '100vw' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// CSS `aspect-ratio` values. 'Original' (empty string) clears the property.
|
||||||
|
export const ASPECT_RATIOS = [
|
||||||
|
{ label: 'Original', value: '' },
|
||||||
|
{ label: '1:1', value: '1 / 1' },
|
||||||
|
{ label: '4:3', value: '4 / 3' },
|
||||||
|
{ label: '3:2', value: '3 / 2' },
|
||||||
|
{ label: '16:9', value: '16 / 9' },
|
||||||
|
{ label: '4:5', value: '4 / 5' },
|
||||||
|
{ label: '9:16', value: '9 / 16' },
|
||||||
|
];
|
||||||
|
|
||||||
|
// box-shadow presets; 'Colored' is the color-aware option (accent-tinted).
|
||||||
|
export const SHADOW_PRESETS = [
|
||||||
|
{ label: 'None', value: 'none' },
|
||||||
|
{ label: 'S', value: '0 1px 2px rgba(0,0,0,0.08)' },
|
||||||
|
{ label: 'M', value: '0 4px 8px rgba(0,0,0,0.12)' },
|
||||||
|
{ label: 'L', value: '0 10px 24px rgba(0,0,0,0.18)' },
|
||||||
|
{ label: 'Colored', value: '0 8px 20px rgba(59,130,246,0.35)' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const LINE_HEIGHTS = [
|
||||||
|
{ label: 'Tight', value: '1.1' },
|
||||||
|
{ label: 'Snug', value: '1.25' },
|
||||||
|
{ label: 'Normal', value: '1.5' },
|
||||||
|
{ label: 'Relaxed', value: '1.75' },
|
||||||
|
{ label: 'Loose', value: '2' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const LETTER_SPACINGS = [
|
||||||
|
{ label: 'Tight', value: '-0.02em' },
|
||||||
|
{ label: 'Normal', value: 'normal' },
|
||||||
|
{ label: 'Wide', value: '0.05em' },
|
||||||
|
{ label: 'Wider', value: '0.1em' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const OBJECT_FIT = [
|
||||||
|
{ label: 'Cover', value: 'cover' },
|
||||||
|
{ label: 'Contain', value: 'contain' },
|
||||||
|
{ label: 'Fill', value: 'fill' },
|
||||||
|
{ label: 'None', value: 'none' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const BORDER_STYLES = [
|
||||||
|
{ label: 'None', value: 'none' },
|
||||||
|
{ label: 'Solid', value: 'solid' },
|
||||||
|
{ label: 'Dashed', value: 'dashed' },
|
||||||
|
{ label: 'Dotted', value: 'dotted' },
|
||||||
|
];
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import React, { useMemo, useRef, useEffect } from 'react';
|
import React, { useMemo, useRef, useEffect } from 'react';
|
||||||
import { Frame, Element } from '@craftjs/core';
|
import { Frame, Element, useEditor } from '@craftjs/core';
|
||||||
import { Container } from '../components/layout/Container';
|
import { Container } from '../components/layout/Container';
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
import { DEVICE_WIDTHS } from '../constants/presets';
|
import { DEVICE_WIDTHS } from '../constants/presets';
|
||||||
import { exportBodyHtml } from '../utils/html-export';
|
import { exportBodyHtml } from '../utils/html-export';
|
||||||
|
import { useIsMobile } from '../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../state/MobileChromeContext';
|
||||||
|
|
||||||
interface CanvasProps {
|
interface CanvasProps {
|
||||||
device: DeviceMode;
|
device: DeviceMode;
|
||||||
|
/** Item 10: when false, applies `.guides-off` to hide the dashed drop-target guides. */
|
||||||
|
showGuides: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -81,24 +85,93 @@ const ZonePreview: React.FC<{ craftState: string | null; zone: 'header' | 'foote
|
|||||||
<div
|
<div
|
||||||
ref={containerRef}
|
ref={containerRef}
|
||||||
data-zone-preview={zone}
|
data-zone-preview={zone}
|
||||||
|
className="zone-preview-sep"
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
pointerEvents: 'none',
|
pointerEvents: 'none',
|
||||||
userSelect: 'none',
|
userSelect: 'none',
|
||||||
borderBottom: zone === 'header' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
borderBottom: zone === 'header' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||||
borderTop: zone === 'footer' ? '1px dashed rgba(245,158,11,0.3)' : 'none',
|
borderTop: zone === 'footer' ? '1px dashed rgba(148,163,184,0.25)' : 'none',
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
/**
|
||||||
|
* First-run hint shown over the canvas drop area once the current page's
|
||||||
|
* root node exists and has no children yet. Hidden the instant something
|
||||||
|
* is dropped in, and while a drag is in progress (so it never fights the
|
||||||
|
* drop-target UI). `pointer-events: none` (see .empty-canvas-hint in
|
||||||
|
* editor.css) keeps it from intercepting clicks/drops meant for the
|
||||||
|
* underlying empty canvas.
|
||||||
|
*/
|
||||||
|
export const EmptyCanvasHint: React.FC = () => {
|
||||||
|
const { isEmpty, isDragging } = useEditor((state) => {
|
||||||
|
const root = state.nodes['ROOT'];
|
||||||
|
return {
|
||||||
|
isEmpty: !!root && root.data.nodes.length === 0,
|
||||||
|
isDragging: state.events.dragged.size > 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
if (!isEmpty || isDragging) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="empty-canvas-hint">
|
||||||
|
<i className="fa fa-cubes" aria-hidden />
|
||||||
|
<span>
|
||||||
|
{isMobile
|
||||||
|
? <>Tap <strong>Blocks</strong> below to add content, or pick a Template to start.</>
|
||||||
|
: 'Drag blocks from the left panel, or pick a Template to start.'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Canvas: React.FC<CanvasProps> = ({ device, showGuides }) => {
|
||||||
const width = DEVICE_WIDTHS[device];
|
const width = DEVICE_WIDTHS[device];
|
||||||
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
|
const { isEditingHeader, isEditingFooter, headerPage, footerPage } = usePages();
|
||||||
|
|
||||||
const isEditingRegularPage = !isEditingHeader && !isEditingFooter;
|
const isEditingRegularPage = !isEditingHeader && !isEditingFooter;
|
||||||
|
|
||||||
|
// Fast-follow item 4: while `MobileSelectionToolbar` is up (fixed, ~53px
|
||||||
|
// tall, just above the tab bar), it covers whatever content was at the
|
||||||
|
// very bottom of the canvas's own scroll area -- on a short page, the
|
||||||
|
// last section could sit permanently under the toolbar with no way to
|
||||||
|
// scroll past it. Mirrors that toolbar's own visibility condition
|
||||||
|
// (`selectedId && activeSheet === null`) exactly, computed independently
|
||||||
|
// here since Canvas has no other reason to depend on the toolbar
|
||||||
|
// component itself.
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { activeSheet } = useMobileChrome();
|
||||||
|
const { selectedId } = useEditor((state) => {
|
||||||
|
const selected = state.events.selected;
|
||||||
|
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
|
||||||
|
return { selectedId: id && id !== 'ROOT' ? id : null };
|
||||||
|
});
|
||||||
|
const mobileToolbarVisible = isMobile && !!selectedId && activeSheet === null;
|
||||||
|
|
||||||
|
// Fast-follow item 3: `MobileSelectionToolbar`'s "Style" tap scrolls the
|
||||||
|
// selected node up towards the top of the canvas so it stays visible
|
||||||
|
// above the Styles sheet (~65dvh tall) -- but that scroll is still bound
|
||||||
|
// by the canvas's own natural scroll range. For a selected node near the
|
||||||
|
// END of the content (very plausibly the last section on the page --
|
||||||
|
// exactly the kind of node someone just added/duplicated and wants to
|
||||||
|
// style), there may not be enough scrollable distance below it to bring
|
||||||
|
// its top all the way up to the visible band above the sheet; the browser
|
||||||
|
// simply clamps at its existing max scrollTop, leaving the node's top
|
||||||
|
// stuck behind the sheet with nothing anyone can do about it (verified
|
||||||
|
// live: the last section of a page landed under the sheet even after the
|
||||||
|
// scroll-into-view ran). Pad the canvas with a full extra viewport's
|
||||||
|
// worth of scroll room while the sheet is open with a selection, exactly
|
||||||
|
// as `has-mobile-selection-toolbar` (item 4) already pads it for the
|
||||||
|
// fixed toolbar -- generous enough that ANY node, including the very
|
||||||
|
// last one, can always be scrolled with its top reaching the very top of
|
||||||
|
// the canvas (comfortably within the "top ~30%" target).
|
||||||
|
const mobileStylesSheetPad = isMobile && !!selectedId && activeSheet === 'styles';
|
||||||
|
|
||||||
const frameStyle = isEditingHeader
|
const frameStyle = isEditingHeader
|
||||||
? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' }
|
? { minHeight: '60px', backgroundColor: '#ffffff', padding: '12px 24px', display: 'flex', alignItems: 'center' }
|
||||||
: isEditingFooter
|
: isEditingFooter
|
||||||
@@ -108,9 +181,13 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div';
|
const frameTag = isEditingHeader ? 'header' : isEditingFooter ? 'footer' : 'div';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="editor-canvas">
|
|
||||||
<div
|
<div
|
||||||
className="canvas-device-frame"
|
className={`editor-canvas${mobileToolbarVisible ? ' has-mobile-selection-toolbar' : ''}${
|
||||||
|
mobileStylesSheetPad ? ' has-mobile-styles-sheet' : ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`canvas-device-frame${showGuides ? '' : ' guides-off'}`}
|
||||||
style={{
|
style={{
|
||||||
width,
|
width,
|
||||||
maxWidth: '100%',
|
maxWidth: '100%',
|
||||||
@@ -140,6 +217,7 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
<ZonePreview craftState={headerPage.craftState} zone="header" />
|
<ZonePreview craftState={headerPage.craftState} zone="header" />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div style={{ position: 'relative' }}>
|
||||||
<Frame>
|
<Frame>
|
||||||
<Element
|
<Element
|
||||||
is={Container}
|
is={Container}
|
||||||
@@ -148,6 +226,8 @@ export const Canvas: React.FC<CanvasProps> = ({ device }) => {
|
|||||||
style={frameStyle}
|
style={frameStyle}
|
||||||
/>
|
/>
|
||||||
</Frame>
|
</Frame>
|
||||||
|
{isEditingRegularPage && <EmptyCanvasHint />}
|
||||||
|
</div>
|
||||||
|
|
||||||
{isEditingRegularPage && (
|
{isEditingRegularPage && (
|
||||||
<ZonePreview craftState={footerPage.craftState} zone="footer" />
|
<ZonePreview craftState={footerPage.craftState} zone="footer" />
|
||||||
|
|||||||
@@ -1,16 +1,60 @@
|
|||||||
import React, { useState, useCallback } from 'react';
|
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { TopBar } from '../panels/topbar/TopBar';
|
import { TopBar } from '../panels/topbar/TopBar';
|
||||||
import { LeftPanel } from '../panels/left/LeftPanel';
|
import { LeftPanel } from '../panels/left/LeftPanel';
|
||||||
import { RightPanel } from '../panels/right/RightPanel';
|
import { RightPanel } from '../panels/right/RightPanel';
|
||||||
|
import { MobilePanelBar } from '../panels/mobile/MobilePanelBar';
|
||||||
|
import { MobileSelectionToolbar } from '../panels/mobile/MobileSelectionToolbar';
|
||||||
import { Canvas } from './Canvas';
|
import { Canvas } from './Canvas';
|
||||||
import { ContextMenu } from '../panels/context-menu/ContextMenu';
|
import { ContextMenu } from '../panels/context-menu/ContextMenu';
|
||||||
import { useContextMenu } from '../hooks/useContextMenu';
|
import { useContextMenu } from '../hooks/useContextMenu';
|
||||||
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
|
||||||
|
import { useIsMobile } from '../hooks/useIsMobile';
|
||||||
|
import { MobileChromeProvider } from '../state/MobileChromeContext';
|
||||||
import { DeviceMode } from '../types';
|
import { DeviceMode } from '../types';
|
||||||
|
|
||||||
|
const SHOW_GUIDES_STORAGE_KEY = 'craft-show-guides';
|
||||||
|
|
||||||
|
function loadShowGuides(): boolean {
|
||||||
|
try {
|
||||||
|
const stored = window.localStorage.getItem(SHOW_GUIDES_STORAGE_KEY);
|
||||||
|
return stored === null ? true : stored === '1';
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const EditorShell: React.FC = () => {
|
export const EditorShell: React.FC = () => {
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const [device, setDevice] = useState<DeviceMode>('desktop');
|
const [device, setDevice] = useState<DeviceMode>('desktop');
|
||||||
|
// Phase A: default the canvas to the "mobile" preview width the first
|
||||||
|
// time we detect a mobile viewport, so the frame fits without the user
|
||||||
|
// having to reach for the device switcher (now tucked in TopBar's
|
||||||
|
// overflow menu on mobile). Only fires once, and only if the device is
|
||||||
|
// still at its initial default -- it must not fight a device the user
|
||||||
|
// has already picked (e.g. from the overflow menu) on a later re-render.
|
||||||
|
const mobileDeviceAppliedRef = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (isMobile && !mobileDeviceAppliedRef.current) {
|
||||||
|
mobileDeviceAppliedRef.current = true;
|
||||||
|
setDevice((current) => (current === 'desktop' ? 'mobile' : current));
|
||||||
|
}
|
||||||
|
}, [isMobile]);
|
||||||
|
// Item 10: canvas dashed "guide" outlines toggle -- default ON, persisted
|
||||||
|
// so the choice survives a reload. Lifted here (rather than owned by
|
||||||
|
// TopBar or Canvas alone) because the toggle button lives in TopBar but
|
||||||
|
// the `.guides-off` class it drives is applied to Canvas's
|
||||||
|
// `.canvas-device-frame`, mirroring how `device` is already lifted for
|
||||||
|
// the same reason.
|
||||||
|
const [showGuides, setShowGuidesState] = useState<boolean>(loadShowGuides);
|
||||||
|
const setShowGuides = useCallback((next: boolean) => {
|
||||||
|
setShowGuidesState(next);
|
||||||
|
try {
|
||||||
|
window.localStorage.setItem(SHOW_GUIDES_STORAGE_KEY, next ? '1' : '0');
|
||||||
|
} catch {
|
||||||
|
// Storage unavailable (private browsing, etc.) -- in-memory state still works.
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
const { menuState, show: showMenu, hide: hideMenu } = useContextMenu();
|
const { menuState, show: showMenu, hide: hideMenu } = useContextMenu();
|
||||||
const { query } = useEditor();
|
const { query } = useEditor();
|
||||||
|
|
||||||
@@ -33,15 +77,28 @@ export const EditorShell: React.FC = () => {
|
|||||||
}, [query, showMenu]);
|
}, [query, showMenu]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
// Mobile-A2: shared sheet/modal-open state (see MobileChromeContext) --
|
||||||
|
// provided around the whole shell so TopBar's Templates/Head Code modal
|
||||||
|
// state and MobilePanelBar's sheet state live in one place. Desktop
|
||||||
|
// doesn't render MobilePanelBar and TopBar's desktop branch behaves
|
||||||
|
// identically to before (same booleans, just sourced from context).
|
||||||
|
<MobileChromeProvider>
|
||||||
<div className="editor-app">
|
<div className="editor-app">
|
||||||
<TopBar device={device} onDeviceChange={setDevice} />
|
<TopBar
|
||||||
|
device={device}
|
||||||
|
onDeviceChange={setDevice}
|
||||||
|
showGuides={showGuides}
|
||||||
|
onToggleGuides={() => setShowGuides(!showGuides)}
|
||||||
|
/>
|
||||||
<div className="editor-container">
|
<div className="editor-container">
|
||||||
<LeftPanel />
|
{!isMobile && <LeftPanel />}
|
||||||
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
<div onContextMenu={handleContextMenu} style={{ flex: 1, display: 'flex', minWidth: 0 }}>
|
||||||
<Canvas device={device} />
|
<Canvas device={device} showGuides={showGuides} />
|
||||||
</div>
|
</div>
|
||||||
<RightPanel />
|
{!isMobile && <RightPanel />}
|
||||||
</div>
|
</div>
|
||||||
|
{isMobile && <MobilePanelBar />}
|
||||||
|
{isMobile && <MobileSelectionToolbar />}
|
||||||
<ContextMenu
|
<ContextMenu
|
||||||
visible={menuState.visible}
|
visible={menuState.visible}
|
||||||
x={menuState.x}
|
x={menuState.x}
|
||||||
@@ -50,5 +107,6 @@ export const EditorShell: React.FC = () => {
|
|||||||
onClose={hideMenu}
|
onClose={hideMenu}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</MobileChromeProvider>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as Footer.editguard.test.tsx: mock @craftjs/core's
|
||||||
|
useEditor so we can drive editor state without a real <Editor> tree. */
|
||||||
|
let mockNodes: Record<string, { data: { nodes: string[] } }> = {};
|
||||||
|
let mockDraggedSize = 0;
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: (collect: (state: any) => any) =>
|
||||||
|
collect({
|
||||||
|
nodes: mockNodes,
|
||||||
|
events: { dragged: { size: mockDraggedSize } },
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { EmptyCanvasHint } from './Canvas';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockNodes = {};
|
||||||
|
mockDraggedSize = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EmptyCanvasHint', () => {
|
||||||
|
test('renders nothing before ROOT has mounted (no root node yet)', () => {
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('renders the hint once ROOT exists with zero children', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: [] } } };
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).not.toBeNull();
|
||||||
|
expect(container.textContent).toContain('Drag blocks from the left panel');
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides once the page has content', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: ['node-1'] } } };
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hides while a drag is in progress, even on an empty root', () => {
|
||||||
|
mockNodes = { ROOT: { data: { nodes: [] } } };
|
||||||
|
mockDraggedSize = 1;
|
||||||
|
render(<EmptyCanvasHint />);
|
||||||
|
expect(container.querySelector('.empty-canvas-hint')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as Footer.editguard.test.tsx: mock @craftjs/core
|
||||||
|
so RenderNode (the <Editor onRender> override) can be driven without a
|
||||||
|
real Editor tree. document.body doubles as the portal target, same as
|
||||||
|
the component itself uses. */
|
||||||
|
let mockNode: {
|
||||||
|
id: string;
|
||||||
|
selected: boolean;
|
||||||
|
hovered: boolean;
|
||||||
|
dom: HTMLElement | null;
|
||||||
|
displayName: string;
|
||||||
|
parent: string | null;
|
||||||
|
isCanvas: boolean;
|
||||||
|
};
|
||||||
|
const selectNodeSpy = vi.fn();
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: () => ({ actions: { selectNode: selectNodeSpy } }),
|
||||||
|
useNode: (collect?: (node: any) => any) => {
|
||||||
|
const node = {
|
||||||
|
events: { selected: mockNode.selected, hovered: mockNode.hovered },
|
||||||
|
dom: mockNode.dom,
|
||||||
|
data: {
|
||||||
|
custom: {},
|
||||||
|
displayName: mockNode.displayName,
|
||||||
|
parent: mockNode.parent,
|
||||||
|
isCanvas: mockNode.isCanvas,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { id: mockNode.id, ...(collect ? collect(node) : {}) };
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { RenderNode } from './RenderNode';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let nodeDom: HTMLElement;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
nodeDom = document.createElement('div');
|
||||||
|
document.body.appendChild(nodeDom);
|
||||||
|
mockNode = {
|
||||||
|
id: 'node-1',
|
||||||
|
selected: false,
|
||||||
|
hovered: false,
|
||||||
|
dom: nodeDom,
|
||||||
|
displayName: 'Heading',
|
||||||
|
parent: 'ROOT',
|
||||||
|
isCanvas: false,
|
||||||
|
};
|
||||||
|
selectNodeSpy.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
const rendered = <span data-testid="inner">hello</span>;
|
||||||
|
|
||||||
|
describe('RenderNode (Editor onRender override)', () => {
|
||||||
|
test('passes render through untouched when not selected', () => {
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(container.querySelector('[data-testid="inner"]')).not.toBeNull();
|
||||||
|
expect(document.querySelector('.component-indicator')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shows the badge with the displayName when selected', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
const badge = document.querySelector('.component-indicator');
|
||||||
|
expect(badge).not.toBeNull();
|
||||||
|
expect(badge?.textContent).toContain('Heading');
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never shows a badge for ROOT even if "selected"', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.id = 'ROOT';
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(document.querySelector('.component-indicator')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('chevron click selects the parent node', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.parent = 'parent-42';
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
const chevron = document.querySelector('.component-indicator-parent-btn') as HTMLElement;
|
||||||
|
expect(chevron).not.toBeNull();
|
||||||
|
act(() => {
|
||||||
|
chevron.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
|
||||||
|
});
|
||||||
|
expect(selectNodeSpy).toHaveBeenCalledWith('parent-42');
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no chevron when there is no parent', () => {
|
||||||
|
mockNode.selected = true;
|
||||||
|
mockNode.parent = null;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(document.querySelector('.component-indicator-parent-btn')).toBeNull();
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
document.querySelector('.component-indicator')?.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tags a droppable (isCanvas) node dom with data-craft-node', () => {
|
||||||
|
mockNode.isCanvas = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(true);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not tag a non-canvas (leaf) node dom with data-craft-node', () => {
|
||||||
|
mockNode.isCanvas = false;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never tags ROOT with data-craft-node even though ROOT is a canvas', () => {
|
||||||
|
mockNode.id = 'ROOT';
|
||||||
|
mockNode.isCanvas = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-node')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tags the dom with data-craft-hovered when the Craft hovered event is set (Layers panel hover sync)', () => {
|
||||||
|
mockNode.hovered = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('removes data-craft-hovered once the hovered event clears', () => {
|
||||||
|
mockNode.hovered = true;
|
||||||
|
render(<RenderNode render={rendered} />);
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(true);
|
||||||
|
mockNode.hovered = false;
|
||||||
|
act(() => {
|
||||||
|
root.render(<RenderNode render={rendered} />);
|
||||||
|
});
|
||||||
|
expect(nodeDom.hasAttribute('data-craft-hovered')).toBe(false);
|
||||||
|
container.remove();
|
||||||
|
nodeDom.remove();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { useEditor, useNode } from '@craftjs/core';
|
||||||
|
|
||||||
|
interface RenderNodeProps {
|
||||||
|
render: React.ReactElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Craft.js `<Editor onRender>` override -- wraps every node's render output.
|
||||||
|
* For the currently-selected node it portals a floating badge (component
|
||||||
|
* displayName + a "select parent" chevron) positioned over the node's real
|
||||||
|
* DOM element. Non-selected nodes (the overwhelming majority) and ROOT pass
|
||||||
|
* straight through as a Fragment, so this never touches layout, never
|
||||||
|
* appears in `toHtml` export (that walks the Craft node tree, not this
|
||||||
|
* portal), and doesn't wrap every node in extra DOM.
|
||||||
|
*
|
||||||
|
* It also imperatively tags each node's real DOM element with two
|
||||||
|
* editor-only data attributes (never part of `toHtml` export, which walks
|
||||||
|
* the Craft node tree, not the live DOM):
|
||||||
|
* - `data-craft-node`: set on actual Craft.js droppable containers
|
||||||
|
* (`node.data.isCanvas`, excluding ROOT). `editor.css`'s dashed "guide"
|
||||||
|
* outlines target this attribute instead of blanket tag selectors
|
||||||
|
* (div/section/header/...), so a component's own internal wrapper markup
|
||||||
|
* no longer picks up a guide outline it isn't a real drop target for.
|
||||||
|
* - `data-craft-hovered`: mirrors `node.events.hovered` (Craft's hover
|
||||||
|
* event set). Craft's own `connectors.connect()` (called by every
|
||||||
|
* component) wires a native mouseover/mouseleave listener to this event
|
||||||
|
* internally, so a plain mouse hover over any connected node sets it --
|
||||||
|
* this attribute is a real-mouse-hover canvas highlight. (The Layers
|
||||||
|
* panel's row-hover -> canvas-highlight sync, item 12, uses a sibling
|
||||||
|
* `data-layer-hovered` attribute written directly by LayersPanel.tsx
|
||||||
|
* instead of this event, since the action that would drive it here
|
||||||
|
* -- `actions.setNodeEvent` -- is stripped from the public `useEditor()`
|
||||||
|
* API at runtime.) editor.css matches both attributes for the same
|
||||||
|
* outline and suppresses both under `.guides-off`.
|
||||||
|
*/
|
||||||
|
export const RenderNode: React.FC<RenderNodeProps> = ({ render }) => {
|
||||||
|
const { actions } = useEditor();
|
||||||
|
const { id, isSelected, dom, name, parent, isCanvas, isHovered } = useNode((node) => ({
|
||||||
|
isSelected: node.events.selected,
|
||||||
|
isHovered: node.events.hovered,
|
||||||
|
dom: node.dom,
|
||||||
|
name: (node.data.props?.aiName as string) || node.data.displayName,
|
||||||
|
parent: node.data.parent,
|
||||||
|
isCanvas: node.data.isCanvas,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const badgeRef = useRef<HTMLDivElement>(null);
|
||||||
|
const active = isSelected && id !== 'ROOT' && !!dom;
|
||||||
|
|
||||||
|
const updatePosition = useCallback(() => {
|
||||||
|
if (!dom || !badgeRef.current) return;
|
||||||
|
const rect = dom.getBoundingClientRect();
|
||||||
|
const badgeHeight = 22;
|
||||||
|
badgeRef.current.style.left = `${Math.max(rect.left, 0)}px`;
|
||||||
|
badgeRef.current.style.top = `${Math.max(rect.top - badgeHeight, 0)}px`;
|
||||||
|
}, [dom]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active) return;
|
||||||
|
updatePosition();
|
||||||
|
window.addEventListener('resize', updatePosition);
|
||||||
|
document.addEventListener('scroll', updatePosition, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('resize', updatePosition);
|
||||||
|
document.removeEventListener('scroll', updatePosition, true);
|
||||||
|
};
|
||||||
|
}, [active, updatePosition]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dom) return;
|
||||||
|
if (isCanvas && id !== 'ROOT') {
|
||||||
|
dom.setAttribute('data-craft-node', '');
|
||||||
|
} else {
|
||||||
|
dom.removeAttribute('data-craft-node');
|
||||||
|
}
|
||||||
|
}, [dom, isCanvas, id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dom) return;
|
||||||
|
if (isHovered) {
|
||||||
|
dom.setAttribute('data-craft-hovered', '');
|
||||||
|
} else {
|
||||||
|
dom.removeAttribute('data-craft-hovered');
|
||||||
|
}
|
||||||
|
}, [dom, isHovered]);
|
||||||
|
|
||||||
|
if (!active) return <>{render}</>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{render}
|
||||||
|
{createPortal(
|
||||||
|
<div ref={badgeRef} className="component-indicator" style={{ position: 'fixed' }}>
|
||||||
|
<span>{name}</span>
|
||||||
|
{parent && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="component-indicator-parent-btn"
|
||||||
|
title="Select parent"
|
||||||
|
aria-label={`Select parent of ${name}`}
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
actions.selectNode(parent);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-chevron-up" aria-hidden />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>,
|
||||||
|
document.body
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { useIsMobile } from './useIsMobile';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): useIsMobile is the single source of truth every
|
||||||
|
* mobile-only branch (bottom tab bar, collapsed topbar, bottom sheets) reads
|
||||||
|
* from, so it needs direct coverage of: (a) it reflects matchMedia's
|
||||||
|
* `matches`, (b) the `change` listener is registered AND cleaned up on
|
||||||
|
* unmount (a leaked listener would keep re-rendering an unmounted tree /
|
||||||
|
* leak the component instance), and (c) the legacy Safari<14
|
||||||
|
* addListener/removeListener fallback is used when addEventListener isn't
|
||||||
|
* available.
|
||||||
|
*
|
||||||
|
* DOM-harness pattern mirrors PageContext.pure-updaters.test.tsx /
|
||||||
|
* useKeyboardShortcuts.test.tsx: bare createRoot + act, no @testing-library
|
||||||
|
* (not a project dependency).
|
||||||
|
*/
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let originalMatchMedia: typeof window.matchMedia;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A minimal fake MediaQueryList. `mode` picks which listener API it
|
||||||
|
* exposes, so tests can force the legacy fallback path. */
|
||||||
|
function makeMql(matches: boolean, mode: 'modern' | 'legacy' = 'modern') {
|
||||||
|
const listeners: Array<() => void> = [];
|
||||||
|
const mql: any = {
|
||||||
|
matches,
|
||||||
|
media: '(max-width: 768px)',
|
||||||
|
};
|
||||||
|
if (mode === 'modern') {
|
||||||
|
mql.addEventListener = vi.fn((_type: string, fn: () => void) => listeners.push(fn));
|
||||||
|
mql.removeEventListener = vi.fn((_type: string, fn: () => void) => {
|
||||||
|
const i = listeners.indexOf(fn);
|
||||||
|
if (i !== -1) listeners.splice(i, 1);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
mql.addListener = vi.fn((fn: () => void) => listeners.push(fn));
|
||||||
|
mql.removeListener = vi.fn((fn: () => void) => {
|
||||||
|
const i = listeners.indexOf(fn);
|
||||||
|
if (i !== -1) listeners.splice(i, 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { mql, fire: () => listeners.forEach((fn) => fn()), listenerCount: () => listeners.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
let probedValue: boolean | null = null;
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probedValue = useIsMobile();
|
||||||
|
return <span data-value={String(probedValue)} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalMatchMedia = window.matchMedia;
|
||||||
|
probedValue = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
window.matchMedia = originalMatchMedia;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useIsMobile', () => {
|
||||||
|
test('returns true when the mobile media query matches', () => {
|
||||||
|
const { mql } = makeMql(true);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns false when the mobile media query does not match', () => {
|
||||||
|
const { mql } = makeMql(false);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registers the change listener via addEventListener and updates on change', () => {
|
||||||
|
const { mql, fire, listenerCount } = makeMql(false);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
expect(mql.addEventListener).toHaveBeenCalledWith('change', expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
// Flip the query result and fire the registered 'change' listener --
|
||||||
|
// the hook must re-read mql.matches, not just toggle blindly.
|
||||||
|
mql.matches = true;
|
||||||
|
act(() => {
|
||||||
|
fire();
|
||||||
|
});
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cleans up the addEventListener listener on unmount', () => {
|
||||||
|
const { mql, listenerCount } = makeMql(true);
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(mql.removeEventListener).toHaveBeenCalledWith('change', expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to legacy addListener/removeListener when addEventListener is unavailable', () => {
|
||||||
|
const { mql, fire, listenerCount } = makeMql(false, 'legacy');
|
||||||
|
window.matchMedia = vi.fn(() => mql) as any;
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
expect(probedValue).toBe(false);
|
||||||
|
expect(mql.addListener).toHaveBeenCalledWith(expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(1);
|
||||||
|
|
||||||
|
mql.matches = true;
|
||||||
|
act(() => {
|
||||||
|
fire();
|
||||||
|
});
|
||||||
|
expect(probedValue).toBe(true);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(mql.removeListener).toHaveBeenCalledWith(expect.any(Function));
|
||||||
|
expect(listenerCount()).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
/** Mobile breakpoint for the editor chrome (Phase A). Keep in sync with the
|
||||||
|
* `@media (max-width: 768px)` block in `src/styles/editor.css` -- both the
|
||||||
|
* CSS and this hook must agree on where mobile chrome kicks in. */
|
||||||
|
export const MOBILE_BREAKPOINT_PX = 768;
|
||||||
|
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT_PX}px)`;
|
||||||
|
|
||||||
|
function computeIsMobile(): boolean {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
if (typeof window.matchMedia === 'function') {
|
||||||
|
try {
|
||||||
|
return window.matchMedia(MOBILE_QUERY).matches;
|
||||||
|
} catch {
|
||||||
|
// Fall through to the width check below (e.g. some older/embedded
|
||||||
|
// WebViews expose a matchMedia that throws instead of omitting it).
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return window.innerWidth <= MOBILE_BREAKPOINT_PX;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reports whether the viewport is at or below the mobile editor breakpoint.
|
||||||
|
* Drives every mobile-only branch introduced in Phase A (bottom tab bar,
|
||||||
|
* collapsed topbar, bottom sheets) -- desktop rendering must stay identical
|
||||||
|
* above the breakpoint, so this is the single source of truth both React
|
||||||
|
* and (via the matching CSS media query) plain CSS use to agree on "mobile".
|
||||||
|
*
|
||||||
|
* Falls back to a `resize` listener + `window.innerWidth` when
|
||||||
|
* `matchMedia` isn't available (e.g. some test/JSDOM environments), so the
|
||||||
|
* hook degrades gracefully rather than throwing.
|
||||||
|
*/
|
||||||
|
export function useIsMobile(): boolean {
|
||||||
|
const [isMobile, setIsMobile] = useState<boolean>(computeIsMobile);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
if (typeof window.matchMedia === 'function') {
|
||||||
|
let mql: MediaQueryList | null = null;
|
||||||
|
try {
|
||||||
|
mql = window.matchMedia(MOBILE_QUERY);
|
||||||
|
} catch {
|
||||||
|
mql = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mql) {
|
||||||
|
const handleChange = () => setIsMobile(mql!.matches);
|
||||||
|
handleChange();
|
||||||
|
|
||||||
|
if (typeof mql.addEventListener === 'function') {
|
||||||
|
mql.addEventListener('change', handleChange);
|
||||||
|
return () => mql!.removeEventListener('change', handleChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Safari < 14 only supports the deprecated addListener/removeListener pair.
|
||||||
|
const legacyMql = mql as MediaQueryList & {
|
||||||
|
addListener?: (listener: () => void) => void;
|
||||||
|
removeListener?: (listener: () => void) => void;
|
||||||
|
};
|
||||||
|
legacyMql.addListener?.(handleChange);
|
||||||
|
return () => legacyMql.removeListener?.(handleChange);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleResize = () => setIsMobile(window.innerWidth <= MOBILE_BREAKPOINT_PX);
|
||||||
|
window.addEventListener('resize', handleResize);
|
||||||
|
return () => window.removeEventListener('resize', handleResize);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return isMobile;
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import type { NodeTree, Node } from '@craftjs/core';
|
||||||
|
import { useNodeActions, type NodeActions } from './useNodeActions';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase B, item 1: `useNodeActions` was extracted out of `ContextMenu.tsx` so
|
||||||
|
* the desktop right-click menu and the mobile selection toolbar
|
||||||
|
* (`MobileSelectionToolbar`) share one implementation. This suite exercises
|
||||||
|
* the hook directly (mocking `@craftjs/core`'s `useEditor`, mirroring the
|
||||||
|
* pattern in `useKeyboardShortcuts.test.tsx`), covering:
|
||||||
|
* - moveUp/moveDown call `actions.move` with the right target index, and
|
||||||
|
* are no-ops at the respective boundary
|
||||||
|
* - canMoveUp/canMoveDown reflect the node's position among its siblings
|
||||||
|
* - duplicate regenerates ids, inserts the copy IMMEDIATELY AFTER the
|
||||||
|
* source node (`actions.addNodeTree(tree, parentId, sourceIndex + 1)`),
|
||||||
|
* and selects the new copy (`actions.selectNode(tree.rootNodeId)`) --
|
||||||
|
* Phase B fast-follow: the previous append-at-end behavior left the copy
|
||||||
|
* off-screen with the ORIGINAL still selected, so users couldn't see
|
||||||
|
* what "Duplicate" had just done.
|
||||||
|
* - selectParent calls `actions.selectNode` with the parent id
|
||||||
|
* - canSelectParent reflects whether the node's parent is itself real
|
||||||
|
* (not ROOT/missing) -- false at a top-level section, true one level in
|
||||||
|
* - deleteNode routes through `findDeletableTarget` (also covering the
|
||||||
|
* "no deletable target" no-op)
|
||||||
|
* - ROOT/null nodeId disables every action safely (no-ops, all
|
||||||
|
* canMoveUp/canMoveDown/canDelete/canSelectParent false)
|
||||||
|
*/
|
||||||
|
|
||||||
|
const moveMock = vi.fn();
|
||||||
|
const addNodeTreeMock = vi.fn();
|
||||||
|
const selectNodeMock = vi.fn();
|
||||||
|
const deleteMock = vi.fn();
|
||||||
|
|
||||||
|
interface FakeNodeData {
|
||||||
|
parent: string | null;
|
||||||
|
nodes: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
let fakeNodes: Record<string, { data: FakeNodeData }> = {};
|
||||||
|
|
||||||
|
const COPIED_TREE: NodeTree = {
|
||||||
|
rootNodeId: 'child-1',
|
||||||
|
nodes: {
|
||||||
|
'child-1': {
|
||||||
|
id: 'child-1',
|
||||||
|
data: { props: {}, type: { resolvedName: 'Container' }, name: 'Container', displayName: 'Container', isCanvas: false, parent: 'parent-1', linkedNodes: {}, nodes: [], hidden: false },
|
||||||
|
info: {},
|
||||||
|
events: { selected: false, dragged: false, hovered: false },
|
||||||
|
dom: null,
|
||||||
|
related: {},
|
||||||
|
rules: {},
|
||||||
|
_hydrationTimestamp: 0,
|
||||||
|
} as unknown as Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function makeQuery() {
|
||||||
|
return {
|
||||||
|
node: (id: string) => ({
|
||||||
|
get: () => fakeNodes[id] ?? null,
|
||||||
|
toNodeTree: () => {
|
||||||
|
if (id !== 'child-1') throw new Error(`unexpected toNodeTree() for "${id}"`);
|
||||||
|
return COPIED_TREE;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: (collector?: (state: any, query: any) => any) => {
|
||||||
|
const state = {
|
||||||
|
nodes: Object.fromEntries(Object.entries(fakeNodes).map(([id, n]) => [id, n])),
|
||||||
|
};
|
||||||
|
const query = makeQuery();
|
||||||
|
const collected = collector ? collector(state, query) : {};
|
||||||
|
return {
|
||||||
|
...collected,
|
||||||
|
actions: {
|
||||||
|
move: moveMock,
|
||||||
|
addNodeTree: addNodeTreeMock,
|
||||||
|
selectNode: selectNodeMock,
|
||||||
|
delete: deleteMock,
|
||||||
|
},
|
||||||
|
query,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../utils/craft-tree', async (importOriginal) => {
|
||||||
|
const actual = await importOriginal<typeof import('../utils/craft-tree')>();
|
||||||
|
return { ...actual, regenerateTreeIds: vi.fn(actual.regenerateTreeIds) };
|
||||||
|
});
|
||||||
|
|
||||||
|
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||||
|
const regenerateTreeIdsMock = vi.mocked(regenerateTreeIds);
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let captured: NodeActions | null = null;
|
||||||
|
|
||||||
|
const Probe: React.FC<{ nodeId: string | null }> = ({ nodeId }) => {
|
||||||
|
captured = useNodeActions(nodeId);
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function render(nodeId: string | null) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(<Probe nodeId={nodeId} />);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function rerender(nodeId: string | null) {
|
||||||
|
act(() => {
|
||||||
|
root.render(<Probe nodeId={nodeId} />);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
moveMock.mockClear();
|
||||||
|
addNodeTreeMock.mockClear();
|
||||||
|
selectNodeMock.mockClear();
|
||||||
|
deleteMock.mockClear();
|
||||||
|
regenerateTreeIdsMock.mockClear();
|
||||||
|
captured = null;
|
||||||
|
fakeNodes = {
|
||||||
|
ROOT: { data: { parent: null, nodes: ['parent-1'] } },
|
||||||
|
'parent-1': { data: { parent: 'ROOT', nodes: ['child-0', 'child-1', 'child-2'] } },
|
||||||
|
'child-0': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
'child-1': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
'child-2': { data: { parent: 'parent-1', nodes: [] } },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (root) unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useNodeActions', () => {
|
||||||
|
test('a middle child can move both up and down', () => {
|
||||||
|
render('child-1');
|
||||||
|
expect(captured!.canMoveUp).toBe(true);
|
||||||
|
expect(captured!.canMoveDown).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the first child cannot move up, but can move down', () => {
|
||||||
|
render('child-0');
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the last child can move up, but not down', () => {
|
||||||
|
render('child-2');
|
||||||
|
expect(captured!.canMoveUp).toBe(true);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveUp calls actions.move with idx - 1, moveDown with idx + 2 (Craft.js index semantics)', () => {
|
||||||
|
render('child-1');
|
||||||
|
act(() => captured!.moveUp());
|
||||||
|
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 0);
|
||||||
|
|
||||||
|
moveMock.mockClear();
|
||||||
|
act(() => captured!.moveDown());
|
||||||
|
expect(moveMock).toHaveBeenCalledWith('child-1', 'parent-1', 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveUp/moveDown at a boundary are no-ops', () => {
|
||||||
|
render('child-0');
|
||||||
|
act(() => captured!.moveUp());
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
rerender('child-2');
|
||||||
|
act(() => captured!.moveDown());
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('duplicate inserts the copy immediately after the source (parentId, sourceIndex + 1) and selects it', () => {
|
||||||
|
render('child-1');
|
||||||
|
let returned: string | null | undefined;
|
||||||
|
act(() => {
|
||||||
|
returned = captured!.duplicate();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(regenerateTreeIdsMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(addNodeTreeMock).toHaveBeenCalledTimes(1);
|
||||||
|
const [tree, parentId, index] = addNodeTreeMock.mock.calls[0];
|
||||||
|
// child-1 is at index 1 among ['child-0', 'child-1', 'child-2'] -> insert at 2.
|
||||||
|
expect(parentId).toBe('parent-1');
|
||||||
|
expect(index).toBe(2);
|
||||||
|
expect(tree.rootNodeId).not.toBe(COPIED_TREE.rootNodeId);
|
||||||
|
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledTimes(1);
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledWith(tree.rootNodeId);
|
||||||
|
expect(returned).toBe(tree.rootNodeId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('selectParent calls actions.selectNode with the parent id', () => {
|
||||||
|
render('child-1');
|
||||||
|
act(() => captured!.selectParent());
|
||||||
|
expect(selectNodeMock).toHaveBeenCalledWith('parent-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('canSelectParent is false at a top-level node (parent is ROOT), true one level deeper', () => {
|
||||||
|
render('parent-1'); // parent-1's own parent is 'ROOT'
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
|
||||||
|
rerender('child-1'); // child-1's parent is 'parent-1', a real node
|
||||||
|
expect(captured!.canSelectParent).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleteNode calls actions.delete with the node id when deletable', () => {
|
||||||
|
render('child-1');
|
||||||
|
expect(captured!.canDelete).toBe(true);
|
||||||
|
act(() => captured!.deleteNode());
|
||||||
|
expect(deleteMock).toHaveBeenCalledWith('child-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ROOT nodeId disables every action and is a safe no-op', () => {
|
||||||
|
render('ROOT');
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
expect(captured!.canDelete).toBe(false);
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
captured!.moveUp();
|
||||||
|
captured!.moveDown();
|
||||||
|
captured!.duplicate();
|
||||||
|
captured!.selectParent();
|
||||||
|
captured!.deleteNode();
|
||||||
|
});
|
||||||
|
expect(moveMock).not.toHaveBeenCalled();
|
||||||
|
expect(addNodeTreeMock).not.toHaveBeenCalled();
|
||||||
|
expect(selectNodeMock).not.toHaveBeenCalled();
|
||||||
|
expect(deleteMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('null nodeId disables every action and is a safe no-op', () => {
|
||||||
|
render(null);
|
||||||
|
expect(captured!.canMoveUp).toBe(false);
|
||||||
|
expect(captured!.canMoveDown).toBe(false);
|
||||||
|
expect(captured!.canDelete).toBe(false);
|
||||||
|
expect(captured!.canSelectParent).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { regenerateTreeIds } from '../utils/craft-tree';
|
||||||
|
import { findDeletableTarget } from '../utils/craft-helpers';
|
||||||
|
|
||||||
|
export interface NodeActions {
|
||||||
|
moveUp: () => void;
|
||||||
|
moveDown: () => void;
|
||||||
|
/** Duplicates `nodeId`, inserting the copy immediately after the source in
|
||||||
|
* the parent's children and selecting it. Returns the new node's id (so
|
||||||
|
* callers -- e.g. `MobileSelectionToolbar` -- can scroll it into view),
|
||||||
|
* or null if the duplicate could not be performed (no-op for ROOT/null,
|
||||||
|
* or a caught error). */
|
||||||
|
duplicate: () => string | null;
|
||||||
|
deleteNode: () => void;
|
||||||
|
selectParent: () => void;
|
||||||
|
/** True if `nodeId` has an earlier sibling under the same parent (so
|
||||||
|
* `moveUp` would actually move it). False for ROOT/null/no-parent. */
|
||||||
|
canMoveUp: boolean;
|
||||||
|
/** True if `nodeId` has a later sibling under the same parent (so
|
||||||
|
* `moveDown` would actually move it). False for ROOT/null/no-parent. */
|
||||||
|
canMoveDown: boolean;
|
||||||
|
/** True if `findDeletableTarget` resolves to a real, deletable node (either
|
||||||
|
* `nodeId` itself, or an ancestor when `nodeId` is an empty linked-node
|
||||||
|
* slot whose siblings are all also empty -- see `craft-helpers.ts`). */
|
||||||
|
canDelete: boolean;
|
||||||
|
/** True if `nodeId` has a real parent to select -- i.e. the parent is
|
||||||
|
* neither ROOT nor missing. `selectParent` on a top-level section (whose
|
||||||
|
* parent IS 'ROOT') would only select the page-wide ROOT node, which has
|
||||||
|
* no on-canvas outline and no toolbar of its own -- a dead end for a
|
||||||
|
* mobile user with no way back. False for ROOT/null/no-parent too. */
|
||||||
|
canSelectParent: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared node-action logic (move up/down, duplicate, delete, select parent)
|
||||||
|
* extracted from `ContextMenu.tsx` (Phase B) so both the desktop right-click
|
||||||
|
* menu AND the mobile on-canvas selection toolbar (`MobileSelectionToolbar`)
|
||||||
|
* drive the exact same behavior from one place instead of two independent
|
||||||
|
* copies drifting apart.
|
||||||
|
*
|
||||||
|
* IMPORTANT gotcha this hook works around: `@craftjs/core`'s `useEditor`
|
||||||
|
* collector (`@craftjs/utils`' `useCollector`) only synchronously computes
|
||||||
|
* the collector function ONCE, on this hook's very first mount. After that,
|
||||||
|
* it updates purely in reaction to the underlying store's OWN change
|
||||||
|
* notifications, invoking whatever collector closure is current AT THAT
|
||||||
|
* NOTIFICATION -- so a collector that closes over `nodeId` (an argument that
|
||||||
|
* changes across renders of the SAME mounted hook instance, e.g. every time
|
||||||
|
* `MobileSelectionToolbar` re-renders with a newly-selected node) goes stale
|
||||||
|
* for exactly one render: the cached value from the last store notification
|
||||||
|
* (computed against the PREVIOUS nodeId) is what gets returned, until some
|
||||||
|
* unrelated store event happens to trigger a fresh computation. An earlier
|
||||||
|
* version of this hook computed `canMoveUp`/`canMoveDown`/`canDelete` inside
|
||||||
|
* such a collector and was caught showing the PREVIOUS selection's move
|
||||||
|
* boundaries in the mobile toolbar for one render after tapping a new node
|
||||||
|
* (verified with real Playwright touch taps against a real Craft.js
|
||||||
|
* document -- a plain mocked `useEditor` in a unit test doesn't reproduce
|
||||||
|
* this, since a hand-rolled mock has no reason to replicate the real
|
||||||
|
* library's caching).
|
||||||
|
*
|
||||||
|
* The fix: get `actions`/`query` from a collector-FREE `useEditor()` call
|
||||||
|
* (an always-live reference, same pattern `ContextMenu.tsx` used before this
|
||||||
|
* extraction) and compute `canMoveUp`/`canMoveDown`/`canDelete` as plain
|
||||||
|
* synchronous code during render using that live `query` -- never cached.
|
||||||
|
*
|
||||||
|
* That still leaves one gap: `nodeId` staying the SAME across renders while
|
||||||
|
* its position changes (e.g. tapping "Move Up" repeatedly on the same
|
||||||
|
* still-selected node) needs SOMETHING to trigger a re-render so the boundary
|
||||||
|
* flags below get recomputed. An earlier version of this hook forced that
|
||||||
|
* via a second `useEditor((state) => ({ _: state.nodes }))` subscription --
|
||||||
|
* but subscribing to the WHOLE node map reacts to every `dom` ref
|
||||||
|
* assignment too (Craft's `connectors.connect(ref)` calls `actions.setDOM`
|
||||||
|
* synchronously from a React ref callback during COMMIT, i.e. while some
|
||||||
|
* OTHER component is still mounting), which trips React's "Cannot update a
|
||||||
|
* component while rendering a different component" warning the moment a
|
||||||
|
* freshly-added container with children mounts. Callers that need
|
||||||
|
* `canMoveUp`/`canMoveDown` to refresh after a move they themselves
|
||||||
|
* triggered (`MobileSelectionToolbar`) should instead bump their OWN local
|
||||||
|
* state right after calling `moveUp`/`moveDown` -- a plain, local,
|
||||||
|
* event-handler-triggered re-render, not a store-wide subscription.
|
||||||
|
*/
|
||||||
|
export function useNodeActions(nodeId: string | null | undefined): NodeActions {
|
||||||
|
const { actions, query } = useEditor();
|
||||||
|
|
||||||
|
const isRootOrNull = !nodeId || nodeId === 'ROOT';
|
||||||
|
|
||||||
|
let canMoveUp = false;
|
||||||
|
let canMoveDown = false;
|
||||||
|
let canSelectParent = false;
|
||||||
|
if (!isRootOrNull) {
|
||||||
|
try {
|
||||||
|
const node = query.node(nodeId).get();
|
||||||
|
const parentId: string | null | undefined = node?.data?.parent;
|
||||||
|
if (parentId) {
|
||||||
|
canSelectParent = parentId !== 'ROOT';
|
||||||
|
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
|
||||||
|
const idx = siblings.indexOf(nodeId);
|
||||||
|
canMoveUp = idx > 0;
|
||||||
|
canMoveDown = idx !== -1 && idx < siblings.length - 1;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Node no longer exists (e.g. deleted out from under a stale
|
||||||
|
// reference) -- leave both false.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canDelete = !isRootOrNull && !!findDeletableTarget(query, nodeId);
|
||||||
|
|
||||||
|
const getParentId = (): string | null => {
|
||||||
|
if (!nodeId) return null;
|
||||||
|
try {
|
||||||
|
const node = query.node(nodeId).get();
|
||||||
|
return node?.data?.parent || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const duplicate = (): string | null => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return null;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return null;
|
||||||
|
|
||||||
|
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree());
|
||||||
|
|
||||||
|
// Insert the copy IMMEDIATELY AFTER the source node, not appended at
|
||||||
|
// the end of the parent -- on a top-level section, "append at end"
|
||||||
|
// landed the copy at the bottom of the page, off-screen, with the
|
||||||
|
// ORIGINAL still selected, so a duplicate looked like nothing had
|
||||||
|
// happened at all. Resolve the source's index among its siblings so
|
||||||
|
// the copy lands right next to what it was copied from; if that can't
|
||||||
|
// be resolved for any reason, fall back to the old append behavior
|
||||||
|
// rather than guessing at an index (or throwing).
|
||||||
|
let insertIndex: number | undefined;
|
||||||
|
try {
|
||||||
|
const siblings: string[] = query.node(parentId).get()?.data?.nodes || [];
|
||||||
|
const sourceIndex = siblings.indexOf(nodeId);
|
||||||
|
if (sourceIndex !== -1) insertIndex = sourceIndex + 1;
|
||||||
|
} catch {
|
||||||
|
// Leave insertIndex undefined -- addNodeTree appends when omitted.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (insertIndex !== undefined) {
|
||||||
|
actions.addNodeTree(tree, parentId, insertIndex);
|
||||||
|
} else {
|
||||||
|
actions.addNodeTree(tree, parentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Select the new copy (not the original) so the toolbar/context menu
|
||||||
|
// and any on-canvas outline immediately reflect what was just created.
|
||||||
|
actions.selectNode(tree.rootNodeId);
|
||||||
|
|
||||||
|
return tree.rootNodeId;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Duplicate failed:', e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveUp = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return;
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const children = parent.data.nodes || [];
|
||||||
|
const idx = children.indexOf(nodeId);
|
||||||
|
if (idx > 0) {
|
||||||
|
actions.move(nodeId, parentId, idx - 1);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Move up failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveDown = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
try {
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (!parentId) return;
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const children = parent.data.nodes || [];
|
||||||
|
const idx = children.indexOf(nodeId);
|
||||||
|
if (idx < children.length - 1) {
|
||||||
|
actions.move(nodeId, parentId, idx + 2);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Move down failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectParent = () => {
|
||||||
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
|
const parentId = getParentId();
|
||||||
|
if (parentId) {
|
||||||
|
actions.selectNode(parentId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteNode = () => {
|
||||||
|
const target = findDeletableTarget(query, nodeId);
|
||||||
|
if (!target) return;
|
||||||
|
try {
|
||||||
|
actions.delete(target);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Delete failed:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
moveUp,
|
||||||
|
moveDown,
|
||||||
|
duplicate,
|
||||||
|
deleteNode,
|
||||||
|
selectParent,
|
||||||
|
canMoveUp,
|
||||||
|
canMoveDown,
|
||||||
|
canDelete,
|
||||||
|
canSelectParent,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { useVisualViewportInsets } from './useVisualViewport';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fast-follow coverage for `useVisualViewportInsets` (BottomSheet's
|
||||||
|
* keyboard-avoidance source of truth). Mirrors the bare createRoot + act
|
||||||
|
* harness `useIsMobile.test.tsx` uses (no @testing-library/react in this
|
||||||
|
* repo). Covers:
|
||||||
|
* - the no-`visualViewport` fallback (older WebViews) returns
|
||||||
|
* `{ height: window.innerHeight, keyboardInset: 0 }` AND registers no
|
||||||
|
* listener (there's nothing to listen to).
|
||||||
|
* - the keyboard-open math: `keyboardInset = innerHeight - (vv.height +
|
||||||
|
* vv.offsetTop)`, recomputed when the mocked vv fires `resize`.
|
||||||
|
* - both `resize` and `scroll` listeners are added on mount and the SAME
|
||||||
|
* handler is removed for both on unmount (a leaked listener would keep
|
||||||
|
* reacting after the owning component -- e.g. BottomSheet -- is gone).
|
||||||
|
*/
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
let originalInnerHeight: number;
|
||||||
|
let originalVisualViewport: VisualViewport | null;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A minimal fake `visualViewport`: just enough surface for the hook
|
||||||
|
* (`height`, `offsetTop`, `addEventListener`/`removeEventListener`). */
|
||||||
|
function makeVisualViewport(height: number, offsetTop: number) {
|
||||||
|
const listeners: Record<string, Array<() => void>> = { resize: [], scroll: [] };
|
||||||
|
const vv: any = {
|
||||||
|
height,
|
||||||
|
offsetTop,
|
||||||
|
addEventListener: vi.fn((type: string, fn: () => void) => {
|
||||||
|
listeners[type].push(fn);
|
||||||
|
}),
|
||||||
|
removeEventListener: vi.fn((type: string, fn: () => void) => {
|
||||||
|
const i = listeners[type].indexOf(fn);
|
||||||
|
if (i !== -1) listeners[type].splice(i, 1);
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
vv,
|
||||||
|
fire: (type: 'resize' | 'scroll') => listeners[type].forEach((fn) => fn()),
|
||||||
|
listenerCount: (type: 'resize' | 'scroll') => listeners[type].length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let probed: { height: number; keyboardInset: number } | null = null;
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probed = useVisualViewportInsets();
|
||||||
|
return <span data-height={probed.height} data-inset={probed.keyboardInset} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
originalInnerHeight = window.innerHeight;
|
||||||
|
originalVisualViewport = window.visualViewport;
|
||||||
|
probed = null;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', {
|
||||||
|
value: originalInnerHeight,
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
Object.defineProperty(window, 'visualViewport', {
|
||||||
|
value: originalVisualViewport,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useVisualViewportInsets', () => {
|
||||||
|
test('falls back to innerHeight/0 and registers no listener when visualViewport is undefined', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: undefined, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('computes keyboardInset from visualViewport and recomputes on resize', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
const { vv, fire } = makeVisualViewport(800, 0);
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
// No keyboard open: vv fills the layout viewport exactly.
|
||||||
|
expect(probed).toEqual({ height: 800, keyboardInset: 0 });
|
||||||
|
|
||||||
|
// Simulate the on-screen keyboard opening: the visual viewport shrinks.
|
||||||
|
vv.height = 500;
|
||||||
|
vv.offsetTop = 0;
|
||||||
|
act(() => {
|
||||||
|
fire('resize');
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(probed).toEqual({ height: 500, keyboardInset: 300 });
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registers resize and scroll listeners on mount and removes both (same handler) on unmount', () => {
|
||||||
|
Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true, writable: true });
|
||||||
|
const { vv, listenerCount } = makeVisualViewport(800, 0);
|
||||||
|
Object.defineProperty(window, 'visualViewport', { value: vv, configurable: true });
|
||||||
|
|
||||||
|
render(<Probe />);
|
||||||
|
|
||||||
|
expect(vv.addEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
|
||||||
|
expect(vv.addEventListener).toHaveBeenCalledWith('scroll', expect.any(Function));
|
||||||
|
expect(listenerCount('resize')).toBe(1);
|
||||||
|
expect(listenerCount('scroll')).toBe(1);
|
||||||
|
|
||||||
|
const resizeHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'resize')[1];
|
||||||
|
const scrollHandler = vv.addEventListener.mock.calls.find((c: any[]) => c[0] === 'scroll')[1];
|
||||||
|
expect(resizeHandler).toBe(scrollHandler);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
expect(vv.removeEventListener).toHaveBeenCalledWith('resize', resizeHandler);
|
||||||
|
expect(vv.removeEventListener).toHaveBeenCalledWith('scroll', scrollHandler);
|
||||||
|
expect(listenerCount('resize')).toBe(0);
|
||||||
|
expect(listenerCount('scroll')).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
export interface VisualViewportInsets {
|
||||||
|
/** The visual viewport's current height (shrinks when the on-screen
|
||||||
|
* keyboard opens). Falls back to `window.innerHeight` when
|
||||||
|
* `visualViewport` isn't supported. */
|
||||||
|
height: number;
|
||||||
|
/** Extra inset a `position: fixed`, bottom-anchored element should add to
|
||||||
|
* its own `bottom` offset to stay clear of the on-screen keyboard --
|
||||||
|
* `window.innerHeight` minus the visual viewport's bottom edge (its
|
||||||
|
* height + offsetTop). Zero whenever no keyboard is open, or
|
||||||
|
* `visualViewport` isn't supported (a safe no-op fallback). */
|
||||||
|
keyboardInset: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ZERO_INSETS: VisualViewportInsets = { height: 0, keyboardInset: 0 };
|
||||||
|
|
||||||
|
function computeInsets(): VisualViewportInsets {
|
||||||
|
if (typeof window === 'undefined') return ZERO_INSETS;
|
||||||
|
const vv = window.visualViewport;
|
||||||
|
if (!vv) return { height: window.innerHeight, keyboardInset: 0 };
|
||||||
|
const keyboardInset = Math.max(0, window.innerHeight - (vv.height + vv.offsetTop));
|
||||||
|
return { height: vv.height, keyboardInset };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tracks `window.visualViewport`'s height/offset (item 5, Phase B) so
|
||||||
|
* `BottomSheet` can stay clear of the on-screen keyboard. `position: fixed`
|
||||||
|
* elements are positioned against the LAYOUT viewport, which does NOT shrink
|
||||||
|
* when a mobile keyboard opens -- only the visual viewport does -- so a
|
||||||
|
* bottom-anchored sheet's inputs can otherwise end up hidden underneath the
|
||||||
|
* keyboard with no visual indication anything is wrong.
|
||||||
|
*
|
||||||
|
* Guards for browsers without `visualViewport` (older WebViews): falls back
|
||||||
|
* to `{ height: window.innerHeight, keyboardInset: 0 }`, i.e. a no-op, so
|
||||||
|
* the sheet just keeps its existing (keyboard-unaware) sizing there.
|
||||||
|
*/
|
||||||
|
export function useVisualViewportInsets(): VisualViewportInsets {
|
||||||
|
const [insets, setInsets] = useState<VisualViewportInsets>(computeInsets);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === 'undefined' || !window.visualViewport) return;
|
||||||
|
const vv = window.visualViewport;
|
||||||
|
const handleChange = () => setInsets(computeInsets());
|
||||||
|
handleChange();
|
||||||
|
vv.addEventListener('resize', handleChange);
|
||||||
|
vv.addEventListener('scroll', handleChange);
|
||||||
|
return () => {
|
||||||
|
vv.removeEventListener('resize', handleChange);
|
||||||
|
vv.removeEventListener('scroll', handleChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return insets;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { buildSavePayload } from './useWhpApi';
|
import { buildSavePayload } from './useWhpApi';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
import { DEFAULT_SITE_DESIGN } from '../state/SiteDesignContext';
|
||||||
|
|
||||||
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
const pageA: PageData = { id: 'home', name: 'Home', slug: 'index', craftState: 'STORED_HOME' };
|
||||||
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
const pageB: PageData = { id: 'page_2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT' };
|
||||||
@@ -19,6 +20,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__header__',
|
activePageId: '__header__',
|
||||||
isEditingHeader: true,
|
isEditingHeader: true,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
// The fresh live canvas must be reflected in header_craft_state, not the stale stored one.
|
||||||
@@ -52,6 +55,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: '__footer__',
|
activePageId: '__footer__',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: true,
|
isEditingFooter: true,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
expect(payload.footer_craft_state).toBe('LIVE_FOOTER');
|
||||||
@@ -75,6 +80,8 @@ describe('buildSavePayload', () => {
|
|||||||
activePageId: 'home',
|
activePageId: 'home',
|
||||||
isEditingHeader: false,
|
isEditingHeader: false,
|
||||||
isEditingFooter: false,
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Live canvas goes to the active page and top-level slots.
|
// Live canvas goes to the active page and top-level slots.
|
||||||
@@ -87,4 +94,57 @@ describe('buildSavePayload', () => {
|
|||||||
expect(payload.header_craft_state).toBe('STALE_HEADER');
|
expect(payload.header_craft_state).toBe('STALE_HEADER');
|
||||||
expect(payload.footer_craft_state).toBe('STALE_FOOTER');
|
expect(payload.footer_craft_state).toBe('STALE_FOOTER');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('I-1: activePageId matches no page (dangling, e.g. original Home deleted then reload reset it to "home") -- live serialize still lands in pages_craft_state[0] / index.html, not lost', () => {
|
||||||
|
// pages[0] has id 'page_x' (the replacement landing page after the
|
||||||
|
// original 'home' was deleted); activePageId is stuck at the stale
|
||||||
|
// default 'home', which matches no entry in `pages`.
|
||||||
|
const pageX: PageData = { id: 'page_x', name: 'Home', slug: 'index', craftState: 'STORED_X' };
|
||||||
|
const p2: PageData = { id: 'p2', name: 'About', slug: 'about', craftState: 'STORED_ABOUT_2' };
|
||||||
|
|
||||||
|
const payload = buildSavePayload({
|
||||||
|
siteId: 1,
|
||||||
|
siteName: 'Test Site',
|
||||||
|
liveCraftState: 'LIVE_EDIT',
|
||||||
|
pages: [pageX, p2],
|
||||||
|
headerPage,
|
||||||
|
footerPage,
|
||||||
|
activePageId: 'home',
|
||||||
|
isEditingHeader: false,
|
||||||
|
isEditingFooter: false,
|
||||||
|
headCode: DEFAULT_SITE_DESIGN.headCode,
|
||||||
|
design: DEFAULT_SITE_DESIGN,
|
||||||
|
});
|
||||||
|
|
||||||
|
// The live edit must land in pages_craft_state[0] (index.html slot),
|
||||||
|
// not be silently dropped to only the legacy top-level fields.
|
||||||
|
expect(payload.pages_craft_state[0].craftState).toBe('LIVE_EDIT');
|
||||||
|
expect(payload.pages[0].filename).toBe('index.html');
|
||||||
|
// Top-level fields (legacy) should also reflect the live edit.
|
||||||
|
expect(payload.craft_state).toBe('LIVE_EDIT');
|
||||||
|
// The other page is untouched.
|
||||||
|
expect(payload.pages_craft_state.find((p) => p.id === 'p2')?.craftState).toBe('STORED_ABOUT_2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('head code + design tokens are included in the save payload', () => {
|
||||||
|
const design = { ...DEFAULT_SITE_DESIGN, headCode: '<meta name="x">' };
|
||||||
|
|
||||||
|
const payload = buildSavePayload({
|
||||||
|
siteId: 1,
|
||||||
|
siteName: 'Test Site',
|
||||||
|
liveCraftState: 'LIVE_PAGE_HOME',
|
||||||
|
pages: [pageA, pageB],
|
||||||
|
headerPage,
|
||||||
|
footerPage,
|
||||||
|
activePageId: 'home',
|
||||||
|
isEditingHeader: false,
|
||||||
|
isEditingFooter: false,
|
||||||
|
headCode: '<meta name="x">',
|
||||||
|
design,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(payload.head_code).toBe('<meta name="x">');
|
||||||
|
expect(payload.design).toEqual(design);
|
||||||
|
expect(payload.design.headCode).toBe('<meta name="x">');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useCallback } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { useEditorConfig } from '../state/EditorConfigContext';
|
import { useEditorConfig } from '../state/EditorConfigContext';
|
||||||
import { usePages } from '../state/PageContext';
|
import { usePages } from '../state/PageContext';
|
||||||
|
import { useSiteDesign, SiteDesign } from '../state/SiteDesignContext';
|
||||||
import { exportBodyHtml } from '../utils/html-export';
|
import { exportBodyHtml } from '../utils/html-export';
|
||||||
import { PageData } from '../types';
|
import { PageData } from '../types';
|
||||||
|
|
||||||
@@ -18,6 +19,10 @@ export interface BuildSavePayloadInput {
|
|||||||
isEditingHeader: boolean;
|
isEditingHeader: boolean;
|
||||||
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
/** True when the live canvas is showing the footer zone (activePageId === '__footer__'). */
|
||||||
isEditingFooter: boolean;
|
isEditingFooter: boolean;
|
||||||
|
/** Site-wide custom `<head>` code (also present on `design.headCode`). */
|
||||||
|
headCode: string;
|
||||||
|
/** Full site design tokens object -- lets load() restore colors/fonts/headCode. */
|
||||||
|
design: SiteDesign;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -45,10 +50,24 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode,
|
||||||
|
design,
|
||||||
} = input;
|
} = input;
|
||||||
|
|
||||||
const isPageActive = !isEditingHeader && !isEditingFooter;
|
const isPageActive = !isEditingHeader && !isEditingFooter;
|
||||||
|
|
||||||
|
// I-1 (data-loss): `activePageId` can go dangling -- e.g. the original
|
||||||
|
// Home page (id 'home') is deleted, its replacement gets a fresh id
|
||||||
|
// (`page_<ts>`), and a reload re-initializes `activePageId` back to the
|
||||||
|
// hardcoded default `'home'` (see PageContext's `useState('home')`) before
|
||||||
|
// `load()` has a chance to point it at the actually-restored page. If a
|
||||||
|
// real page IS active but matches no entry in `pages`, treat `pages[0]`
|
||||||
|
// (the landing page) as the active one so the live canvas serialization
|
||||||
|
// still reaches the index.html page slot / `pages_craft_state[0]` instead
|
||||||
|
// of only the legacy top-level `craft_state`/`html` fields.
|
||||||
|
const activePageIndex = isPageActive ? pages.findIndex((p) => p.id === activePageId) : -1;
|
||||||
|
const effectiveActivePageId = activePageIndex !== -1 ? activePageId : pages[0]?.id;
|
||||||
|
|
||||||
// Fresh header/footer state: the live canvas wins when that zone is the
|
// Fresh header/footer state: the live canvas wins when that zone is the
|
||||||
// one currently being edited; otherwise fall back to the last-committed
|
// one currently being edited; otherwise fall back to the last-committed
|
||||||
// stored state (updated on zone switch by PageContext's saveCurrentState).
|
// stored state (updated on zone switch by PageContext's saveCurrentState).
|
||||||
@@ -115,7 +134,7 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
const filename = i === 0 ? 'index.html' : page.slug + '.html';
|
const filename = i === 0 ? 'index.html' : page.slug + '.html';
|
||||||
let pageHtml = '';
|
let pageHtml = '';
|
||||||
|
|
||||||
if (isPageActive && page.id === activePageId) {
|
if (isPageActive && page.id === effectiveActivePageId) {
|
||||||
// Active page: use the current canvas HTML (already exported above)
|
// Active page: use the current canvas HTML (already exported above)
|
||||||
pageHtml = currentHtml;
|
pageHtml = currentHtml;
|
||||||
} else if (page.craftState) {
|
} else if (page.craftState) {
|
||||||
@@ -146,7 +165,7 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
// reload the editor's clean-URL routing (.htaccess rewrite of /name →
|
// reload the editor's clean-URL routing (.htaccess rewrite of /name →
|
||||||
// name.html) lines up with the file we just wrote (index.html).
|
// name.html) lines up with the file we just wrote (index.html).
|
||||||
slug: i === 0 ? 'index' : page.slug,
|
slug: i === 0 ? 'index' : page.slug,
|
||||||
craftState: (isPageActive && page.id === activePageId) ? liveCraftState : (page.craftState || null),
|
craftState: (isPageActive && page.id === effectiveActivePageId) ? liveCraftState : (page.craftState || null),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -161,6 +180,8 @@ export function buildSavePayload(input: BuildSavePayloadInput) {
|
|||||||
header_craft_state: headerCraftState,
|
header_craft_state: headerCraftState,
|
||||||
footer_craft_state: footerCraftState,
|
footer_craft_state: footerCraftState,
|
||||||
pages_craft_state: pagesGrapesjs,
|
pages_craft_state: pagesGrapesjs,
|
||||||
|
head_code: headCode,
|
||||||
|
design,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +198,9 @@ export function useWhpApi() {
|
|||||||
setHeaderCraftState,
|
setHeaderCraftState,
|
||||||
setFooterCraftState,
|
setFooterCraftState,
|
||||||
setPagesCraftState,
|
setPagesCraftState,
|
||||||
|
setActivePageIdDirect,
|
||||||
} = usePages();
|
} = usePages();
|
||||||
|
const { design, updateDesign } = useSiteDesign();
|
||||||
|
|
||||||
const save = useCallback(async () => {
|
const save = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -197,6 +220,8 @@ export function useWhpApi() {
|
|||||||
activePageId,
|
activePageId,
|
||||||
isEditingHeader,
|
isEditingHeader,
|
||||||
isEditingFooter,
|
isEditingFooter,
|
||||||
|
headCode: design.headCode,
|
||||||
|
design,
|
||||||
});
|
});
|
||||||
|
|
||||||
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
const resp = await fetch(`${whpConfig.apiUrl}?action=save`, {
|
||||||
@@ -208,7 +233,7 @@ export function useWhpApi() {
|
|||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
return resp.json();
|
return resp.json();
|
||||||
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter]);
|
}, [isWHP, whpConfig, query, pages, activePageId, headerPage, footerPage, isEditingHeader, isEditingFooter, design]);
|
||||||
|
|
||||||
const publish = useCallback(async () => {
|
const publish = useCallback(async () => {
|
||||||
if (!isWHP || !whpConfig) return null;
|
if (!isWHP || !whpConfig) return null;
|
||||||
@@ -242,6 +267,17 @@ export function useWhpApi() {
|
|||||||
if (data.success && data.project) {
|
if (data.success && data.project) {
|
||||||
const proj = data.project;
|
const proj = data.project;
|
||||||
|
|
||||||
|
// Restore site design tokens (colors/fonts/headCode) so the editor
|
||||||
|
// reflects what was last saved. Prefer the full `design` object when
|
||||||
|
// present; fall back to just `head_code` for older project.json files
|
||||||
|
// saved before this field existed (backward-compatible: defaults for
|
||||||
|
// everything else).
|
||||||
|
if (proj.design && typeof proj.design === 'object') {
|
||||||
|
updateDesign(proj.design);
|
||||||
|
} else if (typeof proj.head_code === 'string') {
|
||||||
|
updateDesign({ headCode: proj.head_code });
|
||||||
|
}
|
||||||
|
|
||||||
// Restore header craft state
|
// Restore header craft state
|
||||||
if (proj.header_craft_state) {
|
if (proj.header_craft_state) {
|
||||||
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
setHeaderCraftState(typeof proj.header_craft_state === 'string'
|
||||||
@@ -271,10 +307,23 @@ export function useWhpApi() {
|
|||||||
console.warn('Failed to load page state:', e);
|
console.warn('Failed to load page state:', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// I-1 (data-loss): point activePageId at the page we just loaded
|
||||||
|
// into the canvas. Without this, activePageId stays at whatever it
|
||||||
|
// was initialized to (the hardcoded default 'home'), which goes
|
||||||
|
// dangling the moment the original Home page has been deleted and
|
||||||
|
// replaced (its replacement gets a fresh `page_<ts>` id) -- the next
|
||||||
|
// edit+save would then only reach the legacy top-level fields
|
||||||
|
// instead of the actual page slot. Only do this when a real page is
|
||||||
|
// being loaded, i.e. we're not currently mid-edit of the header/
|
||||||
|
// footer zone (switching zones is handled separately by switchPage).
|
||||||
|
if (!isEditingHeader && !isEditingFooter) {
|
||||||
|
setActivePageIdDirect(firstPage.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState]);
|
}, [isWHP, whpConfig, actions, setHeaderCraftState, setFooterCraftState, setPagesCraftState, setActivePageIdDirect, isEditingHeader, isEditingFooter, updateDesign]);
|
||||||
|
|
||||||
const uploadAsset = useCallback(
|
const uploadAsset = useCallback(
|
||||||
async (file: File) => {
|
async (file: File) => {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import React, { useEffect, useCallback, useRef } from 'react';
|
import React, { useEffect, useCallback, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { findDeletableTarget } from '../../utils/craft-helpers';
|
|
||||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||||
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
|
import { buildSitesmithTarget } from '../../utils/sitesmith-target';
|
||||||
import { regenerateTreeIds } from '../../utils/craft-tree';
|
import { regenerateTreeIds } from '../../utils/craft-tree';
|
||||||
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
||||||
|
import { useNodeActions } from '../../hooks/useNodeActions';
|
||||||
|
|
||||||
interface ContextMenuProps {
|
interface ContextMenuProps {
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
@@ -16,6 +16,8 @@ interface ContextMenuProps {
|
|||||||
|
|
||||||
interface MenuItem {
|
interface MenuItem {
|
||||||
label: string;
|
label: string;
|
||||||
|
/** Font Awesome icon suffix (e.g. 'magic' for fa-magic), rendered before the label. */
|
||||||
|
icon?: string;
|
||||||
shortcut?: string;
|
shortcut?: string;
|
||||||
action: () => void;
|
action: () => void;
|
||||||
danger?: boolean;
|
danger?: boolean;
|
||||||
@@ -63,19 +65,16 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}
|
}
|
||||||
}, [nodeId, query]);
|
}, [nodeId, query]);
|
||||||
|
|
||||||
const duplicate = useCallback(() => {
|
// Shared move/duplicate/delete/select-parent logic (item 1, Phase B) --
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
// extracted into `useNodeActions` so the mobile selection toolbar drives
|
||||||
try {
|
// the exact same behavior. Wrapped here purely to also `onClose()` the
|
||||||
const parentId = getParentId();
|
// menu after each action, same as before the extraction.
|
||||||
if (!parentId) return;
|
const nodeActions = useNodeActions(nodeId);
|
||||||
|
|
||||||
const tree = regenerateTreeIds(query.node(nodeId).toNodeTree());
|
const duplicate = useCallback(() => {
|
||||||
actions.addNodeTree(tree, parentId);
|
nodeActions.duplicate();
|
||||||
} catch (e) {
|
|
||||||
console.error('Duplicate failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const copyNode = useCallback(() => {
|
const copyNode = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
@@ -116,47 +115,19 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}, [nodeId, actions, query, onClose]);
|
}, [nodeId, actions, query, onClose]);
|
||||||
|
|
||||||
const moveUp = useCallback(() => {
|
const moveUp = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.moveUp();
|
||||||
try {
|
|
||||||
const parentId = getParentId();
|
|
||||||
if (!parentId) return;
|
|
||||||
const parent = query.node(parentId).get();
|
|
||||||
const children = parent.data.nodes || [];
|
|
||||||
const idx = children.indexOf(nodeId);
|
|
||||||
if (idx > 0) {
|
|
||||||
actions.move(nodeId, parentId, idx - 1);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Move up failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const moveDown = useCallback(() => {
|
const moveDown = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.moveDown();
|
||||||
try {
|
|
||||||
const parentId = getParentId();
|
|
||||||
if (!parentId) return;
|
|
||||||
const parent = query.node(parentId).get();
|
|
||||||
const children = parent.data.nodes || [];
|
|
||||||
const idx = children.indexOf(nodeId);
|
|
||||||
if (idx < children.length - 1) {
|
|
||||||
actions.move(nodeId, parentId, idx + 2);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Move down failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, query, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const selectParent = useCallback(() => {
|
const selectParent = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
nodeActions.selectParent();
|
||||||
const parentId = getParentId();
|
|
||||||
if (parentId) {
|
|
||||||
actions.selectNode(parentId);
|
|
||||||
}
|
|
||||||
onClose();
|
onClose();
|
||||||
}, [nodeId, actions, getParentId, onClose]);
|
}, [nodeActions, onClose]);
|
||||||
|
|
||||||
const askSitesmith = useCallback(() => {
|
const askSitesmith = useCallback(() => {
|
||||||
if (!nodeId || nodeId === 'ROOT') return;
|
if (!nodeId || nodeId === 'ROOT') return;
|
||||||
@@ -170,18 +141,9 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
}, [nodeId, query, openSitesmith, onClose]);
|
}, [nodeId, query, openSitesmith, onClose]);
|
||||||
|
|
||||||
const deleteNode = useCallback(() => {
|
const deleteNode = useCallback(() => {
|
||||||
const target = findDeletableTarget(query, nodeId);
|
nodeActions.deleteNode();
|
||||||
if (!target) {
|
|
||||||
onClose();
|
onClose();
|
||||||
return;
|
}, [nodeActions, onClose]);
|
||||||
}
|
|
||||||
try {
|
|
||||||
actions.delete(target);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Delete failed:', e);
|
|
||||||
}
|
|
||||||
onClose();
|
|
||||||
}, [nodeId, actions, query, onClose]);
|
|
||||||
|
|
||||||
if (!visible) return null;
|
if (!visible) return null;
|
||||||
|
|
||||||
@@ -189,25 +151,29 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
|
|
||||||
const items: MenuItem[] = [
|
const items: MenuItem[] = [
|
||||||
{
|
{
|
||||||
label: '✨ Ask Sitesmith',
|
label: 'Ask Sitesmith',
|
||||||
|
icon: 'magic',
|
||||||
action: askSitesmith,
|
action: askSitesmith,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
dividerAfter: true,
|
dividerAfter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Duplicate',
|
label: 'Duplicate',
|
||||||
|
icon: 'clone',
|
||||||
shortcut: 'Ctrl+D',
|
shortcut: 'Ctrl+D',
|
||||||
action: duplicate,
|
action: duplicate,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Copy',
|
label: 'Copy',
|
||||||
|
icon: 'files-o',
|
||||||
shortcut: 'Ctrl+C',
|
shortcut: 'Ctrl+C',
|
||||||
action: copyNode,
|
action: copyNode,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Paste',
|
label: 'Paste',
|
||||||
|
icon: 'clipboard',
|
||||||
shortcut: 'Ctrl+V',
|
shortcut: 'Ctrl+V',
|
||||||
action: pasteNode,
|
action: pasteNode,
|
||||||
disabled: !getClipboardNodeId(),
|
disabled: !getClipboardNodeId(),
|
||||||
@@ -215,22 +181,31 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Move Up',
|
label: 'Move Up',
|
||||||
|
icon: 'arrow-up',
|
||||||
action: moveUp,
|
action: moveUp,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Move Down',
|
label: 'Move Down',
|
||||||
|
icon: 'arrow-down',
|
||||||
action: moveDown,
|
action: moveDown,
|
||||||
disabled: isRoot,
|
disabled: isRoot,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Select Parent',
|
label: 'Select Parent',
|
||||||
|
icon: 'level-up',
|
||||||
action: selectParent,
|
action: selectParent,
|
||||||
disabled: isRoot,
|
// Not just `isRoot`: the real dead-end is when nodeId's PARENT is
|
||||||
|
// ROOT (selecting a top-level section -> Select Parent would only
|
||||||
|
// select the page-wide, un-editable ROOT -- no outline, no toolbar).
|
||||||
|
// `canSelectParent` (useNodeActions) already encodes that and matches
|
||||||
|
// the mobile selection toolbar's identical guard.
|
||||||
|
disabled: !nodeActions.canSelectParent,
|
||||||
dividerAfter: true,
|
dividerAfter: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Delete',
|
label: 'Delete',
|
||||||
|
icon: 'trash',
|
||||||
shortcut: 'Del',
|
shortcut: 'Del',
|
||||||
action: deleteNode,
|
action: deleteNode,
|
||||||
danger: true,
|
danger: true,
|
||||||
@@ -291,7 +266,10 @@ export const ContextMenu: React.FC<ContextMenuProps> = ({
|
|||||||
(e.target as HTMLElement).style.background = 'transparent';
|
(e.target as HTMLElement).style.background = 'transparent';
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<span>{item.label}</span>
|
<span>
|
||||||
|
{item.icon && <i className={`fa fa-${item.icon}`} style={{ marginRight: 6, width: 12 }} />}
|
||||||
|
{item.label}
|
||||||
|
</span>
|
||||||
{item.shortcut && (
|
{item.shortcut && (
|
||||||
<span
|
<span
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ import React, { useEffect, useRef, useState, useCallback } from 'react';
|
|||||||
import { useAssets } from '../../hooks/useAssets';
|
import { useAssets } from '../../hooks/useAssets';
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
import { copyToClipboard } from '../../utils/clipboard';
|
import { copyToClipboard } from '../../utils/clipboard';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
|
||||||
/** How long the "Delete?" confirm state stays armed before auto-resetting. */
|
/** How long the "Delete?" confirm state stays armed before auto-resetting. */
|
||||||
const DELETE_CONFIRM_TIMEOUT_MS = 4000;
|
const DELETE_CONFIRM_TIMEOUT_MS = 4000;
|
||||||
|
|
||||||
export const AssetsPanel: React.FC = () => {
|
export const AssetsPanel: React.FC = () => {
|
||||||
const { assets, loading, error, loadAssets, uploadAsset, deleteAsset } = useAssets();
|
const { assets, loading, error, loadAssets, uploadAsset, deleteAsset } = useAssets();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
const [isDragOver, setIsDragOver] = useState(false);
|
const [isDragOver, setIsDragOver] = useState(false);
|
||||||
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
const [copiedUrl, setCopiedUrl] = useState<string | null>(null);
|
||||||
@@ -107,23 +109,41 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
{loading ? 'Uploading...' : 'Upload File'}
|
{loading ? 'Uploading...' : 'Upload File'}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Drop zone */}
|
{/* Drop zone -- a single element that doubles as the empty state.
|
||||||
|
Previously this was a small always-visible dropzone PLUS a
|
||||||
|
separate italic "No assets uploaded yet" line stacked underneath
|
||||||
|
it when empty; merged into one tall dropzone (icon + copy,
|
||||||
|
click-or-drag) so the empty state isn't two redundant messages.
|
||||||
|
Once assets exist it collapses back to a slim persistent drop
|
||||||
|
target above the grid. */}
|
||||||
<div
|
<div
|
||||||
onDrop={handleDrop}
|
onDrop={handleDrop}
|
||||||
onDragOver={handleDragOver}
|
onDragOver={handleDragOver}
|
||||||
onDragLeave={handleDragLeave}
|
onDragLeave={handleDragLeave}
|
||||||
|
{...(assets.length === 0 ? clickableProps(() => fileInputRef.current?.click()) : {})}
|
||||||
style={{
|
style={{
|
||||||
padding: 20,
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: 8,
|
||||||
|
padding: assets.length === 0 ? '36px 20px' : 16,
|
||||||
border: `2px dashed ${isDragOver ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
border: `2px dashed ${isDragOver ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
||||||
borderRadius: 'var(--radius-md)',
|
borderRadius: 'var(--radius-md)',
|
||||||
background: isDragOver ? 'var(--color-accent-subtle)' : 'transparent',
|
background: isDragOver ? 'var(--color-accent-subtle)' : 'transparent',
|
||||||
textAlign: 'center',
|
textAlign: 'center',
|
||||||
color: isDragOver ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
color: isDragOver ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
||||||
fontSize: 11,
|
fontSize: 11,
|
||||||
|
cursor: assets.length === 0 ? 'pointer' : 'default',
|
||||||
transition: 'all var(--transition-fast)',
|
transition: 'all var(--transition-fast)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
Drop files here to upload
|
{assets.length === 0 && (
|
||||||
|
<i className="fa fa-cloud-upload" aria-hidden style={{ fontSize: 28, opacity: 0.5 }} />
|
||||||
|
)}
|
||||||
|
{assets.length === 0
|
||||||
|
? (isMobile ? 'Tap to upload images' : 'Drag images here or click to upload')
|
||||||
|
: 'Drop files here to upload'}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Error message */}
|
{/* Error message */}
|
||||||
@@ -143,20 +163,6 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Asset grid */}
|
{/* Asset grid */}
|
||||||
{assets.length === 0 && !loading && (
|
|
||||||
<div
|
|
||||||
style={{
|
|
||||||
textAlign: 'center',
|
|
||||||
padding: 20,
|
|
||||||
color: 'var(--color-text-dim)',
|
|
||||||
fontSize: 12,
|
|
||||||
fontStyle: 'italic',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
No assets uploaded yet
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
display: 'grid',
|
display: 'grid',
|
||||||
@@ -296,7 +302,7 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -328,7 +334,7 @@ export const AssetsPanel: React.FC = () => {
|
|||||||
onMouseEnter={(e) => { (e.target as HTMLElement).style.opacity = '1'; }}
|
onMouseEnter={(e) => { (e.target as HTMLElement).style.opacity = '1'; }}
|
||||||
onMouseLeave={(e) => { (e.target as HTMLElement).style.opacity = '0.7'; }}
|
onMouseLeave={(e) => { (e.target as HTMLElement).style.opacity = '0.7'; }}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useCallback, useState } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
import { Container } from '../../components/layout/Container';
|
import { Container } from '../../components/layout/Container';
|
||||||
import { Section } from '../../components/layout/Section';
|
import { Section } from '../../components/layout/Section';
|
||||||
import { ColumnLayout } from '../../components/layout/ColumnLayout';
|
import { ColumnLayout } from '../../components/layout/ColumnLayout';
|
||||||
@@ -123,7 +125,7 @@ const categories: CategoryDef[] = [
|
|||||||
label: 'Media',
|
label: 'Media',
|
||||||
blocks: [
|
blocks: [
|
||||||
{ id: 'image', label: 'Image', icon: 'fa-image',
|
{ id: 'image', label: 'Image', icon: 'fa-image',
|
||||||
component: <ImageBlock src="" alt="Image" style={{ maxWidth: '100%', height: 'auto', display: 'block', borderRadius: '8px' }} /> },
|
component: <ImageBlock alt="Image" style={{ maxWidth: '100%', height: 'auto', display: 'block', borderRadius: '8px' }} /> },
|
||||||
{ id: 'video', label: 'Video', icon: 'fa-play-circle',
|
{ id: 'video', label: 'Video', icon: 'fa-play-circle',
|
||||||
component: <VideoBlock videoUrl="" isBackground={false} /> },
|
component: <VideoBlock videoUrl="" isBackground={false} /> },
|
||||||
{ id: 'map-embed', label: 'Map', icon: 'fa-map-marker',
|
{ id: 'map-embed', label: 'Map', icon: 'fa-map-marker',
|
||||||
@@ -146,6 +148,8 @@ const categories: CategoryDef[] = [
|
|||||||
|
|
||||||
export const BlocksPanel: React.FC = () => {
|
export const BlocksPanel: React.FC = () => {
|
||||||
const { connectors, actions, query } = useEditor();
|
const { connectors, actions, query } = useEditor();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { closeSheet } = useMobileChrome();
|
||||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => {
|
const [collapsed, setCollapsed] = useState<Record<string, boolean>>(() => {
|
||||||
const initial: Record<string, boolean> = {};
|
const initial: Record<string, boolean> = {};
|
||||||
categories.forEach((cat, index) => {
|
categories.forEach((cat, index) => {
|
||||||
@@ -158,6 +162,101 @@ export const BlocksPanel: React.FC = () => {
|
|||||||
setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] }));
|
setCollapsed((prev) => ({ ...prev, [categoryId]: !prev[categoryId] }));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Default insertion target when there's no usable selection to anchor
|
||||||
|
* to: the first real Craft.js canvas in the document (falls back to
|
||||||
|
* ROOT). Extracted from the pre-existing onDoubleClick handler so
|
||||||
|
* tap-to-add (mobile, item 3) and double-click (desktop, unchanged) share
|
||||||
|
* the exact same fallback. */
|
||||||
|
const findDefaultCanvasId = useCallback((): string => {
|
||||||
|
try {
|
||||||
|
const serialized = JSON.parse(query.serialize());
|
||||||
|
const nodeIds = Object.keys(serialized);
|
||||||
|
for (const id of nodeIds) {
|
||||||
|
if (serialized[id].isCanvas && id !== 'ROOT') return id;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall through to ROOT below.
|
||||||
|
}
|
||||||
|
return 'ROOT';
|
||||||
|
}, [query]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a fresh node tree for `block` and inserts it into the canvas,
|
||||||
|
* returning the new node's id (or null on failure). Shared by desktop's
|
||||||
|
* double-click (unchanged behavior/position: always appended to
|
||||||
|
* `findDefaultCanvasId()`) and mobile's tap-to-add (item 3), which instead
|
||||||
|
* prefers inserting as a sibling right after the current selection --
|
||||||
|
* `insertAfterSelection: true` only from the mobile tap handler below.
|
||||||
|
*/
|
||||||
|
const addBlockNode = useCallback((block: BlockDef, insertAfterSelection: boolean): string | null => {
|
||||||
|
try {
|
||||||
|
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
|
||||||
|
|
||||||
|
let inserted = false;
|
||||||
|
if (insertAfterSelection) {
|
||||||
|
try {
|
||||||
|
const selectedIds = query.getEvent('selected').all();
|
||||||
|
const selectedId = selectedIds.length > 0 ? selectedIds[0] : null;
|
||||||
|
if (selectedId && selectedId !== 'ROOT') {
|
||||||
|
const selectedNode = query.node(selectedId).get();
|
||||||
|
const parentId = selectedNode?.data?.parent;
|
||||||
|
if (parentId) {
|
||||||
|
const parent = query.node(parentId).get();
|
||||||
|
const siblings: string[] = parent?.data?.nodes || [];
|
||||||
|
const idx = siblings.indexOf(selectedId);
|
||||||
|
if (idx !== -1) {
|
||||||
|
actions.addNodeTree(tree, parentId, idx + 1);
|
||||||
|
inserted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Selection isn't a valid sibling target (e.g. lives in a
|
||||||
|
// linkedNodes slot) -- fall through to the default canvas below.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!inserted) {
|
||||||
|
actions.addNodeTree(tree, findDefaultCanvasId());
|
||||||
|
}
|
||||||
|
|
||||||
|
return tree.rootNodeId;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to add block:', e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, [query, actions, findDefaultCanvasId]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile tap-to-add (item 3): a single tap on a block tile inserts it,
|
||||||
|
* closes the Blocks sheet, then selects the new node and scrolls it into
|
||||||
|
* view so the user immediately sees it (and gets the selection toolbar).
|
||||||
|
* The select/scroll step is deferred two animation frames past the
|
||||||
|
* `addNodeTree` call -- Craft.js's own state update (and thus the new
|
||||||
|
* node's real DOM element) lands asynchronously after this handler
|
||||||
|
* returns, so `query.node(id).get().dom` isn't populated yet if read
|
||||||
|
* synchronously here.
|
||||||
|
*/
|
||||||
|
const handleTapToAdd = useCallback((block: BlockDef) => {
|
||||||
|
const newId = addBlockNode(block, true);
|
||||||
|
closeSheet();
|
||||||
|
if (!newId) return;
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
actions.selectNode(newId);
|
||||||
|
} catch {
|
||||||
|
// Node may have failed to mount -- nothing to select.
|
||||||
|
}
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort scroll -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [addBlockNode, closeSheet, actions, query]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
{categories.map((category) => {
|
{categories.map((category) => {
|
||||||
@@ -178,24 +277,9 @@ export const BlocksPanel: React.FC = () => {
|
|||||||
key={block.id}
|
key={block.id}
|
||||||
className="block-item"
|
className="block-item"
|
||||||
ref={(ref) => { if (ref) connectors.create(ref, block.component); }}
|
ref={(ref) => { if (ref) connectors.create(ref, block.component); }}
|
||||||
onDoubleClick={() => {
|
onDoubleClick={() => addBlockNode(block, false)}
|
||||||
try {
|
onClick={isMobile ? () => handleTapToAdd(block) : undefined}
|
||||||
const serialized = JSON.parse(query.serialize());
|
title={isMobile ? `Tap to add ${block.label}` : `Drag or double-click to add ${block.label}`}
|
||||||
const nodeIds = Object.keys(serialized);
|
|
||||||
let canvasId = 'ROOT';
|
|
||||||
for (const nodeId of nodeIds) {
|
|
||||||
if (serialized[nodeId].isCanvas && nodeId !== 'ROOT') {
|
|
||||||
canvasId = nodeId;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const tree = query.parseReactElement(React.cloneElement(block.component)).toNodeTree();
|
|
||||||
actions.addNodeTree(tree, canvasId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to add block:', e);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
title={`Drag or double-click to add ${block.label}`}
|
|
||||||
>
|
>
|
||||||
<i className={`fa ${block.icon} block-item-icon`} />
|
<i className={`fa ${block.icon} block-item-icon`} />
|
||||||
<span className="block-item-label">{block.label}</span>
|
<span className="block-item-label">{block.label}</span>
|
||||||
|
|||||||
@@ -1,14 +1,74 @@
|
|||||||
import React, { useCallback } from 'react';
|
import React, { useCallback, useEffect, useRef } from 'react';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-type icon lookup keyed by the component's `craft.displayName` (the
|
||||||
|
* same human label `LayerNode` already resolves and shows as the row text).
|
||||||
|
* Mirrors the icon choices in `BlocksPanel.tsx` where a block exists for the
|
||||||
|
* type; the remaining entries (Navbar, Container, Section, Columns,
|
||||||
|
* Background Section, Map, Video, Image, form fields, and the richer
|
||||||
|
* section blocks not draggable from the Basic/Sections categories) get a
|
||||||
|
* sensible FA4 icon of their own. Unknown/future types fall back to
|
||||||
|
* `DEFAULT_ICON`.
|
||||||
|
*/
|
||||||
|
const TYPE_ICONS: Record<string, string> = {
|
||||||
|
// Layout
|
||||||
|
Container: 'fa-square-o',
|
||||||
|
Section: 'fa-window-maximize',
|
||||||
|
Columns: 'fa-th-large',
|
||||||
|
'Background Section': 'fa-picture-o',
|
||||||
|
// Basic
|
||||||
|
Heading: 'fa-header',
|
||||||
|
Text: 'fa-paragraph',
|
||||||
|
Button: 'fa-square',
|
||||||
|
Logo: 'fa-bookmark',
|
||||||
|
Menu: 'fa-bars',
|
||||||
|
Navbar: 'fa-bars',
|
||||||
|
Footer: 'fa-window-minimize',
|
||||||
|
Divider: 'fa-minus',
|
||||||
|
Spacer: 'fa-arrows-v',
|
||||||
|
Icon: 'fa-star',
|
||||||
|
'Star Rating': 'fa-star-half-o',
|
||||||
|
'Social Links': 'fa-share-alt',
|
||||||
|
'Search Bar': 'fa-search',
|
||||||
|
HTML: 'fa-code',
|
||||||
|
// Media
|
||||||
|
Image: 'fa-image',
|
||||||
|
Video: 'fa-play-circle',
|
||||||
|
Map: 'fa-map-marker',
|
||||||
|
// Sections
|
||||||
|
Hero: 'fa-star-o',
|
||||||
|
'Features Grid': 'fa-th-large',
|
||||||
|
'CTA Section': 'fa-bullhorn',
|
||||||
|
'Call to Action': 'fa-bullhorn',
|
||||||
|
Countdown: 'fa-clock-o',
|
||||||
|
Testimonials: 'fa-quote-left',
|
||||||
|
'Content Slider': 'fa-sliders',
|
||||||
|
'Number Counter': 'fa-sort-numeric-asc',
|
||||||
|
Accordion: 'fa-list',
|
||||||
|
Tabs: 'fa-folder-o',
|
||||||
|
'Pricing Table': 'fa-usd',
|
||||||
|
Gallery: 'fa-th',
|
||||||
|
// Forms
|
||||||
|
Form: 'fa-wpforms',
|
||||||
|
Input: 'fa-i-cursor',
|
||||||
|
Textarea: 'fa-align-left',
|
||||||
|
'Submit Button': 'fa-paper-plane',
|
||||||
|
'Contact Form': 'fa-envelope',
|
||||||
|
'Subscribe Form': 'fa-paper-plane',
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_ICON = 'fa-cube';
|
||||||
|
const ROOT_ICON = 'fa-desktop';
|
||||||
|
|
||||||
interface LayerNodeProps {
|
interface LayerNodeProps {
|
||||||
nodeId: string;
|
nodeId: string;
|
||||||
depth: number;
|
depth: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
||||||
const { node, selectedId, actions } = useEditor((state) => {
|
const { node, selectedId, actions, query } = useEditor((state) => {
|
||||||
const n = state.nodes[nodeId];
|
const n = state.nodes[nodeId];
|
||||||
const selectedIds = state.events.selected;
|
const selectedIds = state.events.selected;
|
||||||
const selId = selectedIds ? Array.from(selectedIds)[0] : null;
|
const selId = selectedIds ? Array.from(selectedIds)[0] : null;
|
||||||
@@ -18,28 +78,77 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const isSelected = selectedId === nodeId;
|
||||||
|
|
||||||
const handleActivate = useCallback(() => {
|
const handleActivate = useCallback(() => {
|
||||||
actions.selectNode(nodeId);
|
actions.selectNode(nodeId);
|
||||||
}, [actions, nodeId]);
|
}, [actions, nodeId]);
|
||||||
|
|
||||||
|
// Layers-panel <-> canvas hover sync (Item 12): tags the target node's own
|
||||||
|
// DOM element (found via `query`) with `data-layer-hovered` directly.
|
||||||
|
// `RenderNode.tsx` mirrors Craft's *own* `hovered` node event onto
|
||||||
|
// `data-craft-hovered` for the (separate, mouse-driven) canvas hover
|
||||||
|
// outline -- editor.css's rule matches both attributes. This panel can't
|
||||||
|
// reuse that path: `setNodeEvent` is a private action that `useEditor()`
|
||||||
|
// strips from its `actions` return at runtime (see
|
||||||
|
// @craftjs/core/dist/esm's `xe()` action stripper, not just its TypeScript
|
||||||
|
// type), so calling it here throws. Writing our own attribute directly is
|
||||||
|
// a supported, version-stable way to get the same highlight.
|
||||||
|
const hoveredDomRef = useRef<HTMLElement | null>(null);
|
||||||
|
|
||||||
|
const handleMouseEnter = useCallback(
|
||||||
|
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||||
|
const dom = query.node(nodeId).get()?.dom;
|
||||||
|
if (dom) {
|
||||||
|
dom.setAttribute('data-layer-hovered', '');
|
||||||
|
hoveredDomRef.current = dom;
|
||||||
|
}
|
||||||
|
if (!isSelected) {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[query, nodeId, isSelected],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handleMouseLeave = useCallback(
|
||||||
|
(e: React.MouseEvent<HTMLElement> | React.FocusEvent<HTMLElement>) => {
|
||||||
|
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||||
|
hoveredDomRef.current = null;
|
||||||
|
if (!isSelected) {
|
||||||
|
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[isSelected],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Safety net: if this row unmounts (e.g. the user switches away from the
|
||||||
|
// Layers tab, or the tree re-shuffles) while still hovered, clear the
|
||||||
|
// attribute so it doesn't get stuck highlighted on the canvas forever.
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
hoveredDomRef.current?.removeAttribute('data-layer-hovered');
|
||||||
|
hoveredDomRef.current = null;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
if (!node) return null;
|
if (!node) return null;
|
||||||
|
|
||||||
const isSelected = selectedId === nodeId;
|
|
||||||
const nodeType = node.data.type;
|
|
||||||
const resolvedName = typeof nodeType === 'object' && nodeType !== null && 'resolvedName' in nodeType
|
|
||||||
? (nodeType as any).resolvedName
|
|
||||||
: typeof nodeType === 'string' ? nodeType : undefined;
|
|
||||||
const displayName = (node.data.props?.aiName as string) || node.data.displayName || (node.data.type as any)?.resolvedName || 'Node';
|
const displayName = (node.data.props?.aiName as string) || node.data.displayName || (node.data.type as any)?.resolvedName || 'Node';
|
||||||
const childNodeIds: string[] = node.data.nodes || [];
|
const childNodeIds: string[] = node.data.nodes || [];
|
||||||
const linkedNodeIds: string[] = Object.values(node.data.linkedNodes || {}) as string[];
|
const linkedNodeIds: string[] = Object.values(node.data.linkedNodes || {}) as string[];
|
||||||
const allChildren = [...childNodeIds, ...linkedNodeIds];
|
const allChildren = [...childNodeIds, ...linkedNodeIds];
|
||||||
const isRoot = nodeId === 'ROOT';
|
const isRoot = nodeId === 'ROOT';
|
||||||
|
const icon = isRoot ? ROOT_ICON : TYPE_ICONS[displayName] || DEFAULT_ICON;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
{...clickableProps(handleActivate)}
|
{...clickableProps(handleActivate)}
|
||||||
|
onMouseEnter={handleMouseEnter}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
|
className="layer-node-row"
|
||||||
style={{
|
style={{
|
||||||
|
position: 'relative',
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
padding: '5px 8px',
|
padding: '5px 8px',
|
||||||
@@ -56,30 +165,53 @@ const LayerNode: React.FC<LayerNodeProps> = ({ nodeId, depth }) => {
|
|||||||
textOverflow: 'ellipsis',
|
textOverflow: 'ellipsis',
|
||||||
userSelect: 'none',
|
userSelect: 'none',
|
||||||
}}
|
}}
|
||||||
onMouseEnter={(e) => {
|
onFocus={handleMouseEnter}
|
||||||
if (!isSelected) {
|
onBlur={handleMouseLeave}
|
||||||
(e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onMouseLeave={(e) => {
|
|
||||||
if (!isSelected) {
|
|
||||||
(e.currentTarget as HTMLElement).style.background = 'transparent';
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
{/* Indentation indicator */}
|
{/* Indent guides: one vertical line per ancestor depth level,
|
||||||
{allChildren.length > 0 && (
|
aligned under each ancestor's disclosure/icon column so nested
|
||||||
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)' }}>
|
rows read as a tree instead of a flat, ever-further-indented list. */}
|
||||||
|
{Array.from({ length: depth }).map((_, level) => (
|
||||||
|
<span
|
||||||
|
key={level}
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: `${8 + level * 16 + 4}px`,
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
width: 1,
|
||||||
|
background: 'var(--color-border)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Indentation/disclosure indicator */}
|
||||||
|
{allChildren.length > 0 ? (
|
||||||
|
<span style={{ marginRight: 4, fontSize: 8, color: 'var(--color-text-dim)', flexShrink: 0 }}>
|
||||||
▼
|
▼
|
||||||
</span>
|
</span>
|
||||||
)}
|
) : (
|
||||||
{allChildren.length === 0 && (
|
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent', flexShrink: 0 }}>
|
||||||
<span style={{ marginRight: 4, fontSize: 8, color: 'transparent' }}>
|
|
||||||
▼
|
▼
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Component type icon and name */}
|
{/* Component type icon */}
|
||||||
|
<i
|
||||||
|
className={`fa ${icon}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
style={{
|
||||||
|
marginRight: 6,
|
||||||
|
fontSize: 11,
|
||||||
|
width: 12,
|
||||||
|
textAlign: 'center',
|
||||||
|
flexShrink: 0,
|
||||||
|
color: isSelected ? 'var(--color-accent)' : 'var(--color-text-dim)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Name */}
|
||||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||||
{isRoot ? 'Canvas (Root)' : displayName}
|
{isRoot ? 'Canvas (Root)' : displayName}
|
||||||
</span>
|
</span>
|
||||||
|
|||||||
@@ -58,18 +58,23 @@ export const PagesPanel: React.FC = () => {
|
|||||||
.replace(/-+/g, '-');
|
.replace(/-+/g, '-');
|
||||||
};
|
};
|
||||||
|
|
||||||
/* ---------- Zone button style ---------- */
|
/* ---------- Zone row style ----------
|
||||||
const zoneButtonStyle = (isActive: boolean): React.CSSProperties => ({
|
* Same neutral surface language as the page-list rows below (Item 11) --
|
||||||
|
* header/footer are just two more items in the tree, not a louder,
|
||||||
|
* differently-colored category. The active/editing state reuses the same
|
||||||
|
* accent-outline treatment the page list already uses for the active page,
|
||||||
|
* so there's one consistent "this is what's currently open" affordance. */
|
||||||
|
const zoneRowStyle = (isActive: boolean): React.CSSProperties => ({
|
||||||
display: 'flex',
|
display: 'flex',
|
||||||
alignItems: 'center',
|
alignItems: 'center',
|
||||||
gap: 8,
|
gap: 8,
|
||||||
width: '100%',
|
width: '100%',
|
||||||
padding: '10px 12px',
|
padding: '7px 10px',
|
||||||
fontSize: 12,
|
fontSize: 12,
|
||||||
fontWeight: 600,
|
fontWeight: isActive ? 600 : 500,
|
||||||
color: isActive ? '#f59e0b' : '#fbbf24',
|
color: isActive ? 'var(--color-accent)' : 'var(--color-text-muted)',
|
||||||
background: isActive ? 'rgba(245, 158, 11, 0.15)' : 'rgba(245, 158, 11, 0.06)',
|
background: isActive ? 'var(--color-accent-subtle)' : 'var(--color-bg-elevated)',
|
||||||
border: `1px solid ${isActive ? 'rgba(245, 158, 11, 0.5)' : 'rgba(245, 158, 11, 0.2)'}`,
|
border: `1px solid ${isActive ? 'var(--color-accent)' : 'var(--color-border)'}`,
|
||||||
borderRadius: 'var(--radius-md)',
|
borderRadius: 'var(--radius-md)',
|
||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
transition: 'all var(--transition-fast)',
|
transition: 'all var(--transition-fast)',
|
||||||
@@ -78,57 +83,35 @@ export const PagesPanel: React.FC = () => {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||||
{/* Header/Footer zone buttons */}
|
{/* Header/Footer zone rows */}
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8 }}>
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 8 }}>
|
||||||
<button
|
<button
|
||||||
onClick={editHeader}
|
onClick={editHeader}
|
||||||
style={zoneButtonStyle(isEditingHeader)}
|
className="zone-row"
|
||||||
|
style={zoneRowStyle(isEditingHeader)}
|
||||||
|
title="Appears on all pages"
|
||||||
>
|
>
|
||||||
<i className="fa fa-window-maximize" style={{ fontSize: 13 }} />
|
<i className="fa fa-window-maximize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||||
<div style={{ flex: 1 }}>
|
<span style={{ flex: 1 }}>Header</span>
|
||||||
<div>Edit Header</div>
|
{isEditingHeader ? (
|
||||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||||
Appears on all pages
|
) : (
|
||||||
</div>
|
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||||
</div>
|
|
||||||
{isEditingHeader && (
|
|
||||||
<span style={{
|
|
||||||
fontSize: 9,
|
|
||||||
fontWeight: 700,
|
|
||||||
textTransform: 'uppercase',
|
|
||||||
letterSpacing: '0.5px',
|
|
||||||
background: 'rgba(245, 158, 11, 0.25)',
|
|
||||||
padding: '2px 6px',
|
|
||||||
borderRadius: 'var(--radius-sm)',
|
|
||||||
}}>
|
|
||||||
Editing
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={editFooter}
|
onClick={editFooter}
|
||||||
style={zoneButtonStyle(isEditingFooter)}
|
className="zone-row"
|
||||||
|
style={zoneRowStyle(isEditingFooter)}
|
||||||
|
title="Appears on all pages"
|
||||||
>
|
>
|
||||||
<i className="fa fa-window-minimize" style={{ fontSize: 13 }} />
|
<i className="fa fa-window-minimize" style={{ fontSize: 12, width: 14, textAlign: 'center', flexShrink: 0 }} />
|
||||||
<div style={{ flex: 1 }}>
|
<span style={{ flex: 1 }}>Footer</span>
|
||||||
<div>Edit Footer</div>
|
{isEditingFooter ? (
|
||||||
<div style={{ fontSize: 10, opacity: 0.7, fontWeight: 400, marginTop: 1 }}>
|
<i className="fa fa-check-circle" style={{ fontSize: 11 }} aria-hidden />
|
||||||
Appears on all pages
|
) : (
|
||||||
</div>
|
<i className="fa fa-pencil zone-row-pencil" style={{ fontSize: 11 }} aria-hidden />
|
||||||
</div>
|
|
||||||
{isEditingFooter && (
|
|
||||||
<span style={{
|
|
||||||
fontSize: 9,
|
|
||||||
fontWeight: 700,
|
|
||||||
textTransform: 'uppercase',
|
|
||||||
letterSpacing: '0.5px',
|
|
||||||
background: 'rgba(245, 158, 11, 0.25)',
|
|
||||||
padding: '2px 6px',
|
|
||||||
borderRadius: 'var(--radius-sm)',
|
|
||||||
}}>
|
|
||||||
Editing
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -328,18 +311,21 @@ export const PagesPanel: React.FC = () => {
|
|||||||
title="This is the landing page — published as the root URL (index.html)"
|
title="This is the landing page — published as the root URL (index.html)"
|
||||||
style={{
|
style={{
|
||||||
fontSize: 9,
|
fontSize: 9,
|
||||||
fontWeight: 700,
|
fontWeight: 600,
|
||||||
textTransform: 'uppercase',
|
letterSpacing: '0.3px',
|
||||||
letterSpacing: '0.5px',
|
color: 'var(--color-text-muted)',
|
||||||
color: '#fbbf24',
|
background: 'transparent',
|
||||||
background: 'rgba(245, 158, 11, 0.15)',
|
border: '1px solid var(--color-border-light)',
|
||||||
border: '1px solid rgba(245, 158, 11, 0.35)',
|
|
||||||
padding: '1px 5px',
|
padding: '1px 5px',
|
||||||
borderRadius: 'var(--radius-sm)',
|
borderRadius: 'var(--radius-sm)',
|
||||||
flexShrink: 0,
|
flexShrink: 0,
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 4,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<i className="fa fa-home" style={{ marginRight: 3 }} />Landing
|
<i className="fa fa-home" aria-hidden="true" style={{ fontSize: 8, color: 'inherit' }} />
|
||||||
|
Landing
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -359,7 +345,8 @@ export const PagesPanel: React.FC = () => {
|
|||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
onClick={() => startEditing(page)}
|
onClick={() => startEditing(page)}
|
||||||
title="Rename"
|
data-tooltip="Rename"
|
||||||
|
aria-label={`Rename ${page.name}`}
|
||||||
style={{
|
style={{
|
||||||
width: 24,
|
width: 24,
|
||||||
height: 24,
|
height: 24,
|
||||||
@@ -374,12 +361,13 @@ export const PagesPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✎
|
<i className="fa fa-pencil" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
{pages.length > 1 && !isLanding && (
|
{pages.length > 1 && !isLanding && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setDeleteConfirmId(page.id)}
|
onClick={() => setDeleteConfirmId(page.id)}
|
||||||
title="Delete"
|
data-tooltip="Delete"
|
||||||
|
aria-label={`Delete ${page.name}`}
|
||||||
style={{
|
style={{
|
||||||
width: 24,
|
width: 24,
|
||||||
height: 24,
|
height: 24,
|
||||||
@@ -394,7 +382,7 @@ export const PagesPanel: React.FC = () => {
|
|||||||
cursor: 'pointer',
|
cursor: 'pointer',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✕
|
<i className="fa fa-trash" aria-hidden="true" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useVisualViewportInsets } from '../../hooks/useVisualViewport';
|
||||||
|
|
||||||
|
export interface BottomSheetProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
title: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vertical drag distance (px) past which releasing the handle/header
|
||||||
|
* commits to closing the sheet, rather than snapping back open. */
|
||||||
|
const SWIPE_DISMISS_THRESHOLD_PX = 80;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-only bottom sheet (Phase A). Slides up from the bottom of the
|
||||||
|
* viewport to host one of the existing side-panel components
|
||||||
|
* (BlocksPanel/PagesPanel/LayersPanel/AssetsPanel/GuidedStyles) unchanged,
|
||||||
|
* as the mobile replacement for the desktop fixed left/right panel columns.
|
||||||
|
* See `MobilePanelBar`, which owns which sheet (if any) is open.
|
||||||
|
*
|
||||||
|
* Deliberately NOT a generic replacement for `src/ui/Modal.tsx` (centered
|
||||||
|
* dialog chrome) -- this is anchored to the bottom, sized to ~65dvh, and
|
||||||
|
* has its own drag-handle affordance + internally scrollable body, all of
|
||||||
|
* which Modal doesn't need for its centered use cases.
|
||||||
|
*
|
||||||
|
* Phase B adds two more deferred behaviors on top of Phase A's static sheet:
|
||||||
|
* - **Swipe-to-dismiss**: a touchstart/move/end drag tracked on the handle
|
||||||
|
* row + header (not the scrollable body, so it never fights a panel's own
|
||||||
|
* vertical scroll) that follows the finger while dragging down and either
|
||||||
|
* commits to `onClose()` past `SWIPE_DISMISS_THRESHOLD_PX` or snaps back
|
||||||
|
* with a short transition otherwise.
|
||||||
|
* - **On-screen-keyboard clearance**: `useVisualViewportInsets` reports how
|
||||||
|
* much the visual viewport has shrunk from the bottom (i.e. the
|
||||||
|
* keyboard's height); that's surfaced as a `--keyboard-inset` CSS custom
|
||||||
|
* property (see editor.css) which both lifts the whole backdrop/sheet
|
||||||
|
* clear of the keyboard AND caps the sheet's own max-height so it never
|
||||||
|
* extends into the space the keyboard occupies. A `focusin` listener also
|
||||||
|
* scrolls the newly-focused input into view once the keyboard has had a
|
||||||
|
* moment to animate in, as a second line of defense for a field that's
|
||||||
|
* still off-screen after the resize alone (e.g. deep in a long panel).
|
||||||
|
*/
|
||||||
|
export const BottomSheet: React.FC<BottomSheetProps> = ({ open, onClose, title, children }) => {
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', handleKeyDown);
|
||||||
|
|
||||||
|
const prevOverflow = document.body.style.overflow;
|
||||||
|
document.body.style.overflow = 'hidden';
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', handleKeyDown);
|
||||||
|
document.body.style.overflow = prevOverflow;
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
const { keyboardInset } = useVisualViewportInsets();
|
||||||
|
|
||||||
|
const bodyRef = useRef<HTMLDivElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const bodyEl = bodyRef.current;
|
||||||
|
if (!bodyEl) return;
|
||||||
|
const handleFocusIn = (e: FocusEvent) => {
|
||||||
|
const target = e.target as HTMLElement | null;
|
||||||
|
if (!target) return;
|
||||||
|
const tag = target.tagName;
|
||||||
|
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable) {
|
||||||
|
// Give the on-screen keyboard a moment to finish animating in
|
||||||
|
// before scrolling -- doing it immediately measures the pre-keyboard
|
||||||
|
// layout and can undershoot.
|
||||||
|
window.setTimeout(() => {
|
||||||
|
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
bodyEl.addEventListener('focusin', handleFocusIn);
|
||||||
|
return () => bodyEl.removeEventListener('focusin', handleFocusIn);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
// Swipe-to-dismiss: tracked only on the handle row + header (never the
|
||||||
|
// scrollable `.mobile-sheet-body`, which needs its own vertical touch
|
||||||
|
// scrolling to keep working unimpeded).
|
||||||
|
//
|
||||||
|
// The authoritative drag distance lives in a REF (`dragOffsetRef`),
|
||||||
|
// updated synchronously and imperatively on every touchmove -- NOT solely
|
||||||
|
// in the `dragOffset` state used for rendering the drag transform. Two
|
||||||
|
// touchmoves can fire back-to-back inside the same synchronous event
|
||||||
|
// dispatch (e.g. a fast real swipe, or synthetic touch events fired
|
||||||
|
// without a yield between them), and React batches their `setDragOffset`
|
||||||
|
// calls into a single pending update that hasn't committed yet by the
|
||||||
|
// time `touchend` runs in that same tick -- reading the `dragOffset`
|
||||||
|
// STATE value directly in `handleTouchEnd` would then see a stale
|
||||||
|
// (pre-drag) value and wrongly decide the swipe didn't clear the
|
||||||
|
// threshold. The ref sidesteps that entirely (plain synchronous mutation,
|
||||||
|
// no batching). Relatedly, `onClose()` mutates an ANCESTOR component's
|
||||||
|
// state (MobileChromeContext's `closeSheet`) -- it must be called as a
|
||||||
|
// plain statement in the event handler, never from inside a `setState`
|
||||||
|
// functional updater (that runs during this component's own render phase
|
||||||
|
// and trips React's "Cannot update a component while rendering a
|
||||||
|
// different component" warning).
|
||||||
|
const dragStartYRef = useRef<number | null>(null);
|
||||||
|
const dragOffsetRef = useRef(0);
|
||||||
|
const [dragOffset, setDragOffset] = useState(0);
|
||||||
|
|
||||||
|
const handleTouchStart = useCallback((e: React.TouchEvent) => {
|
||||||
|
if (e.touches.length !== 1) return;
|
||||||
|
dragStartYRef.current = e.touches[0].clientY;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleTouchMove = useCallback((e: React.TouchEvent) => {
|
||||||
|
if (dragStartYRef.current === null) return;
|
||||||
|
const delta = e.touches[0].clientY - dragStartYRef.current;
|
||||||
|
// Only follow downward drags -- dragging up shouldn't do anything (the
|
||||||
|
// sheet is already fully open; there's no "expand further" state).
|
||||||
|
const next = Math.max(0, delta);
|
||||||
|
dragOffsetRef.current = next;
|
||||||
|
setDragOffset(next);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleTouchEnd = useCallback(() => {
|
||||||
|
dragStartYRef.current = null;
|
||||||
|
const finalOffset = dragOffsetRef.current;
|
||||||
|
dragOffsetRef.current = 0;
|
||||||
|
setDragOffset(0);
|
||||||
|
if (finalOffset > SWIPE_DISMISS_THRESHOLD_PX) onClose();
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-backdrop"
|
||||||
|
onClick={(e) => {
|
||||||
|
if (e.target === e.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
style={{ ['--keyboard-inset' as any]: `${keyboardInset}px` }}
|
||||||
|
>
|
||||||
|
{/* Deliberately NOT aria-modal: the tab bar stays reachable/operable
|
||||||
|
while a sheet is open (tapping another tab swaps sheets directly),
|
||||||
|
so the rest of the screen must not be marked inert to assistive
|
||||||
|
tech the way a true modal dialog would be. */}
|
||||||
|
<div
|
||||||
|
className="mobile-sheet"
|
||||||
|
role="dialog"
|
||||||
|
aria-label={title}
|
||||||
|
style={{
|
||||||
|
transform: dragOffset ? `translateY(${dragOffset}px)` : undefined,
|
||||||
|
transition: dragOffset ? 'none' : 'transform 0.2s ease',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-handle-row"
|
||||||
|
onTouchStart={handleTouchStart}
|
||||||
|
onTouchMove={handleTouchMove}
|
||||||
|
onTouchEnd={handleTouchEnd}
|
||||||
|
onTouchCancel={handleTouchEnd}
|
||||||
|
>
|
||||||
|
<span className="mobile-sheet-handle" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mobile-sheet-header"
|
||||||
|
onTouchStart={handleTouchStart}
|
||||||
|
onTouchMove={handleTouchMove}
|
||||||
|
onTouchEnd={handleTouchEnd}
|
||||||
|
onTouchCancel={handleTouchEnd}
|
||||||
|
>
|
||||||
|
<span className="mobile-sheet-title">{title}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-sheet-close"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label={`Close ${title}`}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="mobile-sheet-body" ref={bodyRef}>{children}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
import { describe, test, expect, vi } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { MobilePanelBar } from './MobilePanelBar';
|
||||||
|
import { MobileChromeProvider } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): the real BlocksPanel/PagesPanel/LayersPanel/
|
||||||
|
* AssetsPanel/GuidedStyles all pull in Craft.js's `useEditor` and other
|
||||||
|
* heavy dependencies not relevant here, so they're stubbed out -- this
|
||||||
|
* suite is only exercising MobilePanelBar's OWN wiring: tapping a tab opens
|
||||||
|
* that tab's sheet with only its panel rendered, tapping the active tab
|
||||||
|
* again closes it, and (mirroring MobileChromeContext.test.tsx) only one
|
||||||
|
* sheet's content is ever mounted at once.
|
||||||
|
*/
|
||||||
|
vi.mock('../left/BlocksPanel', () => ({ BlocksPanel: () => <div data-testid="panel-blocks" /> }));
|
||||||
|
vi.mock('../left/PagesPanel', () => ({ PagesPanel: () => <div data-testid="panel-pages" /> }));
|
||||||
|
vi.mock('../left/LayersPanel', () => ({ LayersPanel: () => <div data-testid="panel-layers" /> }));
|
||||||
|
vi.mock('../left/AssetsPanel', () => ({ AssetsPanel: () => <div data-testid="panel-assets" /> }));
|
||||||
|
vi.mock('../right/GuidedStyles', () => ({ GuidedStyles: () => <div data-testid="panel-styles" /> }));
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
function tabButton(label: string): HTMLButtonElement {
|
||||||
|
const buttons = Array.from(container.querySelectorAll('.mobile-tab-btn')) as HTMLButtonElement[];
|
||||||
|
const btn = buttons.find((b) => b.textContent?.includes(label));
|
||||||
|
if (!btn) throw new Error(`No tab button found for "${label}"`);
|
||||||
|
return btn;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPanelIds(): string[] {
|
||||||
|
return Array.from(container.querySelectorAll('[data-testid^="panel-"]')).map(
|
||||||
|
(el) => (el as HTMLElement).dataset.testid!,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MobilePanelBar', () => {
|
||||||
|
test('no sheet is open initially', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).toBeNull();
|
||||||
|
expect(openPanelIds()).toEqual([]);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tapping a tab opens exactly that tab\'s panel', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Blocks').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-blocks']);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('switching tabs replaces the open sheet -- only one panel mounted at a time', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Blocks').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-blocks']);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Styles').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-styles']);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Assets').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-assets']);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tapping the active tab again closes the sheet', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Pages').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual(['panel-pages']);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).not.toBeNull();
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Pages').click();
|
||||||
|
});
|
||||||
|
expect(openPanelIds()).toEqual([]);
|
||||||
|
expect(container.querySelector('.mobile-sheet-backdrop')).toBeNull();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('active tab button carries aria-pressed=true only for the open sheet', () => {
|
||||||
|
render(
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<MobilePanelBar />
|
||||||
|
</MobileChromeProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
tabButton('Layers').click();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(tabButton('Layers').getAttribute('aria-pressed')).toBe('true');
|
||||||
|
expect(tabButton('Blocks').getAttribute('aria-pressed')).toBe('false');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { BottomSheet } from './BottomSheet';
|
||||||
|
import { BlocksPanel } from '../left/BlocksPanel';
|
||||||
|
import { PagesPanel } from '../left/PagesPanel';
|
||||||
|
import { LayersPanel } from '../left/LayersPanel';
|
||||||
|
import { AssetsPanel } from '../left/AssetsPanel';
|
||||||
|
import { GuidedStyles } from '../right/GuidedStyles';
|
||||||
|
import { useMobileChrome, MobileSheetTab } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
const TABS: { id: MobileSheetTab; label: string; icon: string }[] = [
|
||||||
|
{ id: 'blocks', label: 'Blocks', icon: 'fa-cube' },
|
||||||
|
{ id: 'pages', label: 'Pages', icon: 'fa-file-o' },
|
||||||
|
{ id: 'layers', label: 'Layers', icon: 'fa-sitemap' },
|
||||||
|
{ id: 'assets', label: 'Assets', icon: 'fa-image' },
|
||||||
|
{ id: 'styles', label: 'Styles', icon: 'fa-paint-brush' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile replacement for the desktop LeftPanel/RightPanel column layout
|
||||||
|
* (Phase A). A fixed bottom tab bar (Blocks/Pages/Layers/Assets/Styles)
|
||||||
|
* toggles a single `BottomSheet` at a time, hosting the SAME panel
|
||||||
|
* component the desktop side panels use -- unchanged, so behavior/state
|
||||||
|
* stays identical, only the chrome around it differs. Tapping the active
|
||||||
|
* tab again, tapping the backdrop, the sheet's close button, or Escape all
|
||||||
|
* close the open sheet.
|
||||||
|
*
|
||||||
|
* "Styles" hosts `GuidedStyles`, which already falls back to the
|
||||||
|
* site-design panel when nothing is selected and switches to the
|
||||||
|
* per-type style panel once something is -- this is the natural place to
|
||||||
|
* edit a tapped element's styling (Phase B deepens the tap-to-select flow;
|
||||||
|
* this component only wires up the sheet, per the Phase A brief).
|
||||||
|
*
|
||||||
|
* Sheet-open state itself lives in `MobileChromeContext` (Mobile-A2), not
|
||||||
|
* a private `useState`, so Phase B can open/close a sheet from elsewhere
|
||||||
|
* (e.g. a canvas selection toolbar). The toggle-to-close-on-repeat-tap
|
||||||
|
* behavior is local to this click handler -- `openSheet` always opens.
|
||||||
|
*/
|
||||||
|
export const MobilePanelBar: React.FC = () => {
|
||||||
|
const { activeSheet, openSheet, closeSheet } = useMobileChrome();
|
||||||
|
|
||||||
|
const handleTabClick = (tab: MobileSheetTab) => {
|
||||||
|
if (activeSheet === tab) closeSheet();
|
||||||
|
else openSheet(tab);
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeLabel = TABS.find((t) => t.id === activeSheet)?.label ?? '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<BottomSheet open={activeSheet !== null} onClose={closeSheet} title={activeLabel}>
|
||||||
|
{activeSheet === 'blocks' && <BlocksPanel />}
|
||||||
|
{activeSheet === 'pages' && <PagesPanel />}
|
||||||
|
{activeSheet === 'layers' && <LayersPanel />}
|
||||||
|
{activeSheet === 'assets' && <AssetsPanel />}
|
||||||
|
{activeSheet === 'styles' && <GuidedStyles />}
|
||||||
|
</BottomSheet>
|
||||||
|
|
||||||
|
<nav className="mobile-tab-bar" aria-label="Editor panels">
|
||||||
|
{TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
type="button"
|
||||||
|
className={`mobile-tab-btn${activeSheet === tab.id ? ' active' : ''}`}
|
||||||
|
onClick={() => handleTabClick(tab.id)}
|
||||||
|
aria-pressed={activeSheet === tab.id}
|
||||||
|
>
|
||||||
|
<i className={`fa ${tab.icon}`} aria-hidden="true" />
|
||||||
|
<span>{tab.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { useEditor } from '@craftjs/core';
|
||||||
|
import { useNodeActions } from '../../hooks/useNodeActions';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase B mobile selection toolbar -- the on-canvas action bar that makes a
|
||||||
|
* tap-selected node actually EDITABLE by touch (reorder/duplicate/delete/
|
||||||
|
* select-parent/edit-styles), mirroring the desktop right-click ContextMenu.
|
||||||
|
* Both share the exact same behavior via `useNodeActions` (item 1).
|
||||||
|
*
|
||||||
|
* Mounted ONCE (in `EditorShell`'s mobile branch), reading the current
|
||||||
|
* selection from `useEditor` directly -- NOT per-node -- and positioned
|
||||||
|
* bottom-fixed just above the tab bar (simplest, robust; a node-anchored
|
||||||
|
* floating toolbar would have to constantly reposition as the canvas
|
||||||
|
* scrolls, and risks being clipped at the viewport edge for a node near the
|
||||||
|
* top or bottom of a tall page). This is a deliberate design call: see the
|
||||||
|
* report for the alternative (floating over the node) that was passed over.
|
||||||
|
*
|
||||||
|
* Hidden whenever a bottom sheet is open (`activeSheet !== null`) -- the
|
||||||
|
* sheet supersedes it, and the two must never visually stack.
|
||||||
|
*
|
||||||
|
* Delete is a two-tap in-app confirm (tap once -> the button becomes
|
||||||
|
* "Confirm?" for a few seconds; tap again within that window commits the
|
||||||
|
* delete; selecting something else cancels it) rather than a native
|
||||||
|
* `confirm()`, matching the project's no-native-dialogs rule.
|
||||||
|
*/
|
||||||
|
const DELETE_CONFIRM_TIMEOUT_MS = 3000;
|
||||||
|
|
||||||
|
export const MobileSelectionToolbar: React.FC = () => {
|
||||||
|
const { activeSheet, openSheet } = useMobileChrome();
|
||||||
|
const { selectedId } = useEditor((state) => {
|
||||||
|
const selected = state.events.selected;
|
||||||
|
const id = selected && selected.size > 0 ? (Array.from(selected)[0] as string) : null;
|
||||||
|
return { selectedId: id && id !== 'ROOT' ? id : null };
|
||||||
|
});
|
||||||
|
// Collector-free -- an always-live reference (same pattern as
|
||||||
|
// GuidedStyles.tsx/BlocksPanel.tsx), used only for imperative DOM lookups
|
||||||
|
// below (scroll-into-view), never for anything that needs to react to
|
||||||
|
// store changes on its own.
|
||||||
|
const { query } = useEditor();
|
||||||
|
|
||||||
|
const nodeActions = useNodeActions(selectedId);
|
||||||
|
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||||
|
const confirmTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
// `useNodeActions` computes canMoveUp/canMoveDown/canDelete synchronously
|
||||||
|
// from a live (never-cached) Craft.js query -- see that hook's doc comment
|
||||||
|
// for why it deliberately does NOT hold its own store subscription to force
|
||||||
|
// a refresh. Moving/duplicating/deleting via THIS toolbar changes the
|
||||||
|
// selected node's position/siblings WITHOUT changing `selectedId` itself
|
||||||
|
// (the node stays selected), so nothing else would otherwise trigger a
|
||||||
|
// re-render of this component to pick up the new boundary flags after,
|
||||||
|
// say, tapping "Move Up" until the node reaches the top. Bumping a plain
|
||||||
|
// local tick from these buttons' own click handlers -- an ordinary,
|
||||||
|
// locally-owned re-render -- covers exactly that, without the broader
|
||||||
|
// store-wide subscription that was found to trip React's "setState while
|
||||||
|
// rendering a different component" warning whenever some unrelated
|
||||||
|
// container mounts (see useNodeActions.ts).
|
||||||
|
const [, forceRefresh] = useState(0);
|
||||||
|
const bumpTick = useCallback(() => forceRefresh((n) => n + 1), []);
|
||||||
|
|
||||||
|
const clearConfirmTimeout = useCallback(() => {
|
||||||
|
if (confirmTimeoutRef.current) {
|
||||||
|
clearTimeout(confirmTimeoutRef.current);
|
||||||
|
confirmTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Reset the two-tap delete confirmation whenever the selection changes
|
||||||
|
// (including being cleared) so a stale "Confirm?" state never lingers onto
|
||||||
|
// a different node.
|
||||||
|
const prevSelectedRef = useRef(selectedId);
|
||||||
|
useEffect(() => {
|
||||||
|
if (prevSelectedRef.current !== selectedId) {
|
||||||
|
prevSelectedRef.current = selectedId;
|
||||||
|
clearConfirmTimeout();
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
}
|
||||||
|
}, [selectedId, clearConfirmTimeout]);
|
||||||
|
|
||||||
|
useEffect(() => clearConfirmTimeout, [clearConfirmTimeout]);
|
||||||
|
|
||||||
|
// Fast-follow item 3: the Styles bottom sheet covers the bottom ~65dvh of
|
||||||
|
// the canvas, so a selected node sitting anywhere in that band goes
|
||||||
|
// invisible the instant the sheet opens -- live style edits then have no
|
||||||
|
// visible effect until the user closes the sheet to check. Whenever the
|
||||||
|
// sheet becomes 'styles' (however it got opened -- currently only this
|
||||||
|
// toolbar's own "Style" button, but this is keyed on the sheet/selection
|
||||||
|
// state rather than the button tap so it stays correct if another entry
|
||||||
|
// point is added later) scroll the selected node to the top of the
|
||||||
|
// canvas's scroll area, into the sliver of screen the sheet leaves clear.
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeSheet !== 'styles' || !selectedId) return;
|
||||||
|
try {
|
||||||
|
query.node(selectedId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
}, [activeSheet, selectedId, query]);
|
||||||
|
|
||||||
|
const handleDeleteTap = useCallback(() => {
|
||||||
|
if (confirmingDelete) {
|
||||||
|
clearConfirmTimeout();
|
||||||
|
setConfirmingDelete(false);
|
||||||
|
nodeActions.deleteNode();
|
||||||
|
bumpTick();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setConfirmingDelete(true);
|
||||||
|
clearConfirmTimeout();
|
||||||
|
confirmTimeoutRef.current = setTimeout(() => setConfirmingDelete(false), DELETE_CONFIRM_TIMEOUT_MS);
|
||||||
|
}, [confirmingDelete, clearConfirmTimeout, nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleEditStyles = useCallback(() => {
|
||||||
|
openSheet('styles');
|
||||||
|
}, [openSheet]);
|
||||||
|
|
||||||
|
const handleMoveUp = useCallback(() => {
|
||||||
|
nodeActions.moveUp();
|
||||||
|
bumpTick();
|
||||||
|
}, [nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleMoveDown = useCallback(() => {
|
||||||
|
nodeActions.moveDown();
|
||||||
|
bumpTick();
|
||||||
|
}, [nodeActions, bumpTick]);
|
||||||
|
|
||||||
|
const handleDuplicate = useCallback(() => {
|
||||||
|
const newId = nodeActions.duplicate();
|
||||||
|
bumpTick();
|
||||||
|
if (!newId) return;
|
||||||
|
// Mirror BlocksPanel's tap-to-add pattern: the new node's real DOM
|
||||||
|
// element isn't attached yet the instant `duplicate()` returns (Craft.js
|
||||||
|
// mounts it asynchronously after this handler's synchronous state
|
||||||
|
// update), so defer two animation frames before reading `.dom` off the
|
||||||
|
// query, same as `handleTapToAdd` does.
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
try {
|
||||||
|
query.node(newId).get()?.dom?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
} catch {
|
||||||
|
// Best-effort scroll -- not fatal if the node/DOM isn't found.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [nodeActions, bumpTick, query]);
|
||||||
|
|
||||||
|
if (!selectedId || activeSheet !== null) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mobile-selection-toolbar" role="toolbar" aria-label="Selected element actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleMoveUp}
|
||||||
|
disabled={!nodeActions.canMoveUp}
|
||||||
|
aria-label="Move up"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-up" aria-hidden="true" />
|
||||||
|
<span>Up</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleMoveDown}
|
||||||
|
disabled={!nodeActions.canMoveDown}
|
||||||
|
aria-label="Move down"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-down" aria-hidden="true" />
|
||||||
|
<span>Down</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleDuplicate}
|
||||||
|
aria-label="Duplicate"
|
||||||
|
>
|
||||||
|
<i className="fa fa-clone" aria-hidden="true" />
|
||||||
|
<span>Copy</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={nodeActions.selectParent}
|
||||||
|
disabled={!nodeActions.canSelectParent}
|
||||||
|
aria-label="Select parent"
|
||||||
|
>
|
||||||
|
<i className="fa fa-level-up" aria-hidden="true" />
|
||||||
|
<span>Parent</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mobile-selection-toolbar-btn"
|
||||||
|
onClick={handleEditStyles}
|
||||||
|
aria-label="Edit styles"
|
||||||
|
>
|
||||||
|
<i className="fa fa-paint-brush" aria-hidden="true" />
|
||||||
|
<span>Style</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`mobile-selection-toolbar-btn danger${confirmingDelete ? ' confirming' : ''}`}
|
||||||
|
onClick={handleDeleteTap}
|
||||||
|
disabled={!nodeActions.canDelete}
|
||||||
|
aria-label={confirmingDelete ? 'Tap again to confirm delete' : 'Delete'}
|
||||||
|
>
|
||||||
|
<i className="fa fa-trash" aria-hidden="true" />
|
||||||
|
<span>{confirmingDelete ? 'Confirm?' : 'Delete'}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React from 'react';
|
import React, { useState } from 'react';
|
||||||
import {
|
import {
|
||||||
TEXT_COLORS,
|
TEXT_COLORS,
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
@@ -17,12 +17,85 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
import { ArrayItemFieldsEditor } from './ArrayItemFields';
|
||||||
|
import { Modal } from '../../../ui/Modal';
|
||||||
|
import { CodeEditor } from '../../../ui/CodeEditor';
|
||||||
|
|
||||||
|
/* ---------- "Edit HTML" modal for the HtmlBlock `code` prop ----------
|
||||||
|
`code` is raw HTML (potentially many lines, embedded <style>/<script>),
|
||||||
|
so it gets a dedicated syntax-highlighted CodeEditor in a modal instead
|
||||||
|
of falling into the generic single-line/textarea string-prop rendering
|
||||||
|
below (see GenericPropsEditor's SKIP of the `code` key). */
|
||||||
|
const HtmlCodeField: React.FC<{ value: string; onChange: (v: string) => void }> = ({ value, onChange }) => {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<CollapsibleSection title="HTML Code">
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
style={{
|
||||||
|
width: '100%', padding: '8px 12px', fontSize: 12, fontWeight: 600,
|
||||||
|
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
|
||||||
|
background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46',
|
||||||
|
borderRadius: 6, cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-code" /> Edit HTML
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<Modal open={open} onClose={() => setOpen(false)} width="min(720px, 90vw)">
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
background: 'var(--color-bg-surface)',
|
||||||
|
border: '1px solid var(--color-border)',
|
||||||
|
borderRadius: 12,
|
||||||
|
boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
overflow: 'hidden',
|
||||||
|
}}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<div style={{
|
||||||
|
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||||
|
padding: '14px 16px', borderBottom: '1px solid var(--color-border)',
|
||||||
|
}}>
|
||||||
|
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--color-text)' }}>Edit HTML</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
style={{
|
||||||
|
width: 28, height: 28, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
||||||
|
background: 'none', border: '1px solid var(--color-border)', borderRadius: 6,
|
||||||
|
color: 'var(--color-text-muted)', cursor: 'pointer', fontSize: 13,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div style={{ padding: 16 }}>
|
||||||
|
<CodeEditor value={value} onChange={onChange} language="html" height={420} />
|
||||||
|
</div>
|
||||||
|
<div style={{ padding: '10px 16px', borderTop: '1px solid var(--color-border)', display: 'flex', justifyContent: 'flex-end' }}>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
style={{
|
||||||
|
padding: '7px 20px', fontSize: 13, fontWeight: 600,
|
||||||
|
background: 'var(--color-accent)', color: '#fff', border: 'none', borderRadius: 6, cursor: 'pointer',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Done
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
|
/* ---------- SMART GENERIC PROPS EDITOR (Fallback) ---------- */
|
||||||
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Record<string, any>; typeName: string }> = ({
|
||||||
selectedId, nodeProps, typeName,
|
selectedId, nodeProps, typeName,
|
||||||
}) => {
|
}) => {
|
||||||
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass']);
|
const SKIP_PROPS = new Set(['style', 'children', 'cssId', 'cssClass', 'code']);
|
||||||
|
|
||||||
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
const { setProp: setPropValue, setPropStyle: setStyleValue } = useNodeProp(selectedId);
|
||||||
|
|
||||||
@@ -35,9 +108,15 @@ export const GenericPropsEditor: React.FC<{ selectedId: string; nodeProps: Recor
|
|||||||
const arrayProps = allProps.filter(([_, val]) => Array.isArray(val));
|
const arrayProps = allProps.filter(([_, val]) => Array.isArray(val));
|
||||||
|
|
||||||
const style = nodeProps.style || {};
|
const style = nodeProps.style || {};
|
||||||
|
const hasCodeProp = typeof nodeProps.code === 'string';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
{/* Raw HTML (HtmlBlock's `code` prop) -- dedicated CodeEditor modal */}
|
||||||
|
{hasCodeProp && (
|
||||||
|
<HtmlCodeField value={nodeProps.code} onChange={(v) => setPropValue('code', v)} />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* String props */}
|
{/* String props */}
|
||||||
{stringProps.length > 0 && (
|
{stringProps.length > 0 && (
|
||||||
<CollapsibleSection title="Properties">
|
<CollapsibleSection title="Properties">
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
|
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
||||||
|
|
||||||
/* ---------- IMAGE (with upload/browse/drop) ---------- */
|
/* ---------- IMAGE (with upload/browse/drop) ---------- */
|
||||||
export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
@@ -33,7 +34,7 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
<SectionLabel>Image Source</SectionLabel>
|
<SectionLabel>Image Source</SectionLabel>
|
||||||
<AssetPicker
|
<AssetPicker
|
||||||
value={nodeProps.src || ''}
|
value={nodeProps.src || ''}
|
||||||
onChange={(url) => actions.setProp(selectedId, (props: any) => { props.src = url; })}
|
onChange={(url) => actions.setProp(selectedId, (props: any) => { props.src = url || PLACEHOLDER_SRC; })}
|
||||||
variant="full"
|
variant="full"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
|
||||||
|
/* MediaStylePanel (via useNodeProp/ArrayPropEditor in ./shared) only needs
|
||||||
|
useEditor from @craftjs/core. Mock it following the DOM-harness pattern
|
||||||
|
used in Footer.editguard.test.tsx / AssetPicker.test.tsx (no
|
||||||
|
@testing-library/react in this repo) so setProp calls can be observed
|
||||||
|
without mounting a real <Editor> tree. */
|
||||||
|
const setPropSpy = vi.fn((_id: string, updater: (p: any) => void) => {
|
||||||
|
updater(lastProps);
|
||||||
|
});
|
||||||
|
let lastProps: any;
|
||||||
|
|
||||||
|
vi.mock('@craftjs/core', () => ({
|
||||||
|
useEditor: () => ({ actions: { setProp: setPropSpy } }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../../utils/assets', () => ({
|
||||||
|
uploadAsset: vi.fn(),
|
||||||
|
listAssets: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { MediaStylePanel } from './MediaStylePanel';
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
function q<T extends Element = Element>(testId: string): T | null {
|
||||||
|
return container.querySelector(`[data-testid="${testId}"]`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setValue(input: HTMLInputElement, value: string) {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!;
|
||||||
|
setter.call(input, value);
|
||||||
|
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
setPropSpy.mockClear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (container) unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* INT: ContentSlider (src/components/sections/ContentSlider.tsx) reads
|
||||||
|
* `slide.imageSrc` in both render and toHtml, but the Slides array editor
|
||||||
|
* here guarded on `item.image !== undefined` and wrote `image` via
|
||||||
|
* AssetPicker's onChange -- a key that ContentSlider never reads. Default
|
||||||
|
* slides (`imageSrc:''`, no `image` key) therefore showed NO image picker at
|
||||||
|
* all (the guard was never true), and even a manually-added `image` value
|
||||||
|
* was a silent no-op on export/render.
|
||||||
|
*/
|
||||||
|
describe('MediaStylePanel Slides editor uses imageSrc (INT)', () => {
|
||||||
|
test('a slide shaped like defaultSlides (imageSrc present, no `image` key) renders the image AssetPicker', () => {
|
||||||
|
lastProps = { slides: [{ type: 'image', imageSrc: '', heading: 'First Slide', text: '', bgColor: '' }] };
|
||||||
|
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
// Before the fix, the guard `item.image !== undefined` was false for
|
||||||
|
// this default-shaped slide, so no AssetPicker rendered at all.
|
||||||
|
expect(q('asset-picker-compact')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('editing the slide image writes imageSrc (not image) via setProp', () => {
|
||||||
|
lastProps = { slides: [{ type: 'image', imageSrc: '', heading: 'First Slide', text: '', bgColor: '' }] };
|
||||||
|
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
const urlInput = q<HTMLInputElement>('asset-picker-url-input')!;
|
||||||
|
expect(urlInput).not.toBeNull();
|
||||||
|
setValue(urlInput, 'https://example.com/slide.jpg');
|
||||||
|
act(() => {
|
||||||
|
urlInput.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(setPropSpy).toHaveBeenCalled();
|
||||||
|
const updatedSlide = lastProps.slides[0];
|
||||||
|
expect(updatedSlide.imageSrc).toBe('https://example.com/slide.jpg');
|
||||||
|
expect(updatedSlide.image).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adding a new slide (emptyItem) includes imageSrc, matching defaultSlides shape', () => {
|
||||||
|
lastProps = { slides: [] };
|
||||||
|
render(<MediaStylePanel selectedId="cs-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
// The "+ Add Item" button for the Slides ArrayPropEditor.
|
||||||
|
const addButtons = Array.from(container.querySelectorAll('button')).filter(
|
||||||
|
(b) => b.textContent?.includes('Add Item'),
|
||||||
|
);
|
||||||
|
expect(addButtons.length).toBeGreaterThan(0);
|
||||||
|
act(() => {
|
||||||
|
addButtons[0].dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(setPropSpy).toHaveBeenCalled();
|
||||||
|
expect(lastProps.slides).toHaveLength(1);
|
||||||
|
expect(lastProps.slides[0]).toHaveProperty('imageSrc');
|
||||||
|
expect(lastProps.slides[0].image).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -145,14 +145,14 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
});
|
});
|
||||||
}} placeholder="Text" rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
}} placeholder="Text" rows={2} style={{ ...smallInputStyle, resize: 'vertical' }} />
|
||||||
)}
|
)}
|
||||||
{item.image !== undefined && (
|
{item.imageSrc !== undefined && (
|
||||||
<AssetPicker
|
<AssetPicker
|
||||||
variant="compact"
|
variant="compact"
|
||||||
value={item.image || ''}
|
value={item.imageSrc || ''}
|
||||||
onChange={(url) => {
|
onChange={(url) => {
|
||||||
actions.setProp(selectedId, (props: any) => {
|
actions.setProp(selectedId, (props: any) => {
|
||||||
const updated = [...(props.slides || [])];
|
const updated = [...(props.slides || [])];
|
||||||
updated[index] = { ...updated[index], image: url };
|
updated[index] = { ...updated[index], imageSrc: url };
|
||||||
props.slides = updated;
|
props.slides = updated;
|
||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
@@ -160,7 +160,7 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
emptyItem={{ heading: 'New Slide', text: '', image: '' }}
|
emptyItem={{ type: 'image', imageSrc: '', heading: 'New Slide', text: '', bgColor: '' }}
|
||||||
/>
|
/>
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { defaultPresetGridColumns } from './shared';
|
||||||
|
import { RADIUS_PRESETS, SPACING_PRESETS, IMAGE_RADIUS_PRESETS, FONT_WEIGHTS, TEXT_SIZES, FONT_FAMILIES } from '../../../constants/presets';
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Regression: 5-item preset sets (RADIUS_PRESETS, SPACING_PRESETS,
|
||||||
|
* IMAGE_RADIUS_PRESETS, FONT_WEIGHTS, and NavStylePanel's ad-hoc
|
||||||
|
* GAP_PRESETS) left a lone orphan button on its own row under the old
|
||||||
|
* fixed 4-column .preset-grid. PresetButtonGrid now derives a column
|
||||||
|
* count from the preset length instead.
|
||||||
|
*/
|
||||||
|
describe('defaultPresetGridColumns', () => {
|
||||||
|
it('gives 5-item sets their own single row (no orphan)', () => {
|
||||||
|
expect(defaultPresetGridColumns(RADIUS_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(SPACING_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(IMAGE_RADIUS_PRESETS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(FONT_WEIGHTS.length)).toBe(5);
|
||||||
|
expect(defaultPresetGridColumns(5)).toBe(5); // NavStylePanel's GAP_PRESETS
|
||||||
|
});
|
||||||
|
|
||||||
|
it('splits 6-item sets into two even rows of 3 (was 4+2 uneven)', () => {
|
||||||
|
expect(defaultPresetGridColumns(TEXT_SIZES.length)).toBe(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the classic 4-column grid for sets that already divide evenly', () => {
|
||||||
|
expect(defaultPresetGridColumns(FONT_FAMILIES.length)).toBe(4); // 8 items
|
||||||
|
expect(defaultPresetGridColumns(4)).toBe(4);
|
||||||
|
expect(defaultPresetGridColumns(3)).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never leaves a single orphan on the final row for any count 1-12', () => {
|
||||||
|
for (let n = 1; n <= 12; n++) {
|
||||||
|
const cols = defaultPresetGridColumns(n);
|
||||||
|
const isLoneOrphan = n > cols && n % cols === 1;
|
||||||
|
expect(isLoneOrphan).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import { describe, test, expect, vi } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import {
|
||||||
|
NumericUnitInput,
|
||||||
|
parseCssLength,
|
||||||
|
SizeControl,
|
||||||
|
AspectRatioControl,
|
||||||
|
parseAspectRatioInput,
|
||||||
|
FocalPointGrid,
|
||||||
|
FOCAL_POINTS,
|
||||||
|
SpacingControl,
|
||||||
|
BorderControl,
|
||||||
|
buildBorderShorthand,
|
||||||
|
AnimationControl,
|
||||||
|
ANIMATIONS,
|
||||||
|
VisibilityControl,
|
||||||
|
} from './shared';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as AssetPicker.test.tsx / ImageBlock.render.test.tsx
|
||||||
|
(no @testing-library/react in this repo). */
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
function click(el: Element | null) {
|
||||||
|
if (!el) throw new Error('element not found');
|
||||||
|
act(() => { (el as HTMLElement).dispatchEvent(new MouseEvent('click', { bubbles: true })); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function setValue(input: HTMLInputElement | HTMLSelectElement, value: string) {
|
||||||
|
const proto = input instanceof HTMLSelectElement ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype;
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(proto, 'value')!.set!;
|
||||||
|
setter.call(input, value);
|
||||||
|
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function blur(el: Element) {
|
||||||
|
act(() => { el.dispatchEvent(new FocusEvent('blur', { bubbles: true })); el.dispatchEvent(new FocusEvent('focusout', { bubbles: true })); });
|
||||||
|
}
|
||||||
|
|
||||||
|
function q<T extends Element = Element>(testId: string): T | null {
|
||||||
|
return container.querySelector(`[data-testid="${testId}"]`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- NumericUnitInput / parseCssLength ---------- */
|
||||||
|
describe('parseCssLength', () => {
|
||||||
|
test('parses "16px" into number 16 + unit px', () => {
|
||||||
|
expect(parseCssLength('16px')).toEqual({ num: '16', unit: 'px' });
|
||||||
|
});
|
||||||
|
test('parses "50%" into number 50 + unit %', () => {
|
||||||
|
expect(parseCssLength('50%', ['px', '%'])).toEqual({ num: '50', unit: '%' });
|
||||||
|
});
|
||||||
|
test('treats "auto" and "" as empty', () => {
|
||||||
|
expect(parseCssLength('auto')).toEqual({ num: '', unit: 'px' });
|
||||||
|
expect(parseCssLength('')).toEqual({ num: '', unit: 'px' });
|
||||||
|
expect(parseCssLength(undefined)).toEqual({ num: '', unit: 'px' });
|
||||||
|
});
|
||||||
|
test('falls back to the first configured unit for an unrecognized unit', () => {
|
||||||
|
expect(parseCssLength('16vh', ['px', '%'])).toEqual({ num: '16', unit: 'px' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('NumericUnitInput', () => {
|
||||||
|
test('renders the parsed number and unit from a "16px" value', () => {
|
||||||
|
render(<NumericUnitInput value="16px" onChange={vi.fn()} />);
|
||||||
|
expect(q<HTMLInputElement>('numeric-unit-number')!.value).toBe('16');
|
||||||
|
expect(q<HTMLSelectElement>('numeric-unit-unit')!.value).toBe('px');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('changing the number emits the recombined string', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<NumericUnitInput value="16px" onChange={onChange} />);
|
||||||
|
setValue(q<HTMLInputElement>('numeric-unit-number')!, '32');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('32px');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('changing the unit re-emits with the current number', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<NumericUnitInput value="16px" onChange={onChange} />);
|
||||||
|
setValue(q<HTMLSelectElement>('numeric-unit-unit')!, '%');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('16%');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clearing the number emits empty string, not "0px"', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<NumericUnitInput value="16px" onChange={onChange} />);
|
||||||
|
setValue(q<HTMLInputElement>('numeric-unit-number')!, '');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('omits the unit <select> when only one unit is configured', () => {
|
||||||
|
render(<NumericUnitInput value="1px" onChange={vi.fn()} units={['px']} />);
|
||||||
|
expect(q('numeric-unit-unit')).toBeNull();
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- SizeControl ---------- */
|
||||||
|
describe('SizeControl', () => {
|
||||||
|
test('clicking a preset button emits its value', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<SizeControl label="Width" value="" onChange={onChange} />);
|
||||||
|
const buttons = container.querySelectorAll('[data-testid="size-control"] .preset-btn');
|
||||||
|
const hundred = Array.from(buttons).find((b) => b.textContent === '100%')!;
|
||||||
|
click(hundred);
|
||||||
|
expect(onChange).toHaveBeenCalledWith('100%');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('custom numeric input emits a non-preset value', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<SizeControl label="Width" value="" onChange={onChange} />);
|
||||||
|
setValue(q<HTMLInputElement>('size-control-custom-number')!, '400');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('400px');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- AspectRatioControl / parseAspectRatioInput ---------- */
|
||||||
|
describe('parseAspectRatioInput', () => {
|
||||||
|
test('parses "16:9" into "16 / 9"', () => {
|
||||||
|
expect(parseAspectRatioInput('16:9')).toBe('16 / 9');
|
||||||
|
});
|
||||||
|
test('accepts "16/9" and "16x9" separators too', () => {
|
||||||
|
expect(parseAspectRatioInput('16/9')).toBe('16 / 9');
|
||||||
|
expect(parseAspectRatioInput('16x9')).toBe('16 / 9');
|
||||||
|
});
|
||||||
|
test('returns empty string for unparseable input', () => {
|
||||||
|
expect(parseAspectRatioInput('not-a-ratio')).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('AspectRatioControl', () => {
|
||||||
|
test('clicking the 16:9 preset emits "16 / 9"', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<AspectRatioControl value="" onChange={onChange} />);
|
||||||
|
const buttons = container.querySelectorAll('[data-testid="aspect-ratio-control"] .preset-btn');
|
||||||
|
const btn = Array.from(buttons).find((b) => b.textContent === '16:9')!;
|
||||||
|
click(btn);
|
||||||
|
expect(onChange).toHaveBeenCalledWith('16 / 9');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking Original emits empty string', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<AspectRatioControl value="1 / 1" onChange={onChange} />);
|
||||||
|
const buttons = container.querySelectorAll('[data-testid="aspect-ratio-control"] .preset-btn');
|
||||||
|
const btn = Array.from(buttons).find((b) => b.textContent === 'Original')!;
|
||||||
|
click(btn);
|
||||||
|
expect(onChange).toHaveBeenCalledWith('');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('typing a custom "16:9" and blurring emits "16 / 9"', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<AspectRatioControl value="" onChange={onChange} />);
|
||||||
|
const input = q<HTMLInputElement>('aspect-ratio-custom-input')!;
|
||||||
|
setValue(input, '16:9');
|
||||||
|
blur(input);
|
||||||
|
expect(onChange).toHaveBeenCalledWith('16 / 9');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- FocalPointGrid ---------- */
|
||||||
|
describe('FocalPointGrid', () => {
|
||||||
|
test('has 9 cells matching FOCAL_POINTS', () => {
|
||||||
|
render(<FocalPointGrid value="center" onChange={vi.fn()} />);
|
||||||
|
const cells = container.querySelectorAll('[data-testid="focal-point-grid"] button');
|
||||||
|
expect(cells.length).toBe(9);
|
||||||
|
expect(FOCAL_POINTS.length).toBe(9);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clicking a cell emits its object-position value', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<FocalPointGrid value="center" onChange={onChange} />);
|
||||||
|
click(q('focal-point-left-top'));
|
||||||
|
expect(onChange).toHaveBeenCalledWith('left top');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the active cell is visually highlighted (distinct background)', () => {
|
||||||
|
render(<FocalPointGrid value="right bottom" onChange={vi.fn()} />);
|
||||||
|
const active = q<HTMLButtonElement>('focal-point-right-bottom')!;
|
||||||
|
const inactive = q<HTMLButtonElement>('focal-point-center')!;
|
||||||
|
expect(active.style.background).not.toBe(inactive.style.background);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('defaults the highlight to center when value is empty', () => {
|
||||||
|
render(<FocalPointGrid value="" onChange={vi.fn()} />);
|
||||||
|
const center = q<HTMLButtonElement>('focal-point-center')!;
|
||||||
|
const other = q<HTMLButtonElement>('focal-point-left-top')!;
|
||||||
|
expect(center.style.background).not.toBe(other.style.background);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- SpacingControl ---------- */
|
||||||
|
describe('SpacingControl', () => {
|
||||||
|
test('linked mode: editing the shared field emits onChange for all 4 sides with the same value', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<SpacingControl label="Margin" value={{}} onChange={onChange} />);
|
||||||
|
setValue(q<HTMLInputElement>('spacing-linked-number')!, '16');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('top', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('right', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('bottom', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('left', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledTimes(4);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a preset fills all sides with the preset value', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<SpacingControl label="Padding" value={{}} onChange={onChange} />);
|
||||||
|
const buttons = container.querySelectorAll('[data-testid="spacing-control"] .preset-btn');
|
||||||
|
const medium = Array.from(buttons).find((b) => b.textContent === 'M')!;
|
||||||
|
click(medium);
|
||||||
|
expect(onChange).toHaveBeenCalledWith('top', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('left', '16px');
|
||||||
|
expect(onChange).toHaveBeenCalledTimes(4);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unlinking lets each side emit independently', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<SpacingControl label="Margin" value={{ top: '4px', right: '4px', bottom: '4px', left: '4px' }} onChange={onChange} />);
|
||||||
|
click(q('spacing-link-toggle'));
|
||||||
|
setValue(q<HTMLInputElement>('spacing-top-number')!, '20');
|
||||||
|
expect(onChange).toHaveBeenCalledWith('top', '20px');
|
||||||
|
expect(onChange).toHaveBeenCalledTimes(1);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- BorderControl ---------- */
|
||||||
|
describe('BorderControl', () => {
|
||||||
|
test('changing width/style/color merges into the full BorderValue object', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
const value = { width: '1px', style: 'solid', color: '#000000' };
|
||||||
|
render(<BorderControl value={value} onChange={onChange} />);
|
||||||
|
setValue(q<HTMLSelectElement>('border-style-select')!, 'dashed');
|
||||||
|
expect(onChange).toHaveBeenCalledWith({ width: '1px', style: 'dashed', color: '#000000' });
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildBorderShorthand builds a CSS border shorthand', () => {
|
||||||
|
expect(buildBorderShorthand({ width: '2px', style: 'solid', color: '#3b82f6' })).toBe('2px solid #3b82f6');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildBorderShorthand returns "none" when style is none or width is empty', () => {
|
||||||
|
expect(buildBorderShorthand({ width: '2px', style: 'none', color: '#000' })).toBe('none');
|
||||||
|
expect(buildBorderShorthand({ width: '', style: 'solid', color: '#000' })).toBe('none');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- AnimationControl ---------- */
|
||||||
|
describe('AnimationControl', () => {
|
||||||
|
test('ANIMATIONS matches the exact data-animation values html-export.ts supports', () => {
|
||||||
|
expect(ANIMATIONS.map((a) => a.value)).toEqual([
|
||||||
|
'none', 'fade-in', 'slide-up', 'slide-left', 'slide-right', 'zoom-in', 'bounce',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('selecting an animation emits { animation, animationDelay }', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<AnimationControl value={{ animation: 'none' }} onChange={onChange} />);
|
||||||
|
const buttons = container.querySelectorAll('[data-testid="animation-control"] .preset-btn');
|
||||||
|
const fadeIn = Array.from(buttons).find((b) => b.textContent === 'Fade In')!;
|
||||||
|
click(fadeIn);
|
||||||
|
expect(onChange).toHaveBeenCalledWith({ animation: 'fade-in', animationDelay: '0' });
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the delay input is hidden when animation is "none" and shown otherwise', () => {
|
||||||
|
render(<AnimationControl value={{ animation: 'none' }} onChange={vi.fn()} />);
|
||||||
|
expect(q('animation-delay-input')).toBeNull();
|
||||||
|
unmount();
|
||||||
|
|
||||||
|
render(<AnimationControl value={{ animation: 'bounce', animationDelay: '0.5' }} onChange={vi.fn()} />);
|
||||||
|
expect(q<HTMLInputElement>('animation-delay-input')!.value).toBe('0.5');
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('changing the delay emits the current animation with the new delay', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<AnimationControl value={{ animation: 'zoom-in', animationDelay: '0' }} onChange={onChange} />);
|
||||||
|
setValue(q<HTMLInputElement>('animation-delay-input')!, '0.3');
|
||||||
|
expect(onChange).toHaveBeenCalledWith({ animation: 'zoom-in', animationDelay: '0.3' });
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- VisibilityControl ---------- */
|
||||||
|
describe('VisibilityControl', () => {
|
||||||
|
test('emits the exact hideOnDesktop/hideOnTablet/hideOnMobile prop names', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<VisibilityControl value={{}} onChange={onChange} />);
|
||||||
|
click(q('visibility-hideOnDesktop'));
|
||||||
|
expect(onChange).toHaveBeenCalledWith({ hideOnDesktop: true });
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('toggling reflects existing true values back to false', () => {
|
||||||
|
const onChange = vi.fn();
|
||||||
|
render(<VisibilityControl value={{ hideOnMobile: true }} onChange={onChange} />);
|
||||||
|
click(q('visibility-hideOnMobile'));
|
||||||
|
expect(onChange).toHaveBeenCalledWith({ hideOnMobile: false });
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('checkboxes reflect the initial value', () => {
|
||||||
|
render(<VisibilityControl value={{ hideOnTablet: true }} onChange={vi.fn()} />);
|
||||||
|
expect(q<HTMLInputElement>('visibility-hideOnDesktop')!.checked).toBe(false);
|
||||||
|
expect(q<HTMLInputElement>('visibility-hideOnTablet')!.checked).toBe(true);
|
||||||
|
expect(q<HTMLInputElement>('visibility-hideOnMobile')!.checked).toBe(false);
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,6 +2,10 @@ import React, { useState, useCallback, CSSProperties } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
GRADIENTS,
|
GRADIENTS,
|
||||||
|
SIZE_PRESETS,
|
||||||
|
ASPECT_RATIOS,
|
||||||
|
SPACING_PRESETS,
|
||||||
|
BORDER_STYLES,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import { uploadAsset } from '../../../utils/assets';
|
import { uploadAsset } from '../../../utils/assets';
|
||||||
|
|
||||||
@@ -84,9 +88,30 @@ interface PresetButtonGridProps {
|
|||||||
presets: { label: string; value: string }[];
|
presets: { label: string; value: string }[];
|
||||||
activeValue: string | undefined;
|
activeValue: string | undefined;
|
||||||
onSelect: (value: string) => void;
|
onSelect: (value: string) => void;
|
||||||
|
/** Explicit column count. When omitted, a column count is derived from
|
||||||
|
* `presets.length` (see `defaultPresetGridColumns`) so odd-sized preset
|
||||||
|
* sets (5, 6, ...) don't leave a lone orphan button dangling on its own
|
||||||
|
* row under the fixed 4-column grid. */
|
||||||
|
columns?: number;
|
||||||
}
|
}
|
||||||
export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, activeValue, onSelect }) => (
|
|
||||||
<div className="preset-grid">
|
/** Picks a column count that avoids a single orphan on the last row.
|
||||||
|
* 4-or-fewer presets keep the classic single row of 4. 5 gets its own
|
||||||
|
* row (5 cols). 6 splits into two even rows of 3. Anything else falls
|
||||||
|
* back to a 4- or 3-column grid depending on which divides evenly. */
|
||||||
|
export function defaultPresetGridColumns(count: number): number {
|
||||||
|
if (count <= 4) return 4;
|
||||||
|
if (count === 5) return 5;
|
||||||
|
if (count === 6) return 3;
|
||||||
|
if (count % 4 === 0) return 4;
|
||||||
|
if (count % 3 === 0) return 3;
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, activeValue, onSelect, columns }) => {
|
||||||
|
const cols = columns ?? defaultPresetGridColumns(presets.length);
|
||||||
|
return (
|
||||||
|
<div className="preset-grid" style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}>
|
||||||
{presets.map((p) => (
|
{presets.map((p) => (
|
||||||
<button
|
<button
|
||||||
key={p.value}
|
key={p.value}
|
||||||
@@ -97,7 +122,8 @@ export const PresetButtonGrid: React.FC<PresetButtonGridProps> = ({ presets, act
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
interface GradientSwatchGridProps {
|
interface GradientSwatchGridProps {
|
||||||
activeValue: string | undefined;
|
activeValue: string | undefined;
|
||||||
@@ -350,3 +376,379 @@ export const ArrayPropEditor: React.FC<ArrayPropEditorProps> = ({ selectedId, pr
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/* =========================================================================
|
||||||
|
ENH-Foundation: reusable StylePanel controls
|
||||||
|
---------------------------------------------------------------------
|
||||||
|
Presentational (value + onChange) controls shared by upcoming feature
|
||||||
|
panels (size/spacing/border/typography/animation/visibility rollout).
|
||||||
|
Nothing below is wired into any feature panel yet -- that's the job of
|
||||||
|
the downstream feature branches. Each control's onChange API is
|
||||||
|
documented on its props interface; see
|
||||||
|
.superpowers/sdd/task-enh-foundation-report.md for the consolidated list.
|
||||||
|
========================================================================= */
|
||||||
|
|
||||||
|
/* ---------- NumericUnitInput ----------
|
||||||
|
A number field + unit dropdown that parses/holds a CSS length string
|
||||||
|
("16px", "50%", "auto", "") and calls onChange(nextString).
|
||||||
|
- Clearing the number field emits '' (not '0px') -- lets the consumer
|
||||||
|
treat '' as "unset/inherit" instead of forcing a 0 value.
|
||||||
|
- value === 'auto' or '' both display as a blank number field (with the
|
||||||
|
`placeholder` -- default "auto" -- shown as a hint).
|
||||||
|
- Changing the unit re-emits with the current number and the new unit;
|
||||||
|
if the number is blank, changing the unit is a no-op (still emits '').
|
||||||
|
- `units` is configurable (default ['px','%']); the unit <select> is
|
||||||
|
omitted entirely when only one unit is passed. */
|
||||||
|
export function parseCssLength(value: string | undefined, units: string[] = ['px', '%']): { num: string; unit: string } {
|
||||||
|
if (!value || value === 'auto') return { num: '', unit: units[0] };
|
||||||
|
const m = String(value).trim().match(/^(-?\d*\.?\d+)\s*([a-zA-Z%]*)$/);
|
||||||
|
if (!m) return { num: '', unit: units[0] };
|
||||||
|
const unit = m[2] || units[0];
|
||||||
|
return { num: m[1], unit: units.includes(unit) ? unit : units[0] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NumericUnitInputProps {
|
||||||
|
/** CSS length string, e.g. "16px" / "50%" / "auto" / "". */
|
||||||
|
value: string;
|
||||||
|
/** Called with the recombined string, e.g. "16px". Called with '' when the
|
||||||
|
* number field is cleared. */
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
/** Allowed unit list; default ['px', '%']. Unit <select> is hidden when
|
||||||
|
* this has length 1. */
|
||||||
|
units?: string[];
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
step?: number;
|
||||||
|
placeholder?: string;
|
||||||
|
/** Base for the data-testid attrs (`${testId}`, `${testId}-number`,
|
||||||
|
* `${testId}-unit`); default 'numeric-unit'. */
|
||||||
|
testId?: string;
|
||||||
|
}
|
||||||
|
export const NumericUnitInput: React.FC<NumericUnitInputProps> = ({
|
||||||
|
value, onChange, units = ['px', '%'], min, max, step, placeholder = 'auto', testId = 'numeric-unit',
|
||||||
|
}) => {
|
||||||
|
const { num, unit } = parseCssLength(value, units);
|
||||||
|
const emit = (nextNum: string, nextUnit: string) => {
|
||||||
|
if (nextNum === '') { onChange(''); return; }
|
||||||
|
onChange(`${nextNum}${nextUnit}`);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'flex', gap: 4 }} data-testid={testId}>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
data-testid={`${testId}-number`}
|
||||||
|
value={num}
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
step={step}
|
||||||
|
placeholder={placeholder}
|
||||||
|
onChange={(e) => emit(e.target.value, unit)}
|
||||||
|
style={{ ...inputStyle, flex: 1 }}
|
||||||
|
/>
|
||||||
|
{units.length > 1 && (
|
||||||
|
<select
|
||||||
|
data-testid={`${testId}-unit`}
|
||||||
|
value={unit}
|
||||||
|
onChange={(e) => emit(num, e.target.value)}
|
||||||
|
style={{ ...inputStyle, width: 60, flex: 'none' }}
|
||||||
|
>
|
||||||
|
{units.map((u) => <option key={u} value={u}>{u}</option>)}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- SizeControl ----------
|
||||||
|
Width (or height) editor: preset buttons (25/50/75/100%, Auto, Full) +
|
||||||
|
a custom NumericUnitInput. One dimension per instance -- render two
|
||||||
|
(label="Width" / label="Height") for components needing both, e.g.
|
||||||
|
ImageBlock / VideoBlock sizing. */
|
||||||
|
export interface SizeControlProps {
|
||||||
|
label: string;
|
||||||
|
/** CSS value for this one dimension, e.g. "100%" / "400px" / "auto" / "". */
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
presets?: { label: string; value: string }[];
|
||||||
|
units?: string[];
|
||||||
|
}
|
||||||
|
export const SizeControl: React.FC<SizeControlProps> = ({ label, value, onChange, presets = SIZE_PRESETS, units = ['px', '%'] }) => (
|
||||||
|
<div className="guided-section" data-testid="size-control">
|
||||||
|
<SectionLabel>{label}</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={presets} activeValue={value} onSelect={onChange} />
|
||||||
|
<div style={{ marginTop: 6 }}>
|
||||||
|
<NumericUnitInput
|
||||||
|
value={presets.some((p) => p.value === value) ? '' : value}
|
||||||
|
onChange={onChange}
|
||||||
|
units={units}
|
||||||
|
testId="size-control-custom"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
/* ---------- AspectRatioControl ----------
|
||||||
|
Preset buttons + a custom "W:H" text entry. Emits a CSS `aspect-ratio`
|
||||||
|
value, e.g. "16 / 9". 'Original' emits ''. Custom entry accepts
|
||||||
|
"16:9" / "16/9" / "16x9" and is parsed on blur or Enter. */
|
||||||
|
export function parseAspectRatioInput(raw: string): string {
|
||||||
|
const m = raw.trim().match(/^(\d+(?:\.\d+)?)\s*[:xX/]\s*(\d+(?:\.\d+)?)$/);
|
||||||
|
if (!m) return '';
|
||||||
|
return `${m[1]} / ${m[2]}`;
|
||||||
|
}
|
||||||
|
function formatAspectRatioForInput(value: string): string {
|
||||||
|
const m = value.match(/^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/);
|
||||||
|
return m ? `${m[1]}:${m[2]}` : '';
|
||||||
|
}
|
||||||
|
export interface AspectRatioControlProps {
|
||||||
|
/** CSS `aspect-ratio` value, e.g. "16 / 9", or '' for Original/unset. */
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
presets?: { label: string; value: string }[];
|
||||||
|
}
|
||||||
|
export const AspectRatioControl: React.FC<AspectRatioControlProps> = ({ value, onChange, presets = ASPECT_RATIOS }) => {
|
||||||
|
const [custom, setCustom] = useState(() => formatAspectRatioForInput(value));
|
||||||
|
|
||||||
|
const applyCustom = () => onChange(parseAspectRatioInput(custom));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="guided-section" data-testid="aspect-ratio-control">
|
||||||
|
<SectionLabel>Aspect Ratio</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={presets} activeValue={value} onSelect={(v) => { onChange(v); setCustom(''); }} />
|
||||||
|
<div style={{ marginTop: 6 }}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
data-testid="aspect-ratio-custom-input"
|
||||||
|
value={custom}
|
||||||
|
placeholder="W:H e.g. 16:9"
|
||||||
|
onChange={(e) => setCustom(e.target.value)}
|
||||||
|
onBlur={applyCustom}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') applyCustom(); }}
|
||||||
|
style={{ ...inputStyle }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- FocalPointGrid ----------
|
||||||
|
3x3 grid of buttons mapping to CSS `object-position` keyword pairs.
|
||||||
|
Used for image crop framing (object-position on an ImageBlock/VideoBlock
|
||||||
|
with object-fit: cover). Highlights the active cell; defaults the
|
||||||
|
highlight to 'center' when value is empty. */
|
||||||
|
export const FOCAL_POINTS: { label: string; value: string }[] = [
|
||||||
|
{ label: '↖', value: 'left top' }, { label: '↑', value: 'center top' }, { label: '↗', value: 'right top' },
|
||||||
|
{ label: '←', value: 'left center' }, { label: '•', value: 'center' }, { label: '→', value: 'right center' },
|
||||||
|
{ label: '↙', value: 'left bottom' }, { label: '↓', value: 'center bottom' }, { label: '↘', value: 'right bottom' },
|
||||||
|
];
|
||||||
|
export interface FocalPointGridProps {
|
||||||
|
/** CSS `object-position` value, e.g. "center" / "left top". */
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
}
|
||||||
|
export const FocalPointGrid: React.FC<FocalPointGridProps> = ({ value, onChange }) => {
|
||||||
|
const active = value || 'center';
|
||||||
|
return (
|
||||||
|
<div className="guided-section" data-testid="focal-point-grid">
|
||||||
|
<SectionLabel>Focal Point</SectionLabel>
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 4, width: 96 }}>
|
||||||
|
{FOCAL_POINTS.map((p) => (
|
||||||
|
<button
|
||||||
|
key={p.value}
|
||||||
|
data-testid={`focal-point-${p.value.replace(/\s+/g, '-')}`}
|
||||||
|
onClick={() => onChange(p.value)}
|
||||||
|
title={p.value}
|
||||||
|
style={{
|
||||||
|
aspectRatio: '1', border: '1px solid #3f3f46', borderRadius: 4, cursor: 'pointer',
|
||||||
|
background: active === p.value ? '#3b82f6' : '#27272a',
|
||||||
|
color: active === p.value ? '#fff' : '#71717a', fontSize: 12,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{p.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- SpacingControl ----------
|
||||||
|
Margin OR padding, per-side, with a link/unlink toggle.
|
||||||
|
API: onChange(side, value) -- called once per side. In linked mode
|
||||||
|
(default), editing the single shared field or clicking a preset calls
|
||||||
|
onChange for all four sides ('top','right','bottom','left') with the
|
||||||
|
same value so the consumer can setPropStyle each side independently
|
||||||
|
(e.g. marginTop/marginRight/marginBottom/marginLeft). In unlinked mode
|
||||||
|
each side's NumericUnitInput calls onChange for just that side. */
|
||||||
|
export type SpacingSide = 'top' | 'right' | 'bottom' | 'left';
|
||||||
|
export interface SpacingSideValues { top?: string; right?: string; bottom?: string; left?: string; }
|
||||||
|
const SPACING_SIDES: SpacingSide[] = ['top', 'right', 'bottom', 'left'];
|
||||||
|
export interface SpacingControlProps {
|
||||||
|
label: string;
|
||||||
|
value: SpacingSideValues;
|
||||||
|
/** Called per-side. Linked edits/presets call this once for each of the
|
||||||
|
* 4 sides (in top/right/bottom/left order) with the same value. */
|
||||||
|
onChange: (side: SpacingSide, value: string) => void;
|
||||||
|
presets?: { label: string; value: string }[];
|
||||||
|
units?: string[];
|
||||||
|
}
|
||||||
|
export const SpacingControl: React.FC<SpacingControlProps> = ({ label, value, onChange, presets = SPACING_PRESETS, units = ['px', '%', 'em', 'rem'] }) => {
|
||||||
|
const [linked, setLinked] = useState(true);
|
||||||
|
|
||||||
|
const applyToAllSides = (v: string) => SPACING_SIDES.forEach((s) => onChange(s, v));
|
||||||
|
const linkedValue = value.top ?? '';
|
||||||
|
const isAllEqual = SPACING_SIDES.every((s) => (value[s] ?? '') === linkedValue);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="guided-section" data-testid="spacing-control">
|
||||||
|
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||||
|
<SectionLabel>{label}</SectionLabel>
|
||||||
|
<button
|
||||||
|
data-testid="spacing-link-toggle"
|
||||||
|
onClick={() => setLinked(!linked)}
|
||||||
|
title={linked ? 'Unlink sides' : 'Link sides'}
|
||||||
|
style={{ background: 'none', border: 'none', color: linked ? '#3b82f6' : '#71717a', cursor: 'pointer', padding: 2 }}
|
||||||
|
>
|
||||||
|
<i className={`fa fa-link${linked ? '' : '-slash'}`} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<PresetButtonGrid presets={presets} activeValue={isAllEqual ? linkedValue : undefined} onSelect={applyToAllSides} />
|
||||||
|
{linked ? (
|
||||||
|
<div style={{ marginTop: 6 }}>
|
||||||
|
<NumericUnitInput value={linkedValue} onChange={applyToAllSides} units={units} testId="spacing-linked" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginTop: 6 }}>
|
||||||
|
{SPACING_SIDES.map((s) => (
|
||||||
|
<div key={s}>
|
||||||
|
<label style={{ ...labelStyle, fontSize: 9 }}>{s}</label>
|
||||||
|
<NumericUnitInput value={value[s] ?? ''} onChange={(v) => onChange(s, v)} units={units} testId={`spacing-${s}`} />
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- BorderControl ----------
|
||||||
|
Width (px) + style (none/solid/dashed/dotted) + color. Single onChange
|
||||||
|
receives the merged { width, style, color } object so the consumer can
|
||||||
|
either setProp each part or build a shorthand via buildBorderShorthand()
|
||||||
|
(returns 'none' when width is falsy or style is 'none'). */
|
||||||
|
export interface BorderValue { width: string; style: string; color: string; }
|
||||||
|
export interface BorderControlProps {
|
||||||
|
value: BorderValue;
|
||||||
|
onChange: (value: BorderValue) => void;
|
||||||
|
label?: string;
|
||||||
|
}
|
||||||
|
export const BorderControl: React.FC<BorderControlProps> = ({ value, onChange, label = 'Border' }) => {
|
||||||
|
const set = (patch: Partial<BorderValue>) => onChange({ ...value, ...patch });
|
||||||
|
return (
|
||||||
|
<div className="guided-section" data-testid="border-control">
|
||||||
|
<SectionLabel>{label}</SectionLabel>
|
||||||
|
<div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<NumericUnitInput value={value.width} onChange={(v) => set({ width: v })} units={['px']} placeholder="0" testId="border-width" />
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
data-testid="border-style-select"
|
||||||
|
value={value.style}
|
||||||
|
onChange={(e) => set({ style: e.target.value })}
|
||||||
|
style={{ ...inputStyle, flex: 1 }}
|
||||||
|
>
|
||||||
|
{BORDER_STYLES.map((s) => <option key={s.value} value={s.value}>{s.label}</option>)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<ColorPickerField label="Border Color" value={value.color} onChange={(v) => set({ color: v })} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
export function buildBorderShorthand(value: BorderValue): string {
|
||||||
|
if (!value.width || !value.style || value.style === 'none') return 'none';
|
||||||
|
return `${value.width} ${value.style} ${value.color || '#000000'}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- AnimationControl ----------
|
||||||
|
"Entrance animation" picker + optional delay. Emits the EXACT prop names
|
||||||
|
the export machinery already consumes (verified against buildDataAttrs()
|
||||||
|
in src/utils/html-export.ts): `animation` and `animationDelay`.
|
||||||
|
NOTE: the export supports fade-in / slide-up / slide-left / slide-right /
|
||||||
|
zoom-in / bounce (no "slide-down" -- html-export.ts has no such variant;
|
||||||
|
slide-left/slide-right exist instead), so ANIMATIONS reflects that exact
|
||||||
|
set rather than guessing. animationDelay is a plain seconds string (e.g.
|
||||||
|
"0.3") -- html-export.ts's inline script assigns it straight to
|
||||||
|
el.style.animationDelay, so consumers should suffix/accept a unit-bearing
|
||||||
|
string like "0.3s" if that's what they choose to store; this control
|
||||||
|
stores/edits the raw numeric string and leaves unit formatting to the
|
||||||
|
caller (kept as the simplest contract; see report for the exact
|
||||||
|
behavior verified against html-export.ts). */
|
||||||
|
export const ANIMATIONS: { label: string; value: string }[] = [
|
||||||
|
{ label: 'None', value: 'none' },
|
||||||
|
{ label: 'Fade In', value: 'fade-in' },
|
||||||
|
{ label: 'Slide Up', value: 'slide-up' },
|
||||||
|
{ label: 'Slide Left', value: 'slide-left' },
|
||||||
|
{ label: 'Slide Right', value: 'slide-right' },
|
||||||
|
{ label: 'Zoom In', value: 'zoom-in' },
|
||||||
|
{ label: 'Bounce', value: 'bounce' },
|
||||||
|
];
|
||||||
|
export interface AnimationValue { animation: string; animationDelay?: string; }
|
||||||
|
export interface AnimationControlProps {
|
||||||
|
value: AnimationValue;
|
||||||
|
onChange: (value: AnimationValue) => void;
|
||||||
|
}
|
||||||
|
export const AnimationControl: React.FC<AnimationControlProps> = ({ value, onChange }) => {
|
||||||
|
const animation = value.animation || 'none';
|
||||||
|
const animationDelay = value.animationDelay ?? '0';
|
||||||
|
return (
|
||||||
|
<div className="guided-section" data-testid="animation-control">
|
||||||
|
<SectionLabel>Entrance Animation</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={ANIMATIONS} activeValue={animation} onSelect={(v) => onChange({ animation: v, animationDelay })} />
|
||||||
|
{animation !== 'none' && (
|
||||||
|
<div style={{ marginTop: 6 }}>
|
||||||
|
<label style={labelStyle}>Delay (seconds)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
data-testid="animation-delay-input"
|
||||||
|
min={0}
|
||||||
|
step={0.1}
|
||||||
|
value={animationDelay}
|
||||||
|
onChange={(e) => onChange({ animation, animationDelay: e.target.value })}
|
||||||
|
style={inputStyle}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ---------- VisibilityControl ----------
|
||||||
|
Hide on Desktop / Tablet / Mobile toggles. Emits the EXACT prop names
|
||||||
|
the export machinery already consumes (verified against buildDataAttrs()
|
||||||
|
in src/utils/html-export.ts): `hideOnDesktop`, `hideOnTablet`,
|
||||||
|
`hideOnMobile` (each rendered as data-hide-desktop/tablet/mobile when
|
||||||
|
truthy). Single onChange receives the merged object. */
|
||||||
|
export interface VisibilityValue { hideOnDesktop?: boolean; hideOnTablet?: boolean; hideOnMobile?: boolean; }
|
||||||
|
export interface VisibilityControlProps {
|
||||||
|
value: VisibilityValue;
|
||||||
|
onChange: (value: VisibilityValue) => void;
|
||||||
|
}
|
||||||
|
const VISIBILITY_KEYS: (keyof VisibilityValue)[] = ['hideOnDesktop', 'hideOnTablet', 'hideOnMobile'];
|
||||||
|
export const VisibilityControl: React.FC<VisibilityControlProps> = ({ value, onChange }) => (
|
||||||
|
<div className="guided-section" data-testid="visibility-control">
|
||||||
|
<SectionLabel>Visibility</SectionLabel>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||||
|
{VISIBILITY_KEYS.map((key) => (
|
||||||
|
<label key={key} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: '#e4e4e7', cursor: 'pointer' }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid={`visibility-${key}`}
|
||||||
|
checked={!!value[key]}
|
||||||
|
onChange={() => onChange({ ...value, [key]: !value[key] })}
|
||||||
|
/>
|
||||||
|
Hide on {key.replace('hideOn', '')}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export const ChatInput: React.FC<Props> = ({ disabled, placeholder, onSend }) =>
|
|||||||
<div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
|
<div style={{ display: 'flex', gap: 8, padding: '8px 0' }}>
|
||||||
<textarea value={v} onChange={(e) => setV(e.target.value)} onKeyDown={onKey} rows={2} disabled={disabled}
|
<textarea value={v} onChange={(e) => setV(e.target.value)} onKeyDown={onKey} rows={2} disabled={disabled}
|
||||||
placeholder={placeholder || 'Describe what you want...'}
|
placeholder={placeholder || 'Describe what you want...'}
|
||||||
|
className="sitesmith-textarea"
|
||||||
style={{
|
style={{
|
||||||
flex: 1, background: disabled ? '#1f1f24' : '#0f0f17', color: '#e5e7eb',
|
flex: 1, background: disabled ? '#1f1f24' : '#0f0f17', color: '#e5e7eb',
|
||||||
border: '1px solid #3f3f46', borderRadius: 6, padding: 10, fontSize: 14, resize: 'none',
|
border: '1px solid #3f3f46', borderRadius: 6, padding: 10, fontSize: 14, resize: 'none',
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ export const SitesmithButton: React.FC<Props> = ({ onClick }) => {
|
|||||||
color: '#fff', border: 'none', padding: '6px 12px', borderRadius: 6, cursor: 'pointer', fontWeight: 500,
|
color: '#fff', border: 'none', padding: '6px 12px', borderRadius: 6, cursor: 'pointer', fontWeight: 500,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
✨ Sitesmith
|
<i className="fa fa-magic" aria-hidden style={{ marginRight: 6 }} /> Sitesmith
|
||||||
{locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 12 }}>🔒</span>}
|
{locked && <i className="fa fa-lock" aria-hidden style={{ marginLeft: 6, fontSize: 12 }} />}
|
||||||
{capped && !locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 11, opacity: 0.85 }}>(cap)</span>}
|
{capped && !locked && <span aria-hidden style={{ marginLeft: 6, fontSize: 11, opacity: 0.85 }}>(cap)</span>}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -98,12 +98,15 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
|||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
closeOnEscape={false}
|
closeOnEscape={false}
|
||||||
closeOnBackdropClick={false}
|
closeOnBackdropClick={false}
|
||||||
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)', zIndex: 9000 }}
|
backdropStyle={{ backgroundColor: 'rgba(0,0,0,0.8)' }}
|
||||||
backdropProps={{ role: 'dialog', 'aria-modal': true }}
|
backdropProps={{ role: 'dialog', 'aria-modal': true }}
|
||||||
>
|
>
|
||||||
<div style={panel}>
|
<div style={panel}>
|
||||||
<div style={header}>
|
<div style={header}>
|
||||||
<div style={{ fontWeight: 600, color: '#fff' }}>✨ Sitesmith</div>
|
<div style={{ fontWeight: 600, color: '#fff' }}>
|
||||||
|
<i className="fa fa-magic" aria-hidden style={{ marginRight: 6 }} />
|
||||||
|
Sitesmith
|
||||||
|
</div>
|
||||||
{summary && summary.enabled && (
|
{summary && summary.enabled && (
|
||||||
<div style={{ fontSize: 12, color: '#a1a1aa', marginLeft: 16 }}>
|
<div style={{ fontSize: 12, color: '#a1a1aa', marginLeft: 16 }}>
|
||||||
{summary.monthly_used} / {summary.monthly_cap} this month
|
{summary.monthly_used} / {summary.monthly_cap} this month
|
||||||
@@ -136,7 +139,7 @@ export const SitesmithModal: React.FC<Props> = ({ onClose, target }) => {
|
|||||||
</button>
|
</button>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
<button onClick={onClose} aria-label="Close" style={closeBtn}>✕</button>
|
<button onClick={onClose} aria-label="Close" style={closeBtn}><i className="fa fa-times" aria-hidden /></button>
|
||||||
</div>
|
</div>
|
||||||
<div style={body}>
|
<div style={body}>
|
||||||
<UpgradeBanner summary={summary} />
|
<UpgradeBanner summary={summary} />
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { describe, test, expect, vi, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { HeadCodeModal } from './HeadCodeModal';
|
||||||
|
import { SiteDesignProvider, useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
|
|
||||||
|
/* ---------- DOM test harness -- same react-dom/client + `act` pattern used
|
||||||
|
throughout src/ui/*.test.tsx (no @testing-library/react in this repo). ---------- */
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (container) {
|
||||||
|
act(() => { root.unmount(); });
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
document.body.style.overflow = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
// Exposes the current headCode so assertions can read it back after a
|
||||||
|
// simulated edit -- CodeEditor writes through `updateDesign`, this just
|
||||||
|
// surfaces the result.
|
||||||
|
function Harness({ onReady }: { onReady: (headCode: string) => void }) {
|
||||||
|
const { design } = useSiteDesign();
|
||||||
|
onReady(design.headCode);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('HeadCodeModal', () => {
|
||||||
|
// HeadCodeModal portals its content to document.body (see the comment in
|
||||||
|
// HeadCodeModal.tsx), so the rendered DOM lives outside `container` --
|
||||||
|
// query document.body instead.
|
||||||
|
|
||||||
|
test('renders the CodeEditor (fallback textarea path) seeded with the current headCode', () => {
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open onClose={vi.fn()} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
// CodeMirror loads via async dynamic import (see CodeEditor.test.tsx);
|
||||||
|
// synchronously after mount the fallback textarea is what's live.
|
||||||
|
const textarea = document.body.querySelector<HTMLTextAreaElement>('[data-testid="code-editor-fallback"]');
|
||||||
|
expect(textarea).not.toBeNull();
|
||||||
|
expect(textarea!.value).toBe('');
|
||||||
|
expect(textarea!.dataset.language).toBe('html');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('typing in the editor writes through to SiteDesignContext.headCode', () => {
|
||||||
|
let latestHeadCode = '';
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open onClose={vi.fn()} />
|
||||||
|
<Harness onReady={(v) => { latestHeadCode = v; }} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const textarea = document.body.querySelector<HTMLTextAreaElement>('[data-testid="code-editor-fallback"]')!;
|
||||||
|
act(() => {
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')!.set!;
|
||||||
|
setter.call(textarea, '<meta name="x" content="y">');
|
||||||
|
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(latestHeadCode).toBe('<meta name="x" content="y">');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not render when closed', () => {
|
||||||
|
render(
|
||||||
|
<SiteDesignProvider>
|
||||||
|
<HeadCodeModal open={false} onClose={vi.fn()} />
|
||||||
|
</SiteDesignProvider>,
|
||||||
|
);
|
||||||
|
expect(document.body.querySelector('[data-testid="code-editor-fallback"]')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
import { CodeEditor } from '../../ui/CodeEditor';
|
||||||
|
|
||||||
interface HeadCodeModalProps {
|
interface HeadCodeModalProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -10,7 +12,15 @@ interface HeadCodeModalProps {
|
|||||||
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
|
export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) => {
|
||||||
const { design, updateDesign } = useSiteDesign();
|
const { design, updateDesign } = useSiteDesign();
|
||||||
|
|
||||||
return (
|
// Mobile-A2/Phase B: portaled to `document.body` -- same fix TemplateModal
|
||||||
|
// already got (see its comment). TopBar.tsx mounts this modal as a child
|
||||||
|
// of `.topbar`, which (as a flex item with its own z-index) forms its own
|
||||||
|
// stacking context; that trapped the modal's fixed-position backdrop
|
||||||
|
// underneath the mobile tab bar (z-index: var(--z-tabbar)) no matter how
|
||||||
|
// high the modal's own z-index was set. Portaling escapes that stacking
|
||||||
|
// context entirely so `--z-modal` (editor.css) is evaluated at the
|
||||||
|
// document root, same as TemplateModal/SitesmithModal.
|
||||||
|
return createPortal(
|
||||||
<Modal open={open} onClose={onClose}>
|
<Modal open={open} onClose={onClose}>
|
||||||
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
<div style={modalStyle} onClick={(e) => e.stopPropagation()}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -46,28 +56,16 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
|
|||||||
Code added here will be injected into the <code style={{ background: 'rgba(255,255,255,0.08)', padding: '1px 4px', borderRadius: 3, fontSize: 11 }}><head></code> of every page on your site. Use it for analytics, custom fonts, or global CSS.
|
Code added here will be injected into the <code style={{ background: 'rgba(255,255,255,0.08)', padding: '1px 4px', borderRadius: 3, fontSize: 11 }}><head></code> of every page on your site. Use it for analytics, custom fonts, or global CSS.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<textarea
|
<div style={{ flex: 1, minHeight: 300 }}>
|
||||||
|
<CodeEditor
|
||||||
value={design.headCode || ''}
|
value={design.headCode || ''}
|
||||||
onChange={(e) => updateDesign({ headCode: e.target.value })}
|
onChange={(code) => updateDesign({ headCode: code })}
|
||||||
|
language="html"
|
||||||
|
height="100%"
|
||||||
placeholder={"<!-- Google Analytics -->\n<script async src=\"https://...\"></script>\n\n<!-- Custom Fonts -->\n<link href=\"https://fonts.googleapis.com/...\" rel=\"stylesheet\">\n\n<style>\n /* Global CSS overrides */\n body { }\n</style>"}
|
placeholder={"<!-- Google Analytics -->\n<script async src=\"https://...\"></script>\n\n<!-- Custom Fonts -->\n<link href=\"https://fonts.googleapis.com/...\" rel=\"stylesheet\">\n\n<style>\n /* Global CSS overrides */\n body { }\n</style>"}
|
||||||
style={{
|
|
||||||
flex: 1,
|
|
||||||
minHeight: 300,
|
|
||||||
padding: 14,
|
|
||||||
background: '#0d0d0f',
|
|
||||||
color: '#e4e4e7',
|
|
||||||
border: '1px solid #3f3f46',
|
|
||||||
borderRadius: 8,
|
|
||||||
fontFamily: 'Source Code Pro, Consolas, monospace',
|
|
||||||
fontSize: 13,
|
|
||||||
lineHeight: 1.6,
|
|
||||||
resize: 'vertical',
|
|
||||||
outline: 'none',
|
|
||||||
tabSize: 2,
|
|
||||||
}}
|
|
||||||
spellCheck={false}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* Footer */}
|
||||||
<div style={{
|
<div style={{
|
||||||
@@ -82,7 +80,8 @@ export const HeadCodeModal: React.FC<HeadCodeModalProps> = ({ open, onClose }) =
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>,
|
||||||
|
document.body,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import { usePages } from '../../state/PageContext';
|
import { usePages } from '../../state/PageContext';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
@@ -8,9 +9,10 @@ import {
|
|||||||
TemplateComponent,
|
TemplateComponent,
|
||||||
TemplateCategory,
|
TemplateCategory,
|
||||||
} from '../../templates';
|
} from '../../templates';
|
||||||
import { componentResolver } from '../../components/resolver';
|
|
||||||
import { clickableProps } from '../../utils/a11y';
|
import { clickableProps } from '../../utils/a11y';
|
||||||
import { Modal } from '../../ui/Modal';
|
import { Modal } from '../../ui/Modal';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Types
|
// Types
|
||||||
@@ -77,28 +79,31 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
return allTemplates.filter((t) => t.category === activeTab);
|
return allTemplates.filter((t) => t.category === activeTab);
|
||||||
}, [activeTab]);
|
}, [activeTab]);
|
||||||
|
|
||||||
// Resolve a TemplateComponent type name to its React component
|
|
||||||
const resolverMap = componentResolver as Record<string, React.ComponentType<any>>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
* Add all components from a template definition onto the current (empty) canvas ROOT.
|
||||||
* Uses Craft.js parseReactElement + addNodeTree which correctly builds valid node structures.
|
* Converts each `TemplateComponent` (the plain `{type, props, children?}`
|
||||||
|
* shape templates author) to a `SerializedTreeNode` and runs it through
|
||||||
|
* `buildNodeTree` (sanitize -> flatten -> materialize), the same tree pipeline
|
||||||
|
* already used for AI-generated content. This recurses into nested
|
||||||
|
* `children` (e.g. a header/footer `Container` wrapping `Logo`/`Menu`, or a
|
||||||
|
* page `Section` wrapping a `Heading`) AND correctly routes them through a
|
||||||
|
* component's SHELL_INNER linked canvas / linked columns where needed --
|
||||||
|
* see `templates/apply-template.ts` for the two bugs this fixes (dropped
|
||||||
|
* children, and a naive `parseReactElement` tree crashing `Section`/
|
||||||
|
* `BackgroundSection`/`FormContainer`/`ColumnLayout`).
|
||||||
*/
|
*/
|
||||||
const addTemplateComponents = useCallback(
|
const addTemplateComponents = useCallback(
|
||||||
(components: TemplateComponent[]) => {
|
(components: TemplateComponent[]) => {
|
||||||
for (const comp of components) {
|
for (const comp of components) {
|
||||||
const Component = resolverMap[comp.type];
|
try {
|
||||||
if (!Component) {
|
const tree = buildNodeTree(query, templateComponentToTreeNode(comp));
|
||||||
console.warn(`Template references unknown component type: ${comp.type}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const element = React.createElement(Component, comp.props);
|
|
||||||
const tree = query.parseReactElement(element).toNodeTree();
|
|
||||||
actions.addNodeTree(tree, 'ROOT');
|
actions.addNodeTree(tree, 'ROOT');
|
||||||
|
} catch (e) {
|
||||||
|
console.warn(`Failed to build template component tree for type "${comp.type}":`, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[query, actions, resolverMap],
|
[query, actions],
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -234,7 +239,14 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
}
|
}
|
||||||
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
||||||
|
|
||||||
return (
|
// Mobile-A2: portaled to `document.body` -- TopBar.tsx mounts this modal
|
||||||
|
// as a child of `.topbar`, which (as a flex item with its own z-index)
|
||||||
|
// forms its own stacking context. That trapped the modal's fixed-position
|
||||||
|
// backdrop underneath the mobile tab bar (z-index: var(--z-tabbar)) no
|
||||||
|
// matter how high the modal's own z-index was set. Portaling escapes that
|
||||||
|
// stacking context entirely so `--z-modal` (see editor.css) is evaluated
|
||||||
|
// at the document root, same as SitesmithModal.
|
||||||
|
return createPortal(
|
||||||
<Modal open={open} onClose={handleModalClose}>
|
<Modal open={open} onClose={handleModalClose}>
|
||||||
<div style={modalStyle}>
|
<div style={modalStyle}>
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
@@ -247,21 +259,39 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
Choose a template to get started quickly
|
Choose a template to get started quickly
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button onClick={onClose} style={closeButtonStyle} title="Close">
|
<button
|
||||||
✕
|
onClick={onClose}
|
||||||
|
className="template-modal-close-btn"
|
||||||
|
style={closeButtonStyle}
|
||||||
|
title="Close"
|
||||||
|
aria-label="Close"
|
||||||
|
onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text)'; }}
|
||||||
|
onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'transparent'; (e.currentTarget as HTMLElement).style.color = '#71717a'; }}
|
||||||
|
>
|
||||||
|
<i className="fa fa-times" aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filter Tabs */}
|
{/* Filter Tabs -- horizontally scrollable (tabBarStyle sets
|
||||||
<div style={tabBarStyle}>
|
overflowX: 'auto') so the row never wraps/overflows the modal at
|
||||||
|
narrow widths; template-modal-tab-btn below keeps each tab from
|
||||||
|
shrinking below a comfortable touch target on mobile. */}
|
||||||
|
<div className="template-modal-tabbar" style={tabBarStyle}>
|
||||||
{TABS.map((tab) => (
|
{TABS.map((tab) => (
|
||||||
<button
|
<button
|
||||||
key={tab.value}
|
key={tab.value}
|
||||||
|
className="template-modal-tab-btn"
|
||||||
onClick={() => setActiveTab(tab.value)}
|
onClick={() => setActiveTab(tab.value)}
|
||||||
style={{
|
style={{
|
||||||
...tabStyle,
|
...tabStyle,
|
||||||
...(activeTab === tab.value ? tabActiveStyle : {}),
|
...(activeTab === tab.value ? tabActiveStyle : {}),
|
||||||
}}
|
}}
|
||||||
|
onMouseEnter={(e) => {
|
||||||
|
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)';
|
||||||
|
}}
|
||||||
|
onMouseLeave={(e) => {
|
||||||
|
if (activeTab !== tab.value) (e.currentTarget as HTMLElement).style.background = 'transparent';
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{tab.label}
|
{tab.label}
|
||||||
</button>
|
</button>
|
||||||
@@ -359,7 +389,8 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>,
|
||||||
|
document.body,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,18 +4,24 @@ import { useEditorConfig } from '../../state/EditorConfigContext';
|
|||||||
import { useWhpApi } from '../../hooks/useWhpApi';
|
import { useWhpApi } from '../../hooks/useWhpApi';
|
||||||
import { usePages } from '../../state/PageContext';
|
import { usePages } from '../../state/PageContext';
|
||||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||||
|
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||||
|
import { useMobileChrome } from '../../state/MobileChromeContext';
|
||||||
import { DeviceMode } from '../../types';
|
import { DeviceMode } from '../../types';
|
||||||
import { TemplateModal } from './TemplateModal';
|
import { TemplateModal } from './TemplateModal';
|
||||||
import { HeadCodeModal } from './HeadCodeModal';
|
import { HeadCodeModal } from './HeadCodeModal';
|
||||||
|
import { TopBarOverflowMenu } from './TopBarOverflowMenu';
|
||||||
import { SitesmithButton } from '../sitesmith/SitesmithButton';
|
import { SitesmithButton } from '../sitesmith/SitesmithButton';
|
||||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||||
|
|
||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
device: DeviceMode;
|
device: DeviceMode;
|
||||||
onDeviceChange: (device: DeviceMode) => void;
|
onDeviceChange: (device: DeviceMode) => void;
|
||||||
|
/** Item 10: canvas dashed guide outlines, default ON. */
|
||||||
|
showGuides: boolean;
|
||||||
|
onToggleGuides: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuides, onToggleGuides }) => {
|
||||||
const { whpConfig, isWHP } = useEditorConfig();
|
const { whpConfig, isWHP } = useEditorConfig();
|
||||||
const { actions, query, canUndo, canRedo } = useEditor((_state, query) => ({
|
const { actions, query, canUndo, canRedo } = useEditor((_state, query) => ({
|
||||||
canUndo: query.history.canUndo(),
|
canUndo: query.history.canUndo(),
|
||||||
@@ -28,8 +34,11 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
||||||
const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle');
|
const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle');
|
||||||
const [isDraft, setIsDraft] = useState(false);
|
const [isDraft, setIsDraft] = useState(false);
|
||||||
const [templateModalOpen, setTemplateModalOpen] = useState(false);
|
// Mobile-A2: lifted from private useState into MobileChromeContext so
|
||||||
const [headCodeModalOpen, setHeadCodeModalOpen] = useState(false);
|
// opening a mobile sheet can close these modals (item 3) -- behavior is
|
||||||
|
// otherwise identical for both the desktop and mobile branches below.
|
||||||
|
const { templateModalOpen, setTemplateModalOpen, headCodeModalOpen, setHeadCodeModalOpen, overflowOpen, setOverflowOpen } = useMobileChrome();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
const { open: openSitesmith } = useSitesmithModal();
|
const { open: openSitesmith } = useSitesmithModal();
|
||||||
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
@@ -119,52 +128,9 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
// Extracted so both the desktop inline Preview button and the mobile
|
||||||
<nav className="topbar">
|
// overflow-menu "Preview" item can trigger the exact same flow.
|
||||||
<div className="topbar-left">
|
const handlePreview = useCallback(() => {
|
||||||
{isWHP && (
|
|
||||||
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
|
|
||||||
<i className="fa fa-arrow-left" /> Back to Panel
|
|
||||||
</a>
|
|
||||||
)}
|
|
||||||
<span className="topbar-title">Site Builder</span>
|
|
||||||
{isWHP && (
|
|
||||||
<span className="topbar-domain">{whpConfig!.siteDomain}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="topbar-center">
|
|
||||||
<div className="device-switcher">
|
|
||||||
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
|
||||||
<button
|
|
||||||
key={d}
|
|
||||||
className={`device-btn ${device === d ? 'active' : ''}`}
|
|
||||||
onClick={() => onDeviceChange(d)}
|
|
||||||
title={d.charAt(0).toUpperCase() + d.slice(1)}
|
|
||||||
aria-label={d.charAt(0).toUpperCase() + d.slice(1)}
|
|
||||||
aria-pressed={device === d}
|
|
||||||
>
|
|
||||||
<i className={`fa ${d === 'desktop' ? 'fa-desktop' : d === 'tablet' ? 'fa-tablet' : 'fa-mobile'}`} />
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="topbar-right">
|
|
||||||
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo} title="Undo" aria-label="Undo">
|
|
||||||
<i className="fa fa-undo" />
|
|
||||||
</button>
|
|
||||||
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo} title="Redo" aria-label="Redo">
|
|
||||||
<i className="fa fa-repeat" />
|
|
||||||
</button>
|
|
||||||
<span className="topbar-divider" />
|
|
||||||
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
|
||||||
<i className="fa fa-th-large" /> Templates
|
|
||||||
</button>
|
|
||||||
<button className="topbar-btn" title="Custom Head Code" aria-label="Custom Head Code" onClick={() => setHeadCodeModalOpen(true)}>
|
|
||||||
<i className="fa fa-code" /> Code
|
|
||||||
</button>
|
|
||||||
<button className="topbar-btn" title="Preview" aria-label="Preview" onClick={() => {
|
|
||||||
try {
|
try {
|
||||||
const serialized = query.serialize();
|
const serialized = query.serialize();
|
||||||
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
import('../../utils/html-export').then(({ exportToHtml, exportBodyHtml }) => {
|
||||||
@@ -217,8 +183,163 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange }) => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Preview failed:', e);
|
console.error('Preview failed:', e);
|
||||||
}
|
}
|
||||||
}}>
|
}, [query, headerPage, footerPage, whpConfig, design]);
|
||||||
<i className="fa fa-eye" /> Preview
|
|
||||||
|
// Phase A: at ≤768px the topbar collapses to only the essentials --
|
||||||
|
// back arrow, Undo/Redo, Save (+Publish) -- with Templates, Sitesmith,
|
||||||
|
// Preview, Head Code, the guides toggle, and the device switcher moved
|
||||||
|
// into the "⋯" overflow menu. This keeps desktop's JSX/behavior below
|
||||||
|
// completely untouched.
|
||||||
|
if (isMobile) {
|
||||||
|
return (
|
||||||
|
<nav className="topbar topbar-mobile">
|
||||||
|
<div className="topbar-left">
|
||||||
|
{isWHP && (
|
||||||
|
<a
|
||||||
|
href={whpConfig!.backUrl}
|
||||||
|
className="topbar-btn icon-only back-btn"
|
||||||
|
aria-label="Back to Panel"
|
||||||
|
data-tooltip="Back"
|
||||||
|
>
|
||||||
|
<i className="fa fa-arrow-left" />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="topbar-right">
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only"
|
||||||
|
onClick={() => actions.history.undo()}
|
||||||
|
disabled={!canUndo}
|
||||||
|
aria-label="Undo"
|
||||||
|
data-tooltip="Undo"
|
||||||
|
>
|
||||||
|
<i className="fa fa-undo" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only"
|
||||||
|
onClick={() => actions.history.redo()}
|
||||||
|
disabled={!canRedo}
|
||||||
|
aria-label="Redo"
|
||||||
|
data-tooltip="Redo"
|
||||||
|
>
|
||||||
|
<i className="fa fa-repeat" />
|
||||||
|
</button>
|
||||||
|
<span className="topbar-divider" />
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only primary"
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saveStatus === 'saving'}
|
||||||
|
aria-label="Save Draft"
|
||||||
|
data-tooltip="Save"
|
||||||
|
>
|
||||||
|
<i className={`fa ${saveStatus === 'saving' ? 'fa-spinner fa-spin' : 'fa-save'}`} />
|
||||||
|
</button>
|
||||||
|
{isWHP && (
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only publish"
|
||||||
|
onClick={handlePublish}
|
||||||
|
disabled={publishStatus === 'publishing' || saveStatus === 'saving'}
|
||||||
|
aria-label="Publish to live site"
|
||||||
|
data-tooltip="Publish"
|
||||||
|
>
|
||||||
|
<i className={`fa ${publishStatus === 'publishing' ? 'fa-spinner fa-spin' : 'fa-globe'}`} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-btn icon-only overflow-toggle${overflowOpen ? ' active' : ''}`}
|
||||||
|
onClick={() => setOverflowOpen(!overflowOpen)}
|
||||||
|
aria-label="More options"
|
||||||
|
aria-expanded={overflowOpen}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
data-tooltip="More"
|
||||||
|
>
|
||||||
|
<i className="fa fa-ellipsis-h" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TopBarOverflowMenu
|
||||||
|
open={overflowOpen}
|
||||||
|
onClose={() => setOverflowOpen(false)}
|
||||||
|
device={device}
|
||||||
|
onDeviceChange={onDeviceChange}
|
||||||
|
showGuides={showGuides}
|
||||||
|
onToggleGuides={onToggleGuides}
|
||||||
|
onOpenTemplates={() => setTemplateModalOpen(true)}
|
||||||
|
onOpenHeadCode={() => setHeadCodeModalOpen(true)}
|
||||||
|
onPreview={handlePreview}
|
||||||
|
sitesmithNode={<SitesmithButton onClick={() => openSitesmith()} />}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TemplateModal open={templateModalOpen} onClose={() => setTemplateModalOpen(false)} />
|
||||||
|
<HeadCodeModal open={headCodeModalOpen} onClose={() => setHeadCodeModalOpen(false)} />
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav className="topbar">
|
||||||
|
<div className="topbar-left">
|
||||||
|
{isWHP && (
|
||||||
|
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
|
||||||
|
<i className="fa fa-arrow-left" /> Back to Panel
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<span className="topbar-title">Site Builder</span>
|
||||||
|
{isWHP && (
|
||||||
|
<span className="topbar-domain">{whpConfig!.siteDomain}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="topbar-center">
|
||||||
|
<div className="device-switcher">
|
||||||
|
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
||||||
|
<button
|
||||||
|
key={d}
|
||||||
|
className={`device-btn ${device === d ? 'active' : ''}`}
|
||||||
|
onClick={() => onDeviceChange(d)}
|
||||||
|
title={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-label={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-pressed={device === d}
|
||||||
|
>
|
||||||
|
<i className={`fa ${d === 'desktop' ? 'fa-desktop' : d === 'tablet' ? 'fa-tablet' : 'fa-mobile'}`} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-btn guides-toggle icon-only${showGuides ? ' active' : ''}`}
|
||||||
|
onClick={onToggleGuides}
|
||||||
|
aria-pressed={showGuides}
|
||||||
|
aria-label={showGuides ? 'Hide canvas guides' : 'Show canvas guides'}
|
||||||
|
data-tooltip={showGuides ? 'Hide guides' : 'Show guides'}
|
||||||
|
>
|
||||||
|
<i className={`fa ${showGuides ? 'fa-th' : 'fa-th-large'}`} aria-hidden />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="topbar-right">
|
||||||
|
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo} title="Undo" aria-label="Undo">
|
||||||
|
<i className="fa fa-undo" />
|
||||||
|
</button>
|
||||||
|
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo} title="Redo" aria-label="Redo">
|
||||||
|
<i className="fa fa-repeat" />
|
||||||
|
</button>
|
||||||
|
<span className="topbar-divider" />
|
||||||
|
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||||
|
<i className="fa fa-th-large" /> Templates
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="topbar-btn icon-only"
|
||||||
|
aria-label="Custom Head Code"
|
||||||
|
data-tooltip="Code"
|
||||||
|
onClick={() => setHeadCodeModalOpen(true)}
|
||||||
|
>
|
||||||
|
<i className="fa fa-code" />
|
||||||
|
</button>
|
||||||
|
<button className="topbar-btn icon-only" aria-label="Preview" data-tooltip="Preview" onClick={handlePreview}>
|
||||||
|
<i className="fa fa-eye" />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Draft/Published status badge */}
|
{/* Draft/Published status badge */}
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import React, { useEffect, useRef } from 'react';
|
||||||
|
import { DeviceMode } from '../../types';
|
||||||
|
|
||||||
|
export interface TopBarOverflowMenuProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
device: DeviceMode;
|
||||||
|
onDeviceChange: (device: DeviceMode) => void;
|
||||||
|
showGuides: boolean;
|
||||||
|
onToggleGuides: () => void;
|
||||||
|
onOpenTemplates: () => void;
|
||||||
|
onOpenHeadCode: () => void;
|
||||||
|
onPreview: () => void;
|
||||||
|
/** Rendered `<SitesmithButton onClick={...} />` -- passed in rather than
|
||||||
|
* re-implemented here so the mobile menu reuses the exact same
|
||||||
|
* lock/cap-aware button the desktop topbar shows. */
|
||||||
|
sitesmithNode: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile topbar "⋯" overflow menu (Phase A). At ≤768px, TopBar collapses to
|
||||||
|
* just the back arrow, Undo/Redo, Save/Publish, and this menu -- everything
|
||||||
|
* else that's inline on desktop (Templates, Sitesmith, Preview, Head Code,
|
||||||
|
* the guides toggle, and the device-width switcher) moves in here so the
|
||||||
|
* collapsed bar never overlaps or pushes controls off-screen.
|
||||||
|
*/
|
||||||
|
export const TopBarOverflowMenu: React.FC<TopBarOverflowMenuProps> = ({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
device,
|
||||||
|
onDeviceChange,
|
||||||
|
showGuides,
|
||||||
|
onToggleGuides,
|
||||||
|
onOpenTemplates,
|
||||||
|
onOpenHeadCode,
|
||||||
|
onPreview,
|
||||||
|
sitesmithNode,
|
||||||
|
}) => {
|
||||||
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const handleClick = (e: MouseEvent) => {
|
||||||
|
if (menuRef.current && !menuRef.current.contains(e.target as Node)) onClose();
|
||||||
|
};
|
||||||
|
const handleEsc = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') onClose();
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', handleClick);
|
||||||
|
document.addEventListener('keydown', handleEsc);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', handleClick);
|
||||||
|
document.removeEventListener('keydown', handleEsc);
|
||||||
|
};
|
||||||
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
const runAndClose = (fn: () => void) => () => {
|
||||||
|
fn();
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={menuRef} className="topbar-overflow-menu" role="menu">
|
||||||
|
<div className="topbar-overflow-section">
|
||||||
|
<span className="topbar-overflow-label">Preview width</span>
|
||||||
|
<div className="device-switcher">
|
||||||
|
{(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map((d) => (
|
||||||
|
<button
|
||||||
|
key={d}
|
||||||
|
type="button"
|
||||||
|
className={`device-btn ${device === d ? 'active' : ''}`}
|
||||||
|
onClick={() => onDeviceChange(d)}
|
||||||
|
title={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-label={d.charAt(0).toUpperCase() + d.slice(1)}
|
||||||
|
aria-pressed={device === d}
|
||||||
|
>
|
||||||
|
<i className={`fa ${d === 'desktop' ? 'fa-desktop' : d === 'tablet' ? 'fa-tablet' : 'fa-mobile'}`} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenTemplates)}>
|
||||||
|
<i className="fa fa-th-large" aria-hidden="true" /> Templates
|
||||||
|
</button>
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onPreview)}>
|
||||||
|
<i className="fa fa-eye" aria-hidden="true" /> Preview
|
||||||
|
</button>
|
||||||
|
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenHeadCode)}>
|
||||||
|
<i className="fa fa-code" aria-hidden="true" /> Head Code
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`topbar-overflow-item${showGuides ? ' active' : ''}`}
|
||||||
|
role="menuitem"
|
||||||
|
onClick={runAndClose(onToggleGuides)}
|
||||||
|
aria-pressed={showGuides}
|
||||||
|
>
|
||||||
|
<i className={`fa ${showGuides ? 'fa-th' : 'fa-th-large'}`} aria-hidden="true" />
|
||||||
|
{' '}{showGuides ? 'Hide Guides' : 'Show Guides'}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="topbar-overflow-sitesmith" onClick={onClose}>
|
||||||
|
{sitesmithNode}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { Editor, useEditor } from '@craftjs/core';
|
||||||
|
import { componentResolver } from '../../components/resolver';
|
||||||
|
import { allTemplates } from '../../templates';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
import { DEFAULT_HEADER_STATE } from '../../state/PageContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression test for: loading a template makes the header/footer ZONE
|
||||||
|
* PREVIEW (`ZonePreview` in `editor/Canvas.tsx`, which calls
|
||||||
|
* `exportBodyHtml(craftState)`) render as an empty strip -- no nav links, no
|
||||||
|
* logo, no footer text -- and (a second bug found while fixing the first)
|
||||||
|
* makes a template page's `Section`-wrapped content crash the live editor
|
||||||
|
* entirely.
|
||||||
|
*
|
||||||
|
* This drives the EXACT same path `TemplateModal.tsx`'s `applyZone` /
|
||||||
|
* `addTemplateComponents` uses to load a template's header/footer/page
|
||||||
|
* content onto the live Craft.js canvas (`buildNodeTree` +
|
||||||
|
* `actions.addNodeTree(tree, 'ROOT')`), then serializes it
|
||||||
|
* (`query.serialize()`, exactly what `PageContext`'s `switchPage` /
|
||||||
|
* `saveCurrentState` do right after `TemplateModal` finishes applying a
|
||||||
|
* zone/page) and feeds the result through `exportBodyHtml` -- the same
|
||||||
|
* function `ZonePreview` calls, and the same function `handlePublish` uses
|
||||||
|
* to compose the published header/footer HTML. So this also covers whether
|
||||||
|
* published output is affected (it was).
|
||||||
|
*/
|
||||||
|
let api: any;
|
||||||
|
function Harness() {
|
||||||
|
const { actions, query } = useEditor();
|
||||||
|
api = { actions, query };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount() {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
let root!: Root;
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(
|
||||||
|
<Editor resolver={componentResolver}>
|
||||||
|
<Harness />
|
||||||
|
</Editor>,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
container,
|
||||||
|
unmount: () => {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
|
||||||
|
function addTemplateComponents(components: any[]) {
|
||||||
|
for (const comp of components) {
|
||||||
|
const tree = buildNodeTree(api.query, templateComponentToTreeNode(comp));
|
||||||
|
api.actions.addNodeTree(tree, 'ROOT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_HEADER_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"header"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
const EMPTY_CANVAS_ROOT =
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"div"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}';
|
||||||
|
|
||||||
|
describe('template header/footer zone export (loading a template)', () => {
|
||||||
|
test('sanity check: the DEFAULT header (fresh project, no template) exports its content', () => {
|
||||||
|
const { html } = exportBodyHtml(DEFAULT_HEADER_STATE);
|
||||||
|
expect(html).toContain('MySite');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template header (SaaS Landing) exports its real nav/logo content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.header.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_HEADER_ROOT);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.header.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
// The template's logo text and a real nav link -- if these are missing,
|
||||||
|
// the header rendered as an empty strip (the reported bug).
|
||||||
|
expect(html).toContain('FlowStack');
|
||||||
|
expect(html).toContain('Features');
|
||||||
|
expect(html).toContain('Start Free');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template footer (SaaS Landing) exports its real copyright/tagline content -- not an empty strip', () => {
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl!.footer.components.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(
|
||||||
|
'{"ROOT":{"type":{"resolvedName":"Container"},"isCanvas":true,"props":{"style":{},"tag":"footer"},"displayName":"Container","custom":{},"hidden":false,"nodes":[],"linkedNodes":{}}}',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents(tpl!.footer.components);
|
||||||
|
});
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
|
||||||
|
expect(html).toContain('FlowStack, Inc.');
|
||||||
|
expect(html).toContain('Ship products faster');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a template page Section with nested children (SaaS Landing Home) builds + exports without crashing', () => {
|
||||||
|
// Regression for the SECOND bug surfaced while fixing the first: naively
|
||||||
|
// rebuilding nested children via React.createElement + parseReactElement
|
||||||
|
// crashes any component with an internal SHELL_INNER linked canvas
|
||||||
|
// (Section/BackgroundSection/FormContainer) or linked columns
|
||||||
|
// (ColumnLayout). The SaaS Landing home page's second component is a
|
||||||
|
// `Section` wrapping a `Heading` ("Trusted by 10,000+ development
|
||||||
|
// teams...") -- exactly this shape.
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing');
|
||||||
|
const homePage = tpl!.pages[0];
|
||||||
|
const sectionComp = homePage.content.components.find((c) => c.type === 'Section');
|
||||||
|
expect(sectionComp).toBeDefined();
|
||||||
|
expect(sectionComp!.children?.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
const { unmount } = mount();
|
||||||
|
act(() => {
|
||||||
|
api.actions.deserialize(EMPTY_CANVAS_ROOT);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
act(() => {
|
||||||
|
addTemplateComponents([sectionComp!]);
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
const serialized = api.query.serialize();
|
||||||
|
const { html } = exportBodyHtml(serialized);
|
||||||
|
expect(html).toContain('Trusted by 10,000+ development teams');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { describe, test, expect } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { MobileChromeProvider, useMobileChrome, MobileSheetTab } from './MobileChromeContext';
|
||||||
|
import { SitesmithProvider, useSitesmithModal } from './SitesmithContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mobile-A2 (review item 5): covers the two invariants item 3 depends on --
|
||||||
|
* (1) only one sheet is ever open ("tab-bar-always-wins", Phase A's existing
|
||||||
|
* behavior, now backed by the shared context instead of a private
|
||||||
|
* useState), and (2) opening a sheet closes any open full-screen modal
|
||||||
|
* (Templates / Head Code / Sitesmith), so a sheet is never shown stacked
|
||||||
|
* underneath one.
|
||||||
|
*
|
||||||
|
* DOM-harness pattern mirrors PageContext.pure-updaters.test.tsx: bare
|
||||||
|
* createRoot + act, a Consumer component that stashes the hook result on an
|
||||||
|
* outer variable so assertions can run outside of render.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let container: HTMLDivElement;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
function render(ui: React.ReactElement) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
root.render(ui);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function unmount() {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
|
||||||
|
let chrome: ReturnType<typeof useMobileChrome> | null = null;
|
||||||
|
let sitesmith: ReturnType<typeof useSitesmithModal> | null = null;
|
||||||
|
|
||||||
|
const Consumer: React.FC = () => {
|
||||||
|
chrome = useMobileChrome();
|
||||||
|
sitesmith = useSitesmithModal();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderProviders() {
|
||||||
|
render(
|
||||||
|
<SitesmithProvider>
|
||||||
|
<MobileChromeProvider>
|
||||||
|
<Consumer />
|
||||||
|
</MobileChromeProvider>
|
||||||
|
</SitesmithProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MobileChromeContext', () => {
|
||||||
|
test('only one sheet is ever open at a time', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('blocks'));
|
||||||
|
expect(chrome!.activeSheet).toBe('blocks');
|
||||||
|
|
||||||
|
// Opening a different sheet replaces the previous one -- never both.
|
||||||
|
act(() => chrome!.openSheet('styles'));
|
||||||
|
expect(chrome!.activeSheet).toBe('styles');
|
||||||
|
|
||||||
|
act(() => chrome!.closeSheet());
|
||||||
|
expect(chrome!.activeSheet).toBeNull();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet is idempotent-safe: opening the same tab twice stays open (caller owns toggle-to-close)', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('pages'));
|
||||||
|
expect(chrome!.activeSheet).toBe('pages');
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('pages'));
|
||||||
|
expect(chrome!.activeSheet).toBe('pages');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Templates modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.setTemplateModalOpen(true));
|
||||||
|
expect(chrome!.templateModalOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('blocks'));
|
||||||
|
expect(chrome!.templateModalOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('blocks');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Head Code modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.setHeadCodeModalOpen(true));
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('assets'));
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('assets');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('openSheet closes an open Sitesmith modal', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => sitesmith!.open());
|
||||||
|
expect(sitesmith!.isOpen).toBe(true);
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('layers'));
|
||||||
|
|
||||||
|
// sitesmith is a stale snapshot from before the re-render the `act`
|
||||||
|
// above triggered; re-read via the live ref after settling.
|
||||||
|
expect(sitesmith!.isOpen).toBe(false);
|
||||||
|
expect(chrome!.activeSheet).toBe('layers');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('closeSheet does not disturb modal state', () => {
|
||||||
|
renderProviders();
|
||||||
|
|
||||||
|
act(() => chrome!.openSheet('styles'));
|
||||||
|
act(() => chrome!.closeSheet());
|
||||||
|
|
||||||
|
expect(chrome!.activeSheet).toBeNull();
|
||||||
|
expect(chrome!.templateModalOpen).toBe(false);
|
||||||
|
expect(chrome!.headCodeModalOpen).toBe(false);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sheet tabs are exactly the five mobile panels', () => {
|
||||||
|
const tabs: MobileSheetTab[] = ['blocks', 'pages', 'layers', 'assets', 'styles'];
|
||||||
|
renderProviders();
|
||||||
|
tabs.forEach((tab) => {
|
||||||
|
act(() => chrome!.openSheet(tab));
|
||||||
|
expect(chrome!.activeSheet).toBe(tab);
|
||||||
|
});
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user