Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0419291259 | ||
|
|
1d9460c173 | ||
|
|
8d69982a0b | ||
|
|
fb40e3ece4 | ||
|
|
9591fcb8a7 | ||
|
|
f80811318b | ||
|
|
cb9fea6656 | ||
|
|
b1afdcb585 |
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",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, test, expect } from 'vitest';
|
import { describe, test, expect } from 'vitest';
|
||||||
import { ImageBlock } from './ImageBlock';
|
import { ImageBlock, pxAttr } from './ImageBlock';
|
||||||
|
|
||||||
const toHtml = (ImageBlock as any).toHtml;
|
const toHtml = (ImageBlock as any).toHtml;
|
||||||
|
|
||||||
@@ -32,3 +32,95 @@ describe('ImageBlock.toHtml src/alt XSS hardening', () => {
|
|||||||
expect(html).toContain('alt="A photo"');
|
expect(html).toContain('alt="A photo"');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml perf attributes (always emitted)', () => {
|
||||||
|
test('loading="lazy" and decoding="async" are always present', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg' }, '');
|
||||||
|
expect(html).toContain('loading="lazy"');
|
||||||
|
expect(html).toContain('decoding="async"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('width/height attributes are emitted when the style has plain px values', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg', style: { width: '400px', height: '300px' } }, '');
|
||||||
|
expect(html).toContain('width="400"');
|
||||||
|
expect(html).toContain('height="300"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('width/height attributes are omitted when the style value is not a plain px length', () => {
|
||||||
|
const { html } = toHtml({ src: 'https://example.com/photo.jpg', style: { width: '50%', height: 'auto' } }, '');
|
||||||
|
expect(html).not.toMatch(/\swidth="/);
|
||||||
|
expect(html).not.toMatch(/\sheight="/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pxAttr', () => {
|
||||||
|
test('extracts the numeric portion of a plain px length', () => {
|
||||||
|
expect(pxAttr('400px')).toBe('400');
|
||||||
|
expect(pxAttr('12.5px')).toBe('12.5');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns undefined for non-px units, non-string, or unset values', () => {
|
||||||
|
expect(pxAttr('50%')).toBeUndefined();
|
||||||
|
expect(pxAttr('auto')).toBeUndefined();
|
||||||
|
expect(pxAttr(undefined)).toBeUndefined();
|
||||||
|
expect(pxAttr(400)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml CSS framing crop (aspect-ratio + object-fit + object-position)', () => {
|
||||||
|
test('style.aspectRatio, objectFit, objectPosition all flow into the emitted style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{ src: 'https://example.com/photo.jpg', style: { aspectRatio: '16 / 9', objectFit: 'cover', objectPosition: 'center top' } },
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('aspect-ratio:16 / 9');
|
||||||
|
expect(html).toContain('object-fit:cover');
|
||||||
|
expect(html).toContain('object-position:center top');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the emitted style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
src: 'https://example.com/photo.jpg',
|
||||||
|
style: {
|
||||||
|
marginTop: '10px', marginRight: '10px', marginBottom: '10px', marginLeft: '10px',
|
||||||
|
paddingTop: '5px',
|
||||||
|
border: '2px solid #ff0000',
|
||||||
|
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||||
|
opacity: '0.8',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:10px');
|
||||||
|
expect(html).toContain('padding-top:5px');
|
||||||
|
expect(html).toContain('border:2px solid #ff0000');
|
||||||
|
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||||
|
expect(html).toContain('opacity:0.8');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ImageBlock.craft.props exposes the box-model/animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (ImageBlock as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model and crop keys', () => {
|
||||||
|
const style = (ImageBlock as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('aspectRatio');
|
||||||
|
expect(style).toHaveProperty('objectFit');
|
||||||
|
expect(style).toHaveProperty('objectPosition');
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -9,6 +9,23 @@ interface ImageBlockProps {
|
|||||||
src?: string;
|
src?: string;
|
||||||
alt?: string;
|
alt?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Extracts the numeric portion of a plain "<n>px" CSS length string, for
|
||||||
|
* emitting real `width`/`height` HTML attributes on the exported `<img>`
|
||||||
|
* (helps the browser reserve layout space before the image loads --
|
||||||
|
* avoiding CLS -- something a CSS-only width/height can't do on its own).
|
||||||
|
* Returns undefined for any other unit ('%', 'auto', '', etc.) so the
|
||||||
|
* attribute is simply omitted when the pixel size isn't known. */
|
||||||
|
export function pxAttr(v: unknown): string | undefined {
|
||||||
|
if (typeof v !== 'string') return undefined;
|
||||||
|
const m = v.trim().match(/^(\d+(?:\.\d+)?)px$/);
|
||||||
|
return m ? m[1] : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper: upload a file to the WHP API and return the proxy URL
|
// Helper: upload a file to the WHP API and return the proxy URL
|
||||||
@@ -83,7 +100,27 @@ export const ImageBlock: UserComponent<ImageBlockProps> = ({
|
|||||||
|
|
||||||
ImageBlock.craft = {
|
ImageBlock.craft = {
|
||||||
displayName: 'Image',
|
displayName: 'Image',
|
||||||
props: { src: PLACEHOLDER_SRC, alt: '', style: { width: '100%', height: 'auto' } },
|
props: {
|
||||||
|
src: PLACEHOLDER_SRC,
|
||||||
|
alt: '',
|
||||||
|
style: {
|
||||||
|
width: '100%',
|
||||||
|
height: 'auto',
|
||||||
|
aspectRatio: '',
|
||||||
|
objectFit: '' as CSSProperties['objectFit'],
|
||||||
|
objectPosition: '',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
|
},
|
||||||
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true },
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -95,5 +132,8 @@ 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(safeImageUrl(src))}"${alt}${s ? ` style="${s}"` : ''} />` };
|
const widthAttr = pxAttr((props.style as any)?.width);
|
||||||
|
const heightAttr = pxAttr((props.style as any)?.height);
|
||||||
|
const dims = `${widthAttr ? ` width="${widthAttr}"` : ''}${heightAttr ? ` height="${heightAttr}"` : ''}`;
|
||||||
|
return { html: `<img src="${escapeAttr(safeImageUrl(src))}"${alt}${dims} loading="lazy" decoding="async"${s ? ` style="${s}"` : ''} />` };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -28,6 +28,49 @@ describe('MapEmbed.toHtml iframe src ampersand encoding (F-export review Minor)'
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('MapEmbed.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the wrapper style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
address: 'New York, NY',
|
||||||
|
style: {
|
||||||
|
marginTop: '16px',
|
||||||
|
paddingRight: '4px',
|
||||||
|
border: '1px solid #cccccc',
|
||||||
|
boxShadow: '0 4px 8px rgba(0,0,0,0.12)',
|
||||||
|
opacity: '0.95',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:16px');
|
||||||
|
expect(html).toContain('padding-right:4px');
|
||||||
|
expect(html).toContain('border:1px solid #cccccc');
|
||||||
|
expect(html).toContain('box-shadow:0 4px 8px rgba(0,0,0,0.12)');
|
||||||
|
expect(html).toContain('opacity:0.95');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MapEmbed.craft.props exposes the animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (MapEmbed as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (MapEmbed as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
describe('MapEmbed.toHtml address/zoom/height XSS hardening', () => {
|
||||||
test('a malicious address cannot break out of the src or title attribute', () => {
|
test('a malicious address cannot break out of the src or title attribute', () => {
|
||||||
const malicious = 'X" onerror="alert(1)';
|
const malicious = 'X" onerror="alert(1)';
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ interface MapEmbedProps {
|
|||||||
zoom?: number;
|
zoom?: number;
|
||||||
height?: string;
|
height?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildMapUrl(address: string, zoom: number): string {
|
function buildMapUrl(address: string, zoom: number): string {
|
||||||
@@ -70,7 +75,18 @@ MapEmbed.craft = {
|
|||||||
address: 'New York, NY',
|
address: 'New York, NY',
|
||||||
zoom: 14,
|
zoom: 14,
|
||||||
height: '400px',
|
height: '400px',
|
||||||
style: {},
|
style: {
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -118,3 +118,75 @@ describe('VideoBlock.toHtml iframe src ampersand encoding (F-export review Minor
|
|||||||
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
expect(srcMatch![1]).not.toMatch(/&(?!amp;)/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.toHtml size + aspect ratio (frame honors style props, not a hardcoded 16:9)', () => {
|
||||||
|
test('direct file: style.width flows to the wrapper, style.aspectRatio flows to the <video>', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', style: { width: '50%', aspectRatio: '4 / 3' } }, '');
|
||||||
|
expect(html).toMatch(/<div style="[^"]*width:50%[^"]*"/);
|
||||||
|
expect(html).toMatch(/<video[^>]*style="[^"]*aspect-ratio:4 \/ 3[^"]*"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('direct file: no aspectRatio set -- no aspect-ratio declaration is forced onto the <video>', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4' }, '');
|
||||||
|
const videoTag = html.match(/<video[^>]*>/)![0];
|
||||||
|
expect(videoTag).not.toContain('aspect-ratio');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('YouTube/Vimeo: style.aspectRatio overrides the 16:9 default on the iframe container', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789', style: { aspectRatio: '1 / 1' } }, '');
|
||||||
|
expect(html).toMatch(/<div[^>]*style="[^"]*aspect-ratio:1 \/ 1[^"]*"[^>]*><iframe/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('YouTube/Vimeo: defaults to 16 / 9 when no aspectRatio style is set', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://vimeo.com/123456789' }, '');
|
||||||
|
expect(html).toMatch(/<div[^>]*style="[^"]*aspect-ratio:16 \/ 9[^"]*"[^>]*><iframe/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.toHtml poster + preload (file type)', () => {
|
||||||
|
test('poster attribute is emitted (escaped) and preload="metadata" is always present on a direct file', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: 'https://example.com/poster.jpg' }, '');
|
||||||
|
expect(html).toContain('poster="https://example.com/poster.jpg"');
|
||||||
|
expect(html).toContain('preload="metadata"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no poster prop -- no poster attribute is emitted, but preload="metadata" still is', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4' }, '');
|
||||||
|
expect(html).not.toContain('poster=');
|
||||||
|
expect(html).toContain('preload="metadata"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a malicious poster (javascript: scheme) is blocked by safeImageUrl', () => {
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: 'javascript:alert(1)' }, '');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a poster value cannot break out of the poster attribute', () => {
|
||||||
|
const malicious = 'https://example.com/x.jpg" onerror="alert(1)';
|
||||||
|
const { html } = toHtml({ videoUrl: 'https://example.com/clip.mp4', poster: malicious }, '');
|
||||||
|
expect(html).not.toContain('onerror="alert(1)"');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('VideoBlock.craft.props exposes the box-model/animation/visibility rollout', () => {
|
||||||
|
test('poster, animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (VideoBlock as any).craft.props;
|
||||||
|
expect(props.poster).toBe('');
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model + size/aspect keys', () => {
|
||||||
|
const style = (VideoBlock as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('width');
|
||||||
|
expect(style).toHaveProperty('aspectRatio');
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useNode, Element, UserComponent } from '@craftjs/core';
|
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 { escapeAttr, safeUrl } from '../../utils/escape';
|
import { escapeAttr, safeUrl, safeImageUrl } from '../../utils/escape';
|
||||||
|
|
||||||
/* ---------- Types ---------- */
|
/* ---------- Types ---------- */
|
||||||
|
|
||||||
@@ -12,6 +12,7 @@ interface VideoBlockProps {
|
|||||||
videoUrl?: string;
|
videoUrl?: string;
|
||||||
videoType?: VideoType;
|
videoType?: VideoType;
|
||||||
embedUrl?: string;
|
embedUrl?: string;
|
||||||
|
poster?: string;
|
||||||
autoplay?: boolean;
|
autoplay?: boolean;
|
||||||
muted?: boolean;
|
muted?: boolean;
|
||||||
loop?: boolean;
|
loop?: boolean;
|
||||||
@@ -22,6 +23,11 @@ interface VideoBlockProps {
|
|||||||
innerMaxWidth?: string;
|
innerMaxWidth?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------- URL detection ---------- */
|
/* ---------- URL detection ---------- */
|
||||||
@@ -120,6 +126,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
videoUrl = '',
|
videoUrl = '',
|
||||||
videoType: _videoTypeProp,
|
videoType: _videoTypeProp,
|
||||||
embedUrl: _embedUrlProp,
|
embedUrl: _embedUrlProp,
|
||||||
|
poster = '',
|
||||||
autoplay = false,
|
autoplay = false,
|
||||||
muted = true,
|
muted = true,
|
||||||
loop = false,
|
loop = false,
|
||||||
@@ -259,8 +266,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
paddingBottom: '56.25%',
|
aspectRatio: (style as any)?.aspectRatio || '16 / 9',
|
||||||
height: 0,
|
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
}}
|
}}
|
||||||
@@ -269,8 +275,7 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
src={buildEmbedParams(embedUrl, { autoplay, muted, loop, controls })}
|
src={buildEmbedParams(embedUrl, { autoplay, muted, loop, controls })}
|
||||||
style={{
|
style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: 0,
|
inset: 0,
|
||||||
left: 0,
|
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
@@ -284,14 +289,18 @@ export const VideoBlock: UserComponent<VideoBlockProps> = ({
|
|||||||
{type === 'file' && (
|
{type === 'file' && (
|
||||||
<video
|
<video
|
||||||
src={embedUrl}
|
src={embedUrl}
|
||||||
|
poster={poster || undefined}
|
||||||
autoPlay={autoplay}
|
autoPlay={autoplay}
|
||||||
muted={muted}
|
muted={muted}
|
||||||
loop={loop}
|
loop={loop}
|
||||||
controls={controls}
|
controls={controls}
|
||||||
|
preload="metadata"
|
||||||
playsInline
|
playsInline
|
||||||
style={{
|
style={{
|
||||||
display: 'block',
|
display: 'block',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
|
aspectRatio: (style as any)?.aspectRatio || undefined,
|
||||||
|
objectFit: 'cover',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -310,6 +319,7 @@ VideoBlock.craft = {
|
|||||||
videoUrl: '',
|
videoUrl: '',
|
||||||
videoType: 'none',
|
videoType: 'none',
|
||||||
embedUrl: '',
|
embedUrl: '',
|
||||||
|
poster: '',
|
||||||
autoplay: false,
|
autoplay: false,
|
||||||
muted: true,
|
muted: true,
|
||||||
loop: false,
|
loop: false,
|
||||||
@@ -318,7 +328,20 @@ VideoBlock.craft = {
|
|||||||
overlayColor: '#000000',
|
overlayColor: '#000000',
|
||||||
overlayOpacity: 50,
|
overlayOpacity: 50,
|
||||||
innerMaxWidth: '1200px',
|
innerMaxWidth: '1200px',
|
||||||
style: {},
|
style: {
|
||||||
|
width: '',
|
||||||
|
aspectRatio: '',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
@@ -334,6 +357,7 @@ VideoBlock.craft = {
|
|||||||
(VideoBlock as any).toHtml = (props: VideoBlockProps, childrenHtml: string) => {
|
(VideoBlock as any).toHtml = (props: VideoBlockProps, childrenHtml: string) => {
|
||||||
const {
|
const {
|
||||||
videoUrl = '',
|
videoUrl = '',
|
||||||
|
poster = '',
|
||||||
autoplay = false,
|
autoplay = false,
|
||||||
muted = true,
|
muted = true,
|
||||||
loop: doLoop = false,
|
loop: doLoop = false,
|
||||||
@@ -422,15 +446,13 @@ VideoBlock.craft = {
|
|||||||
const iframeSrc = buildEmbedParams(embedUrl, { autoplay, muted, loop: doLoop, controls });
|
const iframeSrc = buildEmbedParams(embedUrl, { autoplay, muted, loop: doLoop, controls });
|
||||||
const containerStyle = cssPropsToString({
|
const containerStyle = cssPropsToString({
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
paddingBottom: '56.25%',
|
aspectRatio: (style as any)?.aspectRatio || '16 / 9',
|
||||||
height: '0',
|
|
||||||
overflow: 'hidden',
|
overflow: 'hidden',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
});
|
});
|
||||||
const iframeStyle = cssPropsToString({
|
const iframeStyle = cssPropsToString({
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
top: '0',
|
inset: '0',
|
||||||
left: '0',
|
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
border: 'none',
|
border: 'none',
|
||||||
@@ -447,13 +469,16 @@ VideoBlock.craft = {
|
|||||||
if (doLoop) vidAttrs.push('loop');
|
if (doLoop) vidAttrs.push('loop');
|
||||||
if (controls) vidAttrs.push('controls');
|
if (controls) vidAttrs.push('controls');
|
||||||
vidAttrs.push('playsinline');
|
vidAttrs.push('playsinline');
|
||||||
|
const posterAttr = poster ? ` poster="${escapeAttr(safeImageUrl(poster))}"` : '';
|
||||||
const vidStyle = cssPropsToString({
|
const vidStyle = cssPropsToString({
|
||||||
display: 'block',
|
display: 'block',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
|
aspectRatio: (style as any)?.aspectRatio || undefined,
|
||||||
|
objectFit: 'cover',
|
||||||
borderRadius: (style as any)?.borderRadius || undefined,
|
borderRadius: (style as any)?.borderRadius || undefined,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}><video src="${escapeAttr(safeUrl(embedUrl))}" ${vidAttrs.join(' ')}${vidStyle ? ` style="${vidStyle}"` : ''}></video></div>`,
|
html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}><video src="${escapeAttr(safeUrl(embedUrl))}"${posterAttr} preload="metadata" ${vidAttrs.join(' ')}${vidStyle ? ` style="${vidStyle}"` : ''}></video></div>`,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -139,3 +139,46 @@ describe('ContentSlider.toHtml interval is NOT runtime-type-checked -- must be c
|
|||||||
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
expect(html).toMatch(/setInterval\(function\(\)\{show\(current\+1\);\},3000\);/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the section style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
slides,
|
||||||
|
style: {
|
||||||
|
marginBottom: '24px',
|
||||||
|
paddingTop: '8px',
|
||||||
|
border: '3px dashed #00ff00',
|
||||||
|
boxShadow: '0 10px 24px rgba(0,0,0,0.18)',
|
||||||
|
opacity: '0.75',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-bottom:24px');
|
||||||
|
expect(html).toContain('padding-top:8px');
|
||||||
|
expect(html).toContain('border:3px dashed #00ff00');
|
||||||
|
expect(html).toContain('box-shadow:0 10px 24px rgba(0,0,0,0.18)');
|
||||||
|
expect(html).toContain('opacity:0.75');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('ContentSlider.craft.props exposes the animation/visibility rollout', () => {
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (ContentSlider as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (ContentSlider as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -21,6 +21,11 @@ interface ContentSliderProps {
|
|||||||
showArrows?: boolean;
|
showArrows?: boolean;
|
||||||
height?: string;
|
height?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultSlides: Slide[] = [
|
const defaultSlides: Slide[] = [
|
||||||
@@ -227,7 +232,18 @@ ContentSlider.craft = {
|
|||||||
showDots: true,
|
showDots: true,
|
||||||
showArrows: true,
|
showArrows: true,
|
||||||
height: '400px',
|
height: '400px',
|
||||||
style: {},
|
style: {
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -3,6 +3,73 @@ import { Gallery } from './Gallery';
|
|||||||
|
|
||||||
const toHtml = (Gallery as any).toHtml;
|
const toHtml = (Gallery as any).toHtml;
|
||||||
|
|
||||||
|
describe('Gallery.toHtml columns + lightbox controls (previously unexposed props)', () => {
|
||||||
|
test('columns drives the grid-template-columns repeat count', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], columns: 5 }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(5,1fr)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lightbox=true adds the delegated-listener overlay markup (columns unaffected)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], columns: 4, lightbox: true }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(4,1fr)');
|
||||||
|
expect(html).toContain('role="dialog"');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a non-numeric columns value falls back safely (Number() coercion, not NaN in the template)', () => {
|
||||||
|
const { html } = toHtml({ images: [{ src: '/a.jpg' }], columns: 'not-a-number' as any }, '');
|
||||||
|
expect(html).toContain('grid-template-columns:repeat(3,1fr)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.toHtml box-model styles (margin/padding/border/shadow/opacity)', () => {
|
||||||
|
test('margin/padding/border/box-shadow/opacity all flow into the section style attribute', () => {
|
||||||
|
const { html } = toHtml(
|
||||||
|
{
|
||||||
|
images: [{ src: '/a.jpg', alt: 'a' }],
|
||||||
|
style: {
|
||||||
|
marginTop: '20px',
|
||||||
|
paddingLeft: '12px',
|
||||||
|
border: '1px solid #333333',
|
||||||
|
boxShadow: '0 1px 2px rgba(0,0,0,0.08)',
|
||||||
|
opacity: '0.9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
''
|
||||||
|
);
|
||||||
|
expect(html).toContain('margin-top:20px');
|
||||||
|
expect(html).toContain('padding-left:12px');
|
||||||
|
expect(html).toContain('border:1px solid #333333');
|
||||||
|
expect(html).toContain('box-shadow:0 1px 2px rgba(0,0,0,0.08)');
|
||||||
|
expect(html).toContain('opacity:0.9');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Gallery.craft.props exposes columns/lightbox + the animation/visibility rollout', () => {
|
||||||
|
test('columns and lightbox have their existing defaults', () => {
|
||||||
|
const props = (Gallery as any).craft.props;
|
||||||
|
expect(props.columns).toBe(3);
|
||||||
|
expect(props.lightbox).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('animation, animationDelay, hideOnDesktop/Tablet/Mobile are present with blank/false defaults', () => {
|
||||||
|
const props = (Gallery as any).craft.props;
|
||||||
|
expect(props.animation).toBe('');
|
||||||
|
expect(props.animationDelay).toBe('0');
|
||||||
|
expect(props.hideOnDesktop).toBe(false);
|
||||||
|
expect(props.hideOnTablet).toBe(false);
|
||||||
|
expect(props.hideOnMobile).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('style carries blank/default box-model keys', () => {
|
||||||
|
const style = (Gallery as any).craft.props.style;
|
||||||
|
expect(style).toHaveProperty('marginTop');
|
||||||
|
expect(style).toHaveProperty('paddingTop');
|
||||||
|
expect(style.border).toBe('none');
|
||||||
|
expect(style.boxShadow).toBe('none');
|
||||||
|
expect(style.opacity).toBe('1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('Gallery.toHtml lightbox uses a delegated listener, not per-item onclick (A4.3)', () => {
|
describe('Gallery.toHtml lightbox uses a delegated listener, not per-item onclick (A4.3)', () => {
|
||||||
test('no per-item inline onclick with interpolated src', () => {
|
test('no per-item inline onclick with interpolated src', () => {
|
||||||
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true }, '');
|
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true }, '');
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ interface GalleryProps {
|
|||||||
gap?: string;
|
gap?: string;
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
lightbox?: boolean;
|
lightbox?: boolean;
|
||||||
|
animation?: string;
|
||||||
|
animationDelay?: string;
|
||||||
|
hideOnDesktop?: boolean;
|
||||||
|
hideOnTablet?: boolean;
|
||||||
|
hideOnMobile?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const placeholderSvg = (index: number) => {
|
const placeholderSvg = (index: number) => {
|
||||||
@@ -112,8 +117,20 @@ Gallery.craft = {
|
|||||||
images: defaultImages,
|
images: defaultImages,
|
||||||
columns: 3,
|
columns: 3,
|
||||||
gap: '16px',
|
gap: '16px',
|
||||||
style: { backgroundColor: '#ffffff' },
|
style: {
|
||||||
|
backgroundColor: '#ffffff',
|
||||||
|
marginTop: '', marginRight: '', marginBottom: '', marginLeft: '',
|
||||||
|
paddingTop: '', paddingRight: '', paddingBottom: '', paddingLeft: '',
|
||||||
|
border: 'none',
|
||||||
|
boxShadow: 'none',
|
||||||
|
opacity: '1',
|
||||||
|
},
|
||||||
lightbox: false,
|
lightbox: false,
|
||||||
|
animation: '',
|
||||||
|
animationDelay: '0',
|
||||||
|
hideOnDesktop: false,
|
||||||
|
hideOnTablet: false,
|
||||||
|
hideOnMobile: false,
|
||||||
},
|
},
|
||||||
rules: {
|
rules: {
|
||||||
canDrag: () => true,
|
canDrag: () => true,
|
||||||
|
|||||||
@@ -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' },
|
||||||
|
];
|
||||||
|
|||||||
@@ -2,30 +2,28 @@ import React, { CSSProperties } from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
IMAGE_RADIUS_PRESETS,
|
IMAGE_RADIUS_PRESETS,
|
||||||
|
OBJECT_FIT,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
StylePanelProps,
|
StylePanelProps,
|
||||||
SectionLabel,
|
SectionLabel,
|
||||||
PresetButtonGrid,
|
PresetButtonGrid,
|
||||||
TextInputField,
|
TextInputField,
|
||||||
|
SizeControl,
|
||||||
|
AspectRatioControl,
|
||||||
|
FocalPointGrid,
|
||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
import { PLACEHOLDER_SRC } from '../../../components/media/ImageBlock';
|
||||||
|
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
|
||||||
|
|
||||||
/* ---------- 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 }) => {
|
||||||
const { actions } = useEditor();
|
const { actions } = useEditor();
|
||||||
const style: CSSProperties = nodeProps.style || {};
|
const style: CSSProperties = nodeProps.style || {};
|
||||||
|
|
||||||
const { setPropStyle } = useNodeProp(selectedId);
|
const { setProp, setPropStyle } = useNodeProp(selectedId);
|
||||||
|
|
||||||
const maxWidthPresets = [
|
|
||||||
{ label: '25%', value: '25%' },
|
|
||||||
{ label: '50%', value: '50%' },
|
|
||||||
{ label: '75%', value: '75%' },
|
|
||||||
{ label: '100%', value: '100%' },
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -49,6 +47,39 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Size -- Width absorbs the historical maxWidth presets (25/50/75/100%
|
||||||
|
are a subset of SizeControl's default preset row), Height is new. */}
|
||||||
|
<SizeControl
|
||||||
|
label="Width"
|
||||||
|
value={(style.maxWidth as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('maxWidth', v)}
|
||||||
|
/>
|
||||||
|
<SizeControl
|
||||||
|
label="Height"
|
||||||
|
value={(style.height as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('height', v)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Crop & Framing -- aspect-ratio + object-fit + object-position on the
|
||||||
|
<img> itself is a CSS framing crop (no server-side image processing
|
||||||
|
needed). */}
|
||||||
|
<AspectRatioControl
|
||||||
|
value={(style.aspectRatio as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('aspectRatio', v)}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Object Fit</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={OBJECT_FIT}
|
||||||
|
activeValue={(style.objectFit as string) || ''}
|
||||||
|
onSelect={(v) => setPropStyle('objectFit', v)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<FocalPointGrid
|
||||||
|
value={(style.objectPosition as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('objectPosition', v)}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Border Radius */}
|
{/* Border Radius */}
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Border Radius</SectionLabel>
|
<SectionLabel>Border Radius</SectionLabel>
|
||||||
@@ -59,15 +90,10 @@ export const ImageStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Max Width */}
|
{/* Box model + animation/visibility rollout */}
|
||||||
<div className="guided-section">
|
<BoxModelSection style={style} setPropStyle={setPropStyle} />
|
||||||
<SectionLabel>Max Width</SectionLabel>
|
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
|
||||||
<PresetButtonGrid
|
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
|
||||||
presets={maxWidthPresets}
|
|
||||||
activeValue={style.maxWidth as string}
|
|
||||||
onSelect={(v) => setPropStyle('maxWidth', v)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import React from 'react';
|
|||||||
import { useEditor } from '@craftjs/core';
|
import { useEditor } from '@craftjs/core';
|
||||||
import {
|
import {
|
||||||
BG_COLORS,
|
BG_COLORS,
|
||||||
SPACING_PRESETS,
|
|
||||||
RADIUS_PRESETS,
|
RADIUS_PRESETS,
|
||||||
} from '../../../constants/presets';
|
} from '../../../constants/presets';
|
||||||
import {
|
import {
|
||||||
@@ -13,6 +12,8 @@ import {
|
|||||||
CollapsibleSection,
|
CollapsibleSection,
|
||||||
ColorPickerField,
|
ColorPickerField,
|
||||||
ArrayPropEditor,
|
ArrayPropEditor,
|
||||||
|
SizeControl,
|
||||||
|
AspectRatioControl,
|
||||||
labelStyle,
|
labelStyle,
|
||||||
inputStyle,
|
inputStyle,
|
||||||
smallInputStyle,
|
smallInputStyle,
|
||||||
@@ -20,6 +21,14 @@ import {
|
|||||||
useNodeProp,
|
useNodeProp,
|
||||||
} from './shared';
|
} from './shared';
|
||||||
import { AssetPicker } from '../../../ui/AssetPicker';
|
import { AssetPicker } from '../../../ui/AssetPicker';
|
||||||
|
import { BoxModelSection, BorderEffectsSection, AnimVisSection } from './mediaBoxModel';
|
||||||
|
|
||||||
|
const GALLERY_COLUMN_PRESETS = [
|
||||||
|
{ label: '2', value: '2' },
|
||||||
|
{ label: '3', value: '3' },
|
||||||
|
{ label: '4', value: '4' },
|
||||||
|
{ label: '5', value: '5' },
|
||||||
|
];
|
||||||
|
|
||||||
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
|
/* ---------- MEDIA (Video / Gallery / Map / Slider) ---------- */
|
||||||
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodeProps }) => {
|
||||||
@@ -30,11 +39,48 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Video URL */}
|
{/* Video source -- upload/browse/paste-URL (paste-URL still handles
|
||||||
|
YouTube/Vimeo; upload/browse handle files via detectVideoType's
|
||||||
|
serve_asset resolution). */}
|
||||||
{nodeProps.videoUrl !== undefined && (
|
{nodeProps.videoUrl !== undefined && (
|
||||||
<div style={sectionGap}>
|
<div className="guided-section">
|
||||||
<label style={labelStyle}>Video URL</label>
|
<SectionLabel>Video Source</SectionLabel>
|
||||||
<input type="text" value={nodeProps.videoUrl || ''} onChange={(e) => setProp('videoUrl', e.target.value)} placeholder="YouTube, Vimeo, or .mp4 URL" style={inputStyle} />
|
<AssetPicker
|
||||||
|
mediaType="video"
|
||||||
|
value={nodeProps.videoUrl || ''}
|
||||||
|
onChange={(url) => setProp('videoUrl', url)}
|
||||||
|
variant="full"
|
||||||
|
placeholder="Or paste a YouTube/Vimeo/.mp4 URL..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Video size -- width + aspect ratio for the video frame. */}
|
||||||
|
{nodeProps.videoUrl !== undefined && (
|
||||||
|
<>
|
||||||
|
<SizeControl
|
||||||
|
label="Width"
|
||||||
|
value={(style.width as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('width', v)}
|
||||||
|
/>
|
||||||
|
<AspectRatioControl
|
||||||
|
value={(style.aspectRatio as string) || ''}
|
||||||
|
onChange={(v) => setPropStyle('aspectRatio', v)}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Poster image (optional, file-type videos only in practice but
|
||||||
|
harmless to offer whenever the component has a poster prop). */}
|
||||||
|
{nodeProps.poster !== undefined && (
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Poster Image (optional)</SectionLabel>
|
||||||
|
<AssetPicker
|
||||||
|
mediaType="image"
|
||||||
|
value={nodeProps.poster || ''}
|
||||||
|
onChange={(url) => setProp('poster', url)}
|
||||||
|
variant="full"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -80,6 +126,26 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Gallery layout -- columns + lightbox (existing-but-previously-unexposed props). */}
|
||||||
|
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
||||||
|
<>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Columns</SectionLabel>
|
||||||
|
<PresetButtonGrid
|
||||||
|
presets={GALLERY_COLUMN_PRESETS}
|
||||||
|
activeValue={String(nodeProps.columns ?? 3)}
|
||||||
|
onSelect={(v) => setProp('columns', Number(v))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={{ ...labelStyle, display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer' }}>
|
||||||
|
<input type="checkbox" checked={!!nodeProps.lightbox} onChange={(e) => setProp('lightbox', e.target.checked)} />
|
||||||
|
Enable Lightbox
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Gallery items */}
|
{/* Gallery items */}
|
||||||
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
{nodeProps.images !== undefined && Array.isArray(nodeProps.images) && (
|
||||||
<CollapsibleSection title="Images">
|
<CollapsibleSection title="Images">
|
||||||
@@ -178,21 +244,23 @@ export const MediaStylePanel: React.FC<StylePanelProps> = ({ selectedId, nodePro
|
|||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Background & padding */}
|
{/* Background & radius */}
|
||||||
<CollapsibleSection title="Style" defaultOpen={false}>
|
<CollapsibleSection title="Style" defaultOpen={false}>
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Background</SectionLabel>
|
<SectionLabel>Background</SectionLabel>
|
||||||
<ColorSwatchGrid colors={BG_COLORS} activeValue={style.backgroundColor} onSelect={(v: string) => setPropStyle('backgroundColor', v)} />
|
<ColorSwatchGrid colors={BG_COLORS} activeValue={style.backgroundColor} onSelect={(v: string) => setPropStyle('backgroundColor', v)} />
|
||||||
</div>
|
</div>
|
||||||
<div className="guided-section">
|
|
||||||
<SectionLabel>Padding</SectionLabel>
|
|
||||||
<PresetButtonGrid presets={SPACING_PRESETS} activeValue={style.padding as string} onSelect={(v) => setPropStyle('padding', v)} />
|
|
||||||
</div>
|
|
||||||
<div className="guided-section">
|
<div className="guided-section">
|
||||||
<SectionLabel>Border Radius</SectionLabel>
|
<SectionLabel>Border Radius</SectionLabel>
|
||||||
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
<PresetButtonGrid presets={RADIUS_PRESETS} activeValue={style.borderRadius as string} onSelect={(v) => setPropStyle('borderRadius', v)} />
|
||||||
</div>
|
</div>
|
||||||
</CollapsibleSection>
|
</CollapsibleSection>
|
||||||
|
|
||||||
|
{/* Box model + animation/visibility rollout (Video/Gallery/Map/Slider
|
||||||
|
all carry these props now, so it's safe to render unconditionally). */}
|
||||||
|
<BoxModelSection style={style} setPropStyle={setPropStyle} />
|
||||||
|
<BorderEffectsSection style={style} setPropStyle={setPropStyle} />
|
||||||
|
<AnimVisSection nodeProps={nodeProps} setProp={setProp} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
/* Same DOM-harness pattern as MediaStylePanel.slides.test.tsx -- mock
|
||||||
|
@craftjs/core's useEditor so setProp calls can be observed without
|
||||||
|
mounting a real <Editor> tree, and mock utils/assets so AssetPicker
|
||||||
|
doesn't hit the network. */
|
||||||
|
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 qAll<T extends Element = Element>(testId: string): T[] {
|
||||||
|
return Array.from(container.querySelectorAll(`[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();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MediaStylePanel Video source uses AssetPicker (upload/browse/paste-URL), not a plain text input', () => {
|
||||||
|
test('renders a full-variant AssetPicker (not the old plain input) for videoUrl', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('asset-picker-full')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('applying a pasted URL via the AssetPicker writes videoUrl (not some other key)', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
// The Video Source AssetPicker is the first url-input on the page (the
|
||||||
|
// Poster picker is a second, separate AssetPicker instance below it).
|
||||||
|
const urlInput = qAll<HTMLInputElement>('asset-picker-url-input')[0];
|
||||||
|
expect(urlInput).toBeTruthy();
|
||||||
|
setValue(urlInput, 'https://example.com/clip.mp4');
|
||||||
|
|
||||||
|
const applyBtn = qAll<HTMLButtonElement>('asset-picker-apply')[0];
|
||||||
|
act(() => {
|
||||||
|
applyBtn.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(setPropSpy).toHaveBeenCalled();
|
||||||
|
expect(lastProps.videoUrl).toBe('https://example.com/clip.mp4');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a video-shaped selection also renders a Poster AssetPicker (image) that writes `poster`', () => {
|
||||||
|
lastProps = { videoUrl: 'https://example.com/clip.mp4', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
const pickers = qAll('asset-picker-full');
|
||||||
|
expect(pickers.length).toBe(2); // Video Source + Poster Image
|
||||||
|
|
||||||
|
const urlInputs = qAll<HTMLInputElement>('asset-picker-url-input');
|
||||||
|
const posterInput = urlInputs[1];
|
||||||
|
setValue(posterInput, 'https://example.com/poster.jpg');
|
||||||
|
const applyBtns = qAll<HTMLButtonElement>('asset-picker-apply');
|
||||||
|
act(() => {
|
||||||
|
applyBtns[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(lastProps.poster).toBe('https://example.com/poster.jpg');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MediaStylePanel Video size controls (Width + Aspect Ratio) are gated on videoUrl', () => {
|
||||||
|
test('a video-shaped selection renders SizeControl + AspectRatioControl', () => {
|
||||||
|
lastProps = { videoUrl: '', poster: '', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="vid-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('size-control')).not.toBeNull();
|
||||||
|
expect(q('aspect-ratio-control')).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Map-shaped selection (no videoUrl) does NOT render the video size controls', () => {
|
||||||
|
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {} };
|
||||||
|
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
|
||||||
|
expect(q('size-control')).toBeNull();
|
||||||
|
expect(q('aspect-ratio-control')).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function openCollapsibleByTitle(title: string) {
|
||||||
|
const btn = Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.includes(title));
|
||||||
|
expect(btn).toBeTruthy();
|
||||||
|
act(() => {
|
||||||
|
btn!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MediaStylePanel box-model + animation/visibility rollout renders for every media type', () => {
|
||||||
|
test('a Map-shaped selection still gets Spacing / Border & Effects / Animation & Visibility sections (collapsed by default, open on click)', () => {
|
||||||
|
lastProps = { address: 'New York, NY', zoom: 14, height: '400px', style: {}, animation: '', hideOnDesktop: false };
|
||||||
|
render(<MediaStylePanel selectedId="map-1" nodeProps={lastProps} />);
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Spacing');
|
||||||
|
expect(q('spacing-control')).not.toBeNull();
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Border & Effects');
|
||||||
|
expect(q('border-control')).not.toBeNull();
|
||||||
|
|
||||||
|
openCollapsibleByTitle('Animation & Visibility');
|
||||||
|
expect(q('animation-control')).not.toBeNull();
|
||||||
|
expect(q('visibility-control')).not.toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { SHADOW_PRESETS } from '../../../constants/presets';
|
||||||
|
import {
|
||||||
|
SectionLabel,
|
||||||
|
PresetButtonGrid,
|
||||||
|
CollapsibleSection,
|
||||||
|
SpacingControl,
|
||||||
|
SpacingSide,
|
||||||
|
BorderControl,
|
||||||
|
BorderValue,
|
||||||
|
buildBorderShorthand,
|
||||||
|
AnimationControl,
|
||||||
|
VisibilityControl,
|
||||||
|
sectionGap,
|
||||||
|
labelStyle,
|
||||||
|
} from './shared';
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
Shared box-model / border+effects / animation+visibility sections for the
|
||||||
|
MEDIA package's panels (ImageStylePanel + MediaStylePanel). Kept local to
|
||||||
|
this package (not in shared.tsx, which is foundation/import-only) since
|
||||||
|
it's just DRY-ing the identical JSX block across ImageBlock/VideoBlock/
|
||||||
|
Gallery/ContentSlider/MapEmbed rather than a genuinely cross-package
|
||||||
|
reusable control.
|
||||||
|
========================================================================== */
|
||||||
|
|
||||||
|
function capitalize(s: string): string {
|
||||||
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parses a `border` shorthand string (e.g. "2px solid #ff0000") back into
|
||||||
|
* the {width,style,color} shape BorderControl edits. Only needs to
|
||||||
|
* round-trip values this same panel produced via buildBorderShorthand --
|
||||||
|
* not arbitrary author-supplied CSS. */
|
||||||
|
export function parseBorderShorthand(v: string | undefined): BorderValue {
|
||||||
|
if (!v || v === 'none') return { width: '', style: 'none', color: '#000000' };
|
||||||
|
const m = String(v).trim().match(/^(\d+(?:\.\d+)?(?:px|em|rem)?)\s+(\w+)\s+(.+)$/);
|
||||||
|
if (!m) return { width: '', style: 'none', color: '#000000' };
|
||||||
|
return { width: m[1], style: m[2], color: m[3] };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BoxModelSectionProps {
|
||||||
|
style: Record<string, any>;
|
||||||
|
setPropStyle: (prop: string, value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Margin + Padding, per-side, via the shared SpacingControl. */
|
||||||
|
export const BoxModelSection: React.FC<BoxModelSectionProps> = ({ style, setPropStyle }) => {
|
||||||
|
const sideSetter = (kind: 'margin' | 'padding') => (side: SpacingSide, value: string) =>
|
||||||
|
setPropStyle(`${kind}${capitalize(side)}`, value);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<CollapsibleSection title="Spacing" defaultOpen={false}>
|
||||||
|
<SpacingControl
|
||||||
|
label="Margin"
|
||||||
|
value={{ top: style.marginTop, right: style.marginRight, bottom: style.marginBottom, left: style.marginLeft }}
|
||||||
|
onChange={sideSetter('margin')}
|
||||||
|
/>
|
||||||
|
<SpacingControl
|
||||||
|
label="Padding"
|
||||||
|
value={{ top: style.paddingTop, right: style.paddingRight, bottom: style.paddingBottom, left: style.paddingLeft }}
|
||||||
|
onChange={sideSetter('padding')}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** style.opacity is stored as a CSS-length-free numeric string ("0.8") or
|
||||||
|
* may be blank/undefined (treated as fully opaque). Converts to a 0-100
|
||||||
|
* integer for the range input / label. */
|
||||||
|
function opacityPercent(v: unknown): number {
|
||||||
|
if (v === undefined || v === null || v === '') return 100;
|
||||||
|
const n = parseFloat(String(v));
|
||||||
|
return Number.isFinite(n) ? Math.round(n * 100) : 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BorderEffectsSectionProps {
|
||||||
|
style: Record<string, any>;
|
||||||
|
setPropStyle: (prop: string, value: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Border (width/style/color) + box-shadow preset + opacity slider. */
|
||||||
|
export const BorderEffectsSection: React.FC<BorderEffectsSectionProps> = ({ style, setPropStyle }) => (
|
||||||
|
<CollapsibleSection title="Border & Effects" defaultOpen={false}>
|
||||||
|
<BorderControl
|
||||||
|
value={parseBorderShorthand(style.border)}
|
||||||
|
onChange={(v) => setPropStyle('border', buildBorderShorthand(v))}
|
||||||
|
/>
|
||||||
|
<div className="guided-section">
|
||||||
|
<SectionLabel>Shadow</SectionLabel>
|
||||||
|
<PresetButtonGrid presets={SHADOW_PRESETS} activeValue={style.boxShadow} onSelect={(v) => setPropStyle('boxShadow', v)} />
|
||||||
|
</div>
|
||||||
|
<div style={sectionGap}>
|
||||||
|
<label style={labelStyle}>Opacity: {opacityPercent(style.opacity)}%</label>
|
||||||
|
<input
|
||||||
|
type="range"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
value={opacityPercent(style.opacity)}
|
||||||
|
onChange={(e) => setPropStyle('opacity', String(Number(e.target.value) / 100))}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
|
|
||||||
|
export interface AnimVisSectionProps {
|
||||||
|
nodeProps: Record<string, any>;
|
||||||
|
setProp: (key: string, value: any) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entrance animation + responsive hide toggles -- top-level props consumed
|
||||||
|
* directly by html-export.ts's buildDataAttrs (no toHtml change needed). */
|
||||||
|
export const AnimVisSection: React.FC<AnimVisSectionProps> = ({ nodeProps, setProp }) => (
|
||||||
|
<CollapsibleSection title="Animation & Visibility" defaultOpen={false}>
|
||||||
|
<AnimationControl
|
||||||
|
value={{ animation: nodeProps.animation || 'none', animationDelay: nodeProps.animationDelay }}
|
||||||
|
onChange={(v) => { setProp('animation', v.animation); setProp('animationDelay', v.animationDelay); }}
|
||||||
|
/>
|
||||||
|
<VisibilityControl
|
||||||
|
value={{
|
||||||
|
hideOnDesktop: nodeProps.hideOnDesktop,
|
||||||
|
hideOnTablet: nodeProps.hideOnTablet,
|
||||||
|
hideOnMobile: nodeProps.hideOnMobile,
|
||||||
|
}}
|
||||||
|
onChange={(v) => {
|
||||||
|
setProp('hideOnDesktop', !!v.hideOnDesktop);
|
||||||
|
setProp('hideOnTablet', !!v.hideOnTablet);
|
||||||
|
setProp('hideOnMobile', !!v.hideOnMobile);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</CollapsibleSection>
|
||||||
|
);
|
||||||
@@ -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';
|
||||||
|
|
||||||
@@ -372,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>
|
||||||
|
);
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { createRoot, Root } from 'react-dom/client';
|
||||||
|
import { act } from 'react-dom/test-utils';
|
||||||
|
import { Editor, Frame, Element, useEditor } from '@craftjs/core';
|
||||||
|
import { componentResolver } from '../components/resolver';
|
||||||
|
import { Container } from '../components/layout/Container';
|
||||||
|
import { EditorConfigProvider } from '../state/EditorConfigContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration test harness.
|
||||||
|
*
|
||||||
|
* Mounts an ACTUAL `<Editor resolver={componentResolver}>` + `<Frame>` via
|
||||||
|
* `react-dom/client`'s `createRoot` (no `@testing-library/react`, matching
|
||||||
|
* the existing `*.test.tsx` convention in this repo -- see
|
||||||
|
* `useKeyboardShortcuts.test.tsx` / `RenderNode.test.tsx`). Nothing in
|
||||||
|
* `@craftjs/core` is mocked here: `query`/`actions` come straight out of a
|
||||||
|
* live `useEditor()` call, so `regenerateTreeIds`, `buildNodeTree`,
|
||||||
|
* `parseFreshNode`, `addNodeTree`, `deserialize`, and `serialize` all run
|
||||||
|
* their REAL implementations against a REAL Craft.js `EditorStore`.
|
||||||
|
*
|
||||||
|
* Why this catches bugs the mocked unit tests didn't: a hand-rolled fake
|
||||||
|
* `useEditor`/`query`/`node().toNodeTree()` can only echo back whatever
|
||||||
|
* plain-data shape the test author imagined -- it has no way to reproduce
|
||||||
|
* Craft's actual internal node shape (`data.type` as a live component
|
||||||
|
* function reference, real `parseFreshNode` resolver validation, real
|
||||||
|
* `<Frame>` rendering). Every one of the three historical bugs this suite
|
||||||
|
* targets (`regenerateTreeIds` + `structuredClone`, `TemplateModal` dropping
|
||||||
|
* `children`, `buildNodeTree` emitting `data.type={resolvedName}`) slipped
|
||||||
|
* past its mocked unit test for exactly that reason.
|
||||||
|
*
|
||||||
|
* jsdom shims: as of writing, mounting `<Editor><Frame>...` in this repo's
|
||||||
|
* jsdom (v29, see vitest.config.ts) did NOT require stubbing
|
||||||
|
* `ResizeObserver`/`matchMedia`/`getBoundingClientRect` -- none of the
|
||||||
|
* components exercised by these integration tests read layout geometry
|
||||||
|
* during render. `ensureJsdomShims()` below still installs a `ResizeObserver`
|
||||||
|
* stub defensively (idempotent, only if absent) since it's the one API
|
||||||
|
* Craft/DOM-heavy component code most commonly reaches for and a future
|
||||||
|
* template/component could easily start needing it; add further shims here
|
||||||
|
* (not per-test) if a future component trips over a missing browser API.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let shimsInstalled = false;
|
||||||
|
|
||||||
|
/** Install browser APIs jsdom doesn't implement, if not already present. Safe
|
||||||
|
* to call multiple times (idempotent) and safe in a real browser (guarded by
|
||||||
|
* `typeof` checks, so it never clobbers a real implementation). */
|
||||||
|
export function ensureJsdomShims(): void {
|
||||||
|
if (shimsInstalled) return;
|
||||||
|
shimsInstalled = true;
|
||||||
|
|
||||||
|
if (typeof (globalThis as any).ResizeObserver === 'undefined') {
|
||||||
|
class ResizeObserverStub {
|
||||||
|
observe() {}
|
||||||
|
unobserve() {}
|
||||||
|
disconnect() {}
|
||||||
|
}
|
||||||
|
(globalThis as any).ResizeObserver = ResizeObserverStub;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window !== 'undefined' && typeof window.matchMedia !== 'function') {
|
||||||
|
window.matchMedia = ((query: string) => ({
|
||||||
|
matches: false,
|
||||||
|
media: query,
|
||||||
|
onchange: null,
|
||||||
|
addListener: () => {},
|
||||||
|
removeListener: () => {},
|
||||||
|
addEventListener: () => {},
|
||||||
|
removeEventListener: () => {},
|
||||||
|
dispatchEvent: () => false,
|
||||||
|
})) as unknown as typeof window.matchMedia;
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsdom (as of v29, used by this repo's vitest.config.ts) does NOT
|
||||||
|
// implement `HTMLElement.prototype.innerText` at all -- `'innerText' in
|
||||||
|
// document.createElement('div')` is `false`, so assigning to it (as
|
||||||
|
// `Heading.tsx`/`TextBlock.tsx` do imperatively in a `useEffect`, to avoid
|
||||||
|
// fighting `contentEditable`'s caret position on every prop update) just
|
||||||
|
// sets a throwaway own-property that never touches `textContent`/
|
||||||
|
// `innerHTML` -- real rendered text from these two components would
|
||||||
|
// silently read back as empty in any DOM assertion. Shimmed as a plain
|
||||||
|
// `textContent` alias (real `innerText` also collapses whitespace/applies
|
||||||
|
// layout-based visibility, neither of which matters for these tests).
|
||||||
|
if (typeof HTMLElement !== 'undefined') {
|
||||||
|
if (!Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText')) {
|
||||||
|
Object.defineProperty(HTMLElement.prototype, 'innerText', {
|
||||||
|
configurable: true,
|
||||||
|
get(this: HTMLElement) {
|
||||||
|
return this.textContent;
|
||||||
|
},
|
||||||
|
set(this: HTMLElement, value: string) {
|
||||||
|
this.textContent = value;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CapturedApi {
|
||||||
|
query: any;
|
||||||
|
actions: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Invisible child that grabs a live `query`/`actions` pair out of a real
|
||||||
|
* `useEditor()` call and writes them into a mutable ref the harness owns --
|
||||||
|
* the same "Capture" pattern the brief describes and
|
||||||
|
* `template-zone-export.test.tsx` already uses ad hoc; this hoists it into a
|
||||||
|
* reusable helper. `query`/`actions` from Craft.js are live references (they
|
||||||
|
* read the current store at call time, not a react-state snapshot), so
|
||||||
|
* capturing them once on first render is sufficient -- no need to re-grab
|
||||||
|
* them after every store mutation. */
|
||||||
|
const Capture: React.FC<{ apiRef: React.MutableRefObject<CapturedApi | null> }> = ({ apiRef }) => {
|
||||||
|
const { query, actions } = useEditor();
|
||||||
|
apiRef.current = { query, actions };
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface EditorHarnessOptions {
|
||||||
|
/** A `query.serialize()`-shaped JSON string to `actions.deserialize()`
|
||||||
|
* immediately after mount, replacing the default empty ROOT. */
|
||||||
|
initialState?: string;
|
||||||
|
/** Craft.js `Frame` seed root tag -- 'div' for a regular page, 'header'/
|
||||||
|
* 'footer' for zone editing (mirrors `Canvas.tsx`'s `frameTag`). Ignored
|
||||||
|
* once `initialState` is given (deserialize replaces ROOT anyway); only
|
||||||
|
* affects the very first (pre-deserialize) paint. */
|
||||||
|
frameTag?: 'div' | 'header' | 'footer';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EditorHarness {
|
||||||
|
/** Live `query` from the real `useEditor()` -- reads current store state. */
|
||||||
|
readonly query: any;
|
||||||
|
/** Live `actions` from the real `useEditor()`. */
|
||||||
|
readonly actions: any;
|
||||||
|
/** `query.serialize()` -- the exact string `PageContext`/`useWhpApi` persist
|
||||||
|
* and `exportBodyHtml` consumes. */
|
||||||
|
getSerialized: () => string;
|
||||||
|
/** The DOM node the whole tree (including the real rendered `<Frame>`
|
||||||
|
* content) is mounted under -- assert on `.textContent`/`.innerHTML` here
|
||||||
|
* to verify actual rendering, not just serialized state. */
|
||||||
|
container: HTMLDivElement;
|
||||||
|
/** Re-exported `act` from `react-dom/test-utils` for convenience, matching
|
||||||
|
* the existing `*.test.tsx` files in this repo. */
|
||||||
|
act: typeof act;
|
||||||
|
/** Mount (or replace) an additional child inside the live `<Editor>` tree,
|
||||||
|
* alongside `<Frame>` -- e.g. a probe component that calls a real hook
|
||||||
|
* (`useNodeActions`, `useKeyboardShortcuts`) so the test can drive it
|
||||||
|
* against the REAL editor instance this harness set up. Wrapped in `act`. */
|
||||||
|
mountChild: (node: React.ReactNode) => void;
|
||||||
|
/** Unmounts the React tree and removes `container` from `document.body`. */
|
||||||
|
unmount: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mounts a real `<Editor resolver={componentResolver}>` + `<Frame>` (via
|
||||||
|
* `EditorConfigProvider config={null}` -- standalone mode, no WHP backend)
|
||||||
|
* and returns live `query`/`actions` plus helpers for driving further
|
||||||
|
* real-editor interactions from a test.
|
||||||
|
*/
|
||||||
|
export function renderEditorHarness(opts: EditorHarnessOptions = {}): EditorHarness {
|
||||||
|
ensureJsdomShims();
|
||||||
|
|
||||||
|
const container = document.createElement('div');
|
||||||
|
document.body.appendChild(container);
|
||||||
|
|
||||||
|
const apiRef: React.MutableRefObject<CapturedApi | null> = { current: null };
|
||||||
|
let extraChild: React.ReactNode = null;
|
||||||
|
let root: Root;
|
||||||
|
|
||||||
|
const frameTag = opts.frameTag ?? 'div';
|
||||||
|
|
||||||
|
function paint() {
|
||||||
|
root.render(
|
||||||
|
<EditorConfigProvider config={null}>
|
||||||
|
<Editor resolver={componentResolver} enabled={true}>
|
||||||
|
<Frame>
|
||||||
|
<Element is={Container} canvas tag={frameTag} style={{}} />
|
||||||
|
</Frame>
|
||||||
|
<Capture apiRef={apiRef} />
|
||||||
|
{extraChild}
|
||||||
|
</Editor>
|
||||||
|
</EditorConfigProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
root = createRoot(container);
|
||||||
|
paint();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (opts.initialState) {
|
||||||
|
act(() => {
|
||||||
|
apiRef.current!.actions.deserialize(opts.initialState!);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
get query() {
|
||||||
|
return apiRef.current!.query;
|
||||||
|
},
|
||||||
|
get actions() {
|
||||||
|
return apiRef.current!.actions;
|
||||||
|
},
|
||||||
|
getSerialized: () => apiRef.current!.query.serialize(),
|
||||||
|
container,
|
||||||
|
act,
|
||||||
|
mountChild: (node: React.ReactNode) => {
|
||||||
|
extraChild = node;
|
||||||
|
act(() => {
|
||||||
|
paint();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
unmount: () => {
|
||||||
|
act(() => {
|
||||||
|
root.unmount();
|
||||||
|
});
|
||||||
|
container.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { useApplyAiResponse } from '../../utils/apply-ai-response';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
import type { SitesmithResponse } from '../../types/sitesmith';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for applying a Sitesmith (AI)
|
||||||
|
* response.
|
||||||
|
*
|
||||||
|
* Historical bug: `buildNodeTree` used to hand `query.parseFreshNode`/the
|
||||||
|
* manually-constructed synthetic node a `data.type` of the SERIALIZED
|
||||||
|
* `{ resolvedName }` wrapper object (or, in an earlier attempt, a bare
|
||||||
|
* resolvedName string) instead of the actual component function reference
|
||||||
|
* from `componentResolver`. A live Craft.js node's renderer does
|
||||||
|
* `React.createElement(data.type, props)` directly, so anything other than
|
||||||
|
* a real component reference either fails Craft's own resolver validation
|
||||||
|
* inside `parseFreshNode`/`addNodeTree` ("component type ... does not exist
|
||||||
|
* in the resolver") or -- worse -- passes that validation but renders
|
||||||
|
* nothing/garbage. Either way, a section-replace or insert AI op became a
|
||||||
|
* silent no-op in the live app. The pre-existing mocked unit test
|
||||||
|
* (`apply-ai-response.test.ts`) fakes `query.parseFreshNode` as
|
||||||
|
* `(input) => ({ toNode: () => input })` -- a pure echo with NO validation
|
||||||
|
* at all -- so it could never have caught `buildNodeTree` emitting the
|
||||||
|
* wrong `data.type` shape.
|
||||||
|
*
|
||||||
|
* This suite drives the REAL `useApplyAiResponse()` hook (the exact
|
||||||
|
* consumer-facing API `SitesmithModal`/`useSitesmith` call after a
|
||||||
|
* successful AI response) against a real `EditorStore`/`<Frame>` from
|
||||||
|
* `editorHarness.tsx` -- so a regression in `buildNodeTree`'s `data.type`
|
||||||
|
* would throw here (real `parseFreshNode` resolver validation) or fail the
|
||||||
|
* "content actually landed" assertions (real render/export), exactly as it
|
||||||
|
* did live.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const INITIAL_STATE = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'div' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: ['anchor-1'],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'anchor-1': {
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: { text: 'Anchor Heading', level: 'h2' },
|
||||||
|
displayName: 'Heading',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Mounts `useApplyAiResponse()` (the real hook) inside the harness's live
|
||||||
|
* Editor and returns the captured `apply` function. */
|
||||||
|
function mountApplyFn(h: EditorHarness): { current: ReturnType<typeof useApplyAiResponse> | null } {
|
||||||
|
const ref: { current: ReturnType<typeof useApplyAiResponse> | null } = { current: null };
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
ref.current = useApplyAiResponse();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
h.mountChild(<Probe />);
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AI apply-response (real @craftjs/core editor)', () => {
|
||||||
|
test('section-scope replace with no target: appends a real, rendered node -- not a silent no-op', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
expect(applyRef.current).not.toBeNull();
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'replace',
|
||||||
|
scope: 'section',
|
||||||
|
pages: [
|
||||||
|
{
|
||||||
|
name: 'section',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Inserted Heading Panel' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'inserted a section',
|
||||||
|
};
|
||||||
|
|
||||||
|
let result: { ok: boolean; message?: string } | undefined;
|
||||||
|
await harness.act(async () => {
|
||||||
|
result = await applyRef.current!(resp);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result!.ok).toBe(true);
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(2);
|
||||||
|
expect(rootChildren).toContain('anchor-1');
|
||||||
|
const newId = rootChildren.find((id) => id !== 'anchor-1')!;
|
||||||
|
expect(newId).toBeDefined();
|
||||||
|
|
||||||
|
// Real node.data.type must be the actual component reference so React
|
||||||
|
// can render it -- not a `{resolvedName}` wrapper or a bare string.
|
||||||
|
const newNodeType = harness.query.node(newId).get().data.type;
|
||||||
|
expect(typeof newNodeType).toBe('function');
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('AI Inserted Heading Panel');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('AI Inserted Heading Panel');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('section-scope replace WITH a target node: replaces that node in place (same slot, fresh id)', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'replace',
|
||||||
|
scope: 'section',
|
||||||
|
pages: [
|
||||||
|
{
|
||||||
|
name: 'section',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Replaced The Anchor' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'replaced the section',
|
||||||
|
};
|
||||||
|
|
||||||
|
await harness.act(async () => {
|
||||||
|
await applyRef.current!(resp, 'anchor-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(1); // still just one node in that slot
|
||||||
|
expect(rootChildren).not.toContain('anchor-1'); // the old node is gone
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('AI Replaced The Anchor');
|
||||||
|
expect(harness.container.textContent).not.toContain('Anchor Heading');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('patch op insert_after: inserts a real node as the very next sibling', async () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
const applyRef = mountApplyFn(harness);
|
||||||
|
|
||||||
|
const resp: SitesmithResponse = {
|
||||||
|
type: 'patch',
|
||||||
|
ops: [
|
||||||
|
{
|
||||||
|
op: 'insert_after',
|
||||||
|
node_id: 'anchor-1',
|
||||||
|
tree: { type: { resolvedName: 'Heading' }, props: { text: 'AI Patched In After Anchor' }, nodes: [] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
message: 'patched',
|
||||||
|
};
|
||||||
|
|
||||||
|
let result: { ok: boolean; message?: string } | undefined;
|
||||||
|
await harness.act(async () => {
|
||||||
|
result = await applyRef.current!(resp);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result!.ok).toBe(true);
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toHaveLength(2);
|
||||||
|
expect(rootChildren[0]).toBe('anchor-1');
|
||||||
|
const insertedId = rootChildren[1];
|
||||||
|
|
||||||
|
expect(typeof harness.query.node(insertedId).get().data.type).toBe('function');
|
||||||
|
expect(harness.container.textContent).toContain('AI Patched In After Anchor');
|
||||||
|
// The original anchor is untouched.
|
||||||
|
expect(harness.container.textContent).toContain('Anchor Heading');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import React from 'react';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { useNodeActions, NodeActions } from '../../hooks/useNodeActions';
|
||||||
|
import { useKeyboardShortcuts } from '../../hooks/useKeyboardShortcuts';
|
||||||
|
import { getClipboardNodeId, setClipboardNodeId } from '../../hooks/clipboard';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for duplicate/paste.
|
||||||
|
*
|
||||||
|
* Historical bug: `regenerateTreeIds` used `structuredClone(oldNode.data)` to
|
||||||
|
* clone a copied subtree. For a REAL (live) Craft.js node, `data.type` is the
|
||||||
|
* actual component function reference (not a plain `{resolvedName}` string
|
||||||
|
* wrapper) -- `structuredClone` cannot clone a function and throws
|
||||||
|
* `DataCloneError`, which silently broke duplicate/paste for EVERY
|
||||||
|
* component in the real app. The pre-existing mocked unit tests
|
||||||
|
* (`useNodeActions.test.tsx`, `useKeyboardShortcuts.test.tsx`) faked
|
||||||
|
* `query.node(id).toNodeTree()` to return a plain-data object with
|
||||||
|
* `type: { resolvedName: 'Container' }` -- never a function -- so
|
||||||
|
* `structuredClone` never saw anything it couldn't clone there, and the bug
|
||||||
|
* shipped anyway.
|
||||||
|
*
|
||||||
|
* This suite drives the REAL `useNodeActions`/`useKeyboardShortcuts` hooks
|
||||||
|
* (no `vi.mock('@craftjs/core')` anywhere) against a real
|
||||||
|
* `EditorStore`/`query`/`actions` from `editorHarness.tsx`, on a real
|
||||||
|
* `SocialLinks` node (its `.craft` config makes Craft.js store the actual
|
||||||
|
* `SocialLinks` function as `data.type`) -- so a regression back to
|
||||||
|
* `structuredClone(oldNode.data)` throws here exactly as it did live. See
|
||||||
|
* `task-integ-harness-report.md` for the recorded red-proof run.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const INITIAL_STATE = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'div' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: ['social-1', 'heading-1'],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'social-1': {
|
||||||
|
type: { resolvedName: 'SocialLinks' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: {
|
||||||
|
links: [{ platform: 'facebook', url: 'https://facebook.com/original' }],
|
||||||
|
iconColor: '#ffffff',
|
||||||
|
},
|
||||||
|
displayName: 'Social Links',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
'heading-1': {
|
||||||
|
type: { resolvedName: 'Heading' },
|
||||||
|
isCanvas: false,
|
||||||
|
props: { text: 'Sibling Heading', level: 'h2' },
|
||||||
|
displayName: 'Heading',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
parent: 'ROOT',
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
setClipboardNodeId(null);
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('duplicate/paste (real @craftjs/core editor)', () => {
|
||||||
|
test('useNodeActions().duplicate() on a real SocialLinks node: no throw, +1 node, inserted right after the source, with an independent props copy', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
|
||||||
|
const before = Object.keys(harness.query.getNodes());
|
||||||
|
expect(before).toHaveLength(3); // ROOT, social-1, heading-1
|
||||||
|
|
||||||
|
const probeRef: { current: NodeActions | null } = { current: null };
|
||||||
|
const Probe: React.FC = () => {
|
||||||
|
probeRef.current = useNodeActions('social-1');
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
harness.mountChild(<Probe />);
|
||||||
|
expect(probeRef.current).not.toBeNull();
|
||||||
|
|
||||||
|
let newId: string | null = null;
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => {
|
||||||
|
newId = probeRef.current!.duplicate();
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(newId).not.toBeNull();
|
||||||
|
expect(newId).not.toBe('social-1');
|
||||||
|
|
||||||
|
// +1 node overall.
|
||||||
|
const after = Object.keys(harness.query.getNodes());
|
||||||
|
expect(after).toHaveLength(4);
|
||||||
|
|
||||||
|
// Inserted immediately AFTER the source, not appended at the end.
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toEqual(['social-1', newId, 'heading-1']);
|
||||||
|
|
||||||
|
// The new node was selected.
|
||||||
|
expect(Array.from(harness.query.getEvent('selected').all())).toEqual([newId]);
|
||||||
|
|
||||||
|
// The copy's props object (and any nested arrays/objects within it) must
|
||||||
|
// be a SEPARATE object from the original -- not shared by reference.
|
||||||
|
const originalProps = harness.query.node('social-1').get().data.props;
|
||||||
|
const copyProps = harness.query.node(newId!).get().data.props;
|
||||||
|
expect(copyProps).not.toBe(originalProps);
|
||||||
|
expect(copyProps.links).not.toBe(originalProps.links);
|
||||||
|
expect(copyProps).toEqual(originalProps); // same VALUES though
|
||||||
|
|
||||||
|
// Mutating the copy via setProp must not affect the original.
|
||||||
|
harness.act(() => {
|
||||||
|
harness!.actions.setProp(newId!, (p: any) => {
|
||||||
|
p.links[0].url = 'https://facebook.com/MUTATED-COPY';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
expect(harness.query.node(newId!).get().data.props.links[0].url).toBe(
|
||||||
|
'https://facebook.com/MUTATED-COPY',
|
||||||
|
);
|
||||||
|
expect(harness.query.node('social-1').get().data.props.links[0].url).toBe(
|
||||||
|
'https://facebook.com/original',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Real DOM assertion, not just serialized state: the Frame actually
|
||||||
|
// re-rendered with a second SocialLinks <a> link on the canvas.
|
||||||
|
expect(harness.container.querySelectorAll('a[href="https://facebook.com/original"]')).toHaveLength(1);
|
||||||
|
expect(harness.container.querySelectorAll('a[href="https://facebook.com/MUTATED-COPY"]')).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Ctrl+C / Ctrl+V (useKeyboardShortcuts) on the real editor: pastes a fresh-id sibling copy, original untouched', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: INITIAL_STATE });
|
||||||
|
|
||||||
|
const Consumer: React.FC = () => {
|
||||||
|
useKeyboardShortcuts();
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
harness.mountChild(<Consumer />);
|
||||||
|
|
||||||
|
// Select + copy social-1.
|
||||||
|
harness.act(() => {
|
||||||
|
harness!.actions.selectNode('social-1');
|
||||||
|
});
|
||||||
|
harness.act(() => {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new KeyboardEvent('keydown', { key: 'c', ctrlKey: true, bubbles: true, cancelable: true }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
expect(getClipboardNodeId()).toBe('social-1');
|
||||||
|
|
||||||
|
// Select heading-1 (a sibling), then paste -- should land as a sibling
|
||||||
|
// of heading-1's parent (ROOT), with brand-new ids.
|
||||||
|
harness.act(() => {
|
||||||
|
harness!.actions.selectNode('heading-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
const before = Object.keys(harness.query.getNodes());
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, bubbles: true, cancelable: true }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
const after = Object.keys(harness.query.getNodes());
|
||||||
|
expect(after).toHaveLength(before.length + 1);
|
||||||
|
|
||||||
|
const pastedId = after.find((id) => !before.includes(id))!;
|
||||||
|
expect(pastedId).toBeDefined();
|
||||||
|
|
||||||
|
const rootChildren: string[] = harness.query.node('ROOT').get().data.nodes;
|
||||||
|
expect(rootChildren).toContain(pastedId);
|
||||||
|
|
||||||
|
// Independent props copy again -- same class of bug, same guard.
|
||||||
|
const pastedProps = harness.query.node(pastedId).get().data.props;
|
||||||
|
const originalProps = harness.query.node('social-1').get().data.props;
|
||||||
|
expect(pastedProps.links).not.toBe(originalProps.links);
|
||||||
|
expect(pastedProps).toEqual(originalProps);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import { describe, test, expect, afterEach } from 'vitest';
|
||||||
|
import { renderEditorHarness, EditorHarness } from '../editorHarness';
|
||||||
|
import { allTemplates } from '../../templates';
|
||||||
|
import { buildNodeTree } from '../../utils/craft-tree';
|
||||||
|
import { templateComponentToTreeNode } from '../../templates/apply-template';
|
||||||
|
import { exportBodyHtml } from '../../utils/html-export';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Real-`@craftjs/core` integration coverage for loading a template.
|
||||||
|
*
|
||||||
|
* Historical bug: `TemplateModal.addTemplateComponents` used to build each
|
||||||
|
* template component via `React.createElement(Component, comp.props)` with
|
||||||
|
* NO children argument, silently dropping every nested `children` array
|
||||||
|
* authored in `templates/definitions.ts` (e.g. `makeHeader()`'s
|
||||||
|
* `Container > Logo + Menu`, `makeFooterContent()`'s `Container > TextBlock`,
|
||||||
|
* or any page `Section` wrapping a `Heading`/`ColumnLayout`). The resulting
|
||||||
|
* Craft.js node had `nodes: []`, so both the editor's own header/footer zone
|
||||||
|
* preview AND the published HTML (same `exportBodyHtml` path) rendered as an
|
||||||
|
* empty strip instead of the real nav/footer/section content. The mocked
|
||||||
|
* unit test for `templateComponentToTreeNode` (`apply-template.test.ts`)
|
||||||
|
* tests the pure conversion function in isolation and would pass either way
|
||||||
|
* -- it never drove the result through a real Craft.js tree/render, so it
|
||||||
|
* couldn't have caught `TemplateModal` itself dropping children at the
|
||||||
|
* call site.
|
||||||
|
*
|
||||||
|
* This suite drives the EXACT same path `TemplateModal.tsx`'s
|
||||||
|
* `addTemplateComponents` uses against a REAL Craft.js editor mounted with a
|
||||||
|
* REAL `<Frame>` (via `editorHarness.tsx`) -- so it also exercises real
|
||||||
|
* component rendering (Section/Container SHELL_INNER canvases, ColumnLayout
|
||||||
|
* linked columns), not just tree-shape assertions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const tpl = allTemplates.find((t) => t.id === 'saas-landing')!;
|
||||||
|
|
||||||
|
/** Mirrors TemplateModal.tsx's addTemplateComponents(). */
|
||||||
|
function addTemplateComponents(harness: EditorHarness, components: any[]) {
|
||||||
|
for (const comp of components) {
|
||||||
|
const tree = buildNodeTree(harness.query, templateComponentToTreeNode(comp));
|
||||||
|
harness.actions.addNodeTree(tree, 'ROOT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const EMPTY_HEADER_ROOT = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'header' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const EMPTY_FOOTER_ROOT = JSON.stringify({
|
||||||
|
ROOT: {
|
||||||
|
type: { resolvedName: 'Container' },
|
||||||
|
isCanvas: true,
|
||||||
|
props: { style: {}, tag: 'footer' },
|
||||||
|
displayName: 'Container',
|
||||||
|
custom: {},
|
||||||
|
hidden: false,
|
||||||
|
nodes: [],
|
||||||
|
linkedNodes: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
let harness: EditorHarness | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (harness) {
|
||||||
|
harness.unmount();
|
||||||
|
harness = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('template load (real @craftjs/core editor + real <Frame> render)', () => {
|
||||||
|
test('sanity: the SaaS Landing template actually has nested header/footer/page content to lose', () => {
|
||||||
|
expect(tpl).toBeDefined();
|
||||||
|
expect(tpl.header.components.length).toBeGreaterThan(0);
|
||||||
|
expect(tpl.footer.components.length).toBeGreaterThan(0);
|
||||||
|
expect(tpl.pages[0].content.components.length).toBeGreaterThan(0);
|
||||||
|
const hasNestedChildren = tpl.header.components.some((c: any) => (c.children?.length ?? 0) > 0);
|
||||||
|
expect(hasNestedChildren).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the header keeps its nested nav links + logo -- both in the real DOM and in export', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: EMPTY_HEADER_ROOT, frameTag: 'header' });
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, tpl.header.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
// Real rendered DOM -- not just serialized state.
|
||||||
|
expect(harness.container.textContent).toContain('FlowStack');
|
||||||
|
expect(harness.container.textContent).toContain('Features');
|
||||||
|
expect(harness.container.textContent).toContain('Start Free');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('FlowStack');
|
||||||
|
expect(html).toContain('Features');
|
||||||
|
expect(html).toContain('Start Free');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the footer keeps its nested copyright/tagline content -- both in the real DOM and in export', () => {
|
||||||
|
harness = renderEditorHarness({ initialState: EMPTY_FOOTER_ROOT, frameTag: 'footer' });
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, tpl.footer.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('FlowStack, Inc.');
|
||||||
|
expect(harness.container.textContent).toContain('Ship products faster');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('FlowStack, Inc.');
|
||||||
|
expect(html).toContain('Ship products faster');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the home page keeps a Section-wrapped Heading\'s nested content -- both in the real DOM and in export', () => {
|
||||||
|
const homePage = tpl.pages[0];
|
||||||
|
const sectionComp = homePage.content.components.find((c: any) => c.type === 'Section');
|
||||||
|
expect(sectionComp).toBeDefined();
|
||||||
|
expect(sectionComp!.children?.length).toBeGreaterThan(0);
|
||||||
|
|
||||||
|
harness = renderEditorHarness(); // default empty 'div' root, like a regular page
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, [sectionComp]));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
expect(harness.container.textContent).toContain('Trusted by 10,000+ development teams');
|
||||||
|
|
||||||
|
const { html } = exportBodyHtml(harness.getSerialized());
|
||||||
|
expect(html).toContain('Trusted by 10,000+ development teams');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('loading the FULL home page (all components) keeps every top-level node\'s content -- no silent drops', () => {
|
||||||
|
const homePage = tpl.pages[0];
|
||||||
|
harness = renderEditorHarness();
|
||||||
|
|
||||||
|
expect(() => {
|
||||||
|
harness!.act(() => addTemplateComponents(harness!, homePage.content.components));
|
||||||
|
}).not.toThrow();
|
||||||
|
|
||||||
|
// ROOT should have exactly as many direct children as the template
|
||||||
|
// defines top-level page components -- if children got dropped, nested
|
||||||
|
// content wouldn't show up in ROOT's descendant count via serialize, but
|
||||||
|
// an easier, more direct regression signal is: every top-level
|
||||||
|
// component's OWN text ends up rendered somewhere on the canvas.
|
||||||
|
const serialized = JSON.parse(harness.getSerialized());
|
||||||
|
const totalNodeCount = Object.keys(serialized).length;
|
||||||
|
// A flat (children-dropped) tree would have exactly
|
||||||
|
// homePage.content.components.length + 1 (ROOT) nodes. The real template
|
||||||
|
// has nested children, so a correct load must produce MORE nodes than
|
||||||
|
// that -- this is the shape-level assertion the pre-existing mocked test
|
||||||
|
// could never make (it never touched a real tree).
|
||||||
|
expect(totalNodeCount).toBeGreaterThan(homePage.content.components.length + 1);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user