utils.test.ts
This file
Path
src/jsx/utils.test.ts
366 lines · 11.9 KiB · TypeScript
Last changed by
fix(jsx): add px to numeric gridGap, gridRowGap and gridColumnGap (#5487)Rup Sarmahbefore adoptione5bb206
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–207why, one step back1import {2 isValidAttributeName,3 isValidTagName,4 normalizeIntrinsicElementKey,5 styleObjectForEach,6} from './utils'78describe('normalizeIntrinsicElementKey', () => {9 test.each`10 key | expected11 ${'className'} | ${'class'}12 ${'htmlFor'} | ${'for'}13 ${'crossOrigin'} | ${'crossorigin'}14 ${'httpEquiv'} | ${'http-equiv'}15 ${'itemProp'} | ${'itemprop'}16 ${'fetchPriority'} | ${'fetchpriority'}17 ${'noModule'} | ${'nomodule'}18 ${'formAction'} | ${'formaction'}19 ${'href'} | ${'href'}20 `('should convert $key to $expected', ({ key, expected }) => {21 expect(normalizeIntrinsicElementKey(key)).toBe(expected)22 })23})2425describe('isValidAttributeName', () => {26 test.each`27 name28 ${'class'}29 ${'id'}30 ${'href'}31 ${'data-foo'}32 ${'aria-label'}33 ${'onclick'}34 ${'viewBox'}35 ${'xml:lang'}36 `('should return true for valid name "$name"', ({ name }) => {37 expect(isValidAttributeName(name)).toBe(true)38 })3940 test.each`41 name | description42 ${''} | ${'empty string'}43 ${'" onfocus="alert(1)'} | ${'double quote'}44 ${"' onfocus='alert(1)"} | ${'single quote'}45 ${'foo<bar'} | ${'less than'}46 ${'"><script>alert(1)</script>'} | ${'greater than'}47 ${'foo bar'} | ${'space'}48 ${'foo=bar'} | ${'equals sign'}49 ${'foo/bar'} | ${'slash'}50 ${'foo\\bar'} | ${'backslash'}51 ${'foo`bar'} | ${'backtick'}52 ${'a\x00b'} | ${'null byte'}53 ${'a\x1fb'} | ${'control character'}54 ${'a\x7fb'} | ${'DEL character'}55 `('should return false for "$description"', ({ name }) => {56 expect(isValidAttributeName(name)).toBe(false)57 })5859 test.each`60 name | description61 ${'xlink:href'} | ${'namespace separator'}62 ${'data.foo'} | ${'dot'}63 ${'data_foo'} | ${'underscore'}64 ${'é'} | ${'non-ascii'}65 `('should return true for valid "$description" names', ({ name }) => {66 expect(isValidAttributeName(name)).toBe(true)67 })6869 it('should keep validating names after the valid attribute name cache is reset', () => {70 for (let i = 0; i < 1025; i++) {71 expect(isValidAttributeName(`data-k${i}`)).toBe(true)72 }7374 expect(isValidAttributeName('class')).toBe(true)75 expect(isValidAttributeName('" onfocus="alert(1)')).toBe(false)76 })77})7879describe('isValidTagName', () => {80 test.each`81 name82 ${''}83 ${'div'}84 ${'h1'}85 ${'custom-element'}86 ${'clipPath'}87 ${'foo:bar'}88 ${'x.foo'}89 ${'x_bar'}90 ${'é'}91 `('should return true for valid tag name "$name"', ({ name }) => {92 expect(isValidTagName(name)).toBe(true)93 })9495 test.each`96 name | description97 ${'foo bar'} | ${'space'}98 ${'foo\nbar'} | ${'newline'}99 ${'" onfocus="alert(1)'} | ${'double quote'}100 ${"' onfocus='alert(1)"} | ${'single quote'}101 ${'foo<bar'} | ${'less than'}102 ${'"><script>alert(1)</script>'} | ${'greater than'}103 ${'foo=bar'} | ${'equals sign'}104 ${'foo/bar'} | ${'slash'}105 ${'foo\\bar'} | ${'backslash'}106 ${'foo`bar'} | ${'backtick'}107 ${'a\x00b'} | ${'null byte'}108 ${'a\x1fb'} | ${'control character'}109 ${'a\x7fb'} | ${'DEL character'}110 ${'!'} | ${'single bang'}111 ${'!--'} | ${'parser-control bang prefix'}112 ${'!DOCTYPE'} | ${'doctype-like name'}113 ${'?'} | ${'single question mark'}114 ${'?xml'} | ${'processing instruction'}115 `('should return false for "$description"', ({ name }) => {116 expect(isValidTagName(name)).toBe(false)117 })118119 it('should keep validating names after the valid tag name cache is reset', () => {120 for (let i = 0; i < 257; i++) {121 expect(isValidTagName(`custom-${i}`)).toBe(true)122 }123124 expect(isValidTagName('div')).toBe(true)125 expect(isValidTagName('div onmouseover="alert(1)"')).toBe(false)126 })127})128129describe('styleObjectForEach', () => {130 describe('Should output the number as it is, when a number type is passed', () => {131 test.each`132 property133 ${'animationIterationCount'}134 ${'aspectRatio'}135 ${'borderImageOutset'}136 ${'borderImageSlice'}137 ${'borderImageWidth'}138 ${'columnCount'}139 ${'columns'}140 ${'flex'}141 ${'flexGrow'}142 ${'flexPositive'}143 ${'flexShrink'}144 ${'flexNegative'}145 ${'flexOrder'}146 ${'gridArea'}147 ${'gridRow'}148 ${'gridRowEnd'}149 ${'gridRowSpan'}150 ${'gridRowStart'}151 ${'gridColumn'}152 ${'gridColumnEnd'}153 ${'gridColumnSpan'}154 ${'gridColumnStart'}155 ${'fontWeight'}156 ${'lineClamp'}157 ${'lineHeight'}158 ${'opacity'}159 ${'order'}160 ${'orphans'}161 ${'scale'}162 ${'tabSize'}163 ${'widows'}164 ${'zIndex'}165 ${'zoom'}166 ${'fillOpacity'}167 ${'floodOpacity'}168 ${'stopOpacity'}169 ${'strokeDasharray'}170 ${'strokeDashoffset'}171 ${'strokeMiterlimit'}172 ${'strokeOpacity'}173 ${'strokeWidth'}174 `('$property', ({ property }) => {175 const fn = vi.fn()176 styleObjectForEach({ [property]: 1 }, fn)177 expect(fn).toBeCalledWith(178 property.replace(/[A-Z]/g, (m: string) => `-${m.toLowerCase()}`),179 '1'180 )181 })182 })183 describe('Should output with px suffix, when a number type is passed', () => {184 test.each`185 property186 ${'borderBottomWidth'}187 ${'borderLeftWidth'}188 ${'borderRightWidth'}189 ${'borderTopWidth'}190 ${'borderWidth'}191 ${'bottom'}192 ${'fontSize'}193 ${'height'}194 ${'left'}195 ${'margin'}196 ${'marginBottom'}197 ${'marginLeft'}198 ${'marginRight'}199 ${'marginTop'}200 ${'padding'}201 ${'paddingBottom'}202 ${'paddingLeft'}203 ${'paddingRight'}204 ${'paddingTop'}205 ${'right'}206 ${'top'}207 ${'width'}fix(jsx): add px to numeric gridGap, gridRowGap and gridColumnGap (#5487)Rup Sarmahbefore adoptione5bb206
lines 208–210why, one step back208 ${'gridGap'}209 ${'gridRowGap'}210 ${'gridColumnGap'}Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 211–366why, one step back211 `('$property', ({ property }) => {212 const fn = vi.fn()213 styleObjectForEach({ [property]: 1 }, fn)214 expect(fn).toBeCalledWith(215 property.replace(/[A-Z]/g, (m: string) => `-${m.toLowerCase()}`),216 '1px'217 )218 })219 })220221 describe('Should skip values containing ";" to prevent CSS injection', () => {222 it('skips a value with ";"', () => {223 const fn = vi.fn()224 styleObjectForEach({ color: 'red;background:blue' }, fn)225 expect(fn).not.toBeCalled()226 })227228 it('keeps safe siblings while skipping unsafe ones', () => {229 const fn = vi.fn()230 styleObjectForEach({ color: 'red;background:blue', backgroundColor: 'white' }, fn)231 expect(fn).toBeCalledTimes(1)232 expect(fn).toBeCalledWith('background-color', 'white')233 })234235 it('does not throw for unsafe values', () => {236 expect(() => styleObjectForEach({ color: 'a;b' }, () => {})).not.toThrow()237 })238239 it('keeps semicolons inside quoted strings', () => {240 const fn = vi.fn()241 styleObjectForEach({ fontFamily: '"a;b", sans-serif' }, fn)242 expect(fn).toBeCalledWith('font-family', '"a;b", sans-serif')243 })244245 test.each([246 ['LF', '\n'],247 ['CR', '\r'],248 ['FF', '\f'],249 ])('skips quoted strings that contain %s before a declaration separator', (_, newline) => {250 const fn = vi.fn()251 styleObjectForEach(252 { fontFamily: `"${newline};background:url(https://example.com/a.png)` },253 fn254 )255 expect(fn).not.toBeCalled()256 })257258 it('keeps semicolons inside CSS functions', () => {259 const fn = vi.fn()260 styleObjectForEach({ backgroundImage: 'url("data:image/svg+xml;utf8,<svg></svg>")' }, fn)261 expect(fn).toBeCalledWith('background-image', 'url("data:image/svg+xml;utf8,<svg></svg>")')262 })263264 test.each([['square brackets', 'red[;background:blue]']])(265 'keeps semicolons inside CSS simple blocks with %s',266 (_, value) => {267 const fn = vi.fn()268 styleObjectForEach({ color: value }, fn)269 expect(fn).toBeCalledWith('color', value)270 }271 )272273 test.each([274 ['opening curly block', 'red{;background:blue}'],275 ['closing curly block', 'red};background:blue'],276 ])('skips CSS values containing %s', (_, value) => {277 const fn = vi.fn()278 styleObjectForEach({ color: value, backgroundColor: 'white' }, fn)279 expect(fn).toBeCalledTimes(1)280 expect(fn).toBeCalledWith('background-color', 'white')281 })282283 test.each([284 ['square brackets', 'red[;background:blue];position:fixed'],285 ['curly braces', 'red{;background:blue};position:fixed'],286 ])('skips top-level semicolons after CSS simple blocks with %s', (_, value) => {287 const fn = vi.fn()288 styleObjectForEach({ color: value }, fn)289 expect(fn).not.toBeCalled()290 })291292 it('skips top-level semicolons after CSS comments', () => {293 const fn = vi.fn()294 styleObjectForEach({ color: 'red/*(*/;background:blue;position:fixed;top:0' }, fn)295 expect(fn).not.toBeCalled()296 })297298 test.each([299 ['comment', 'red/*'],300 ['double-quoted string', '"abc'],301 ['single-quoted string', "'abc"],302 ['function block', 'red('],303 ['square block', 'red['],304 ['curly block', 'red{'],305 ['unmatched function closer', 'red)'],306 ['unmatched square closer', 'red]'],307 ['unmatched curly closer', 'red}'],308 ['mismatched simple block closer', 'red[)'],309 ['escape', 'red\\'],310 ])('skips unterminated CSS %s that can swallow following declarations', (_, value) => {311 const fn = vi.fn()312 styleObjectForEach({ color: value, display: 'none' }, fn)313 expect(fn).toBeCalledTimes(1)314 expect(fn).toBeCalledWith('display', 'none')315 })316317 test.each([318 ['comment that closes exactly at end of value', 'red/* hi */'],319 ['CSS hex escape that decodes to a delimiter byte', 'red\\3b '],320 ['vertical tab inside a quoted string', '"\vfoo"'],321 ['trailing solidus that is not a comment start', 'a/'],322 ])('keeps CSS-safe edge case — %s', (_, value) => {323 const fn = vi.fn()324 styleObjectForEach({ color: value }, fn)325 expect(fn).toBeCalledWith('color', value)326 })327328 it('skips style property names that can break declaration boundaries', () => {329 const fn = vi.fn()330 styleObjectForEach({ 'color;background-image': 'url(https://example.com/a.png)' }, fn)331 styleObjectForEach({ 'color:background': 'red' }, fn)332 expect(fn).not.toBeCalled()333 })334335 it('keeps safe property names that use digits', () => {336 const fn = vi.fn()337 styleObjectForEach({ '--my-var-1': '15px', '--myVar-2': '20px' }, fn)338 expect(fn).toHaveBeenNthCalledWith(1, '--my-var-1', '15px')339 expect(fn).toHaveBeenNthCalledWith(2, '--myVar-2', '20px')340 })341342 it('keeps vendor-prefixed property names', () => {343 const fn = vi.fn()344 styleObjectForEach({ WebkitLineClamp: '2' }, fn)345 expect(fn).toBeCalledWith('-webkit-line-clamp', '2')346 })347348 it('keeps validating style property names after the valid style property name cache is reset', () => {349 for (let i = 0; i < 1025; i++) {350 styleObjectForEach({ [`--cache-${i}`]: '1px' }, () => {})351 }352353 const fn = vi.fn()354 styleObjectForEach({ '--after-reset-1': '2px', 'color:background': 'red' }, fn)355 expect(fn).toBeCalledTimes(1)356 expect(fn).toBeCalledWith('--after-reset-1', '2px')357 })358359 it('skips unsupported runtime values without throwing', () => {360 const fn = vi.fn()361 expect(() => styleObjectForEach({ color: false, backgroundColor: 'white' }, fn)).not.toThrow()362 expect(fn).toBeCalledTimes(1)363 expect(fn).toBeCalledWith('background-color', 'white')364 })365 })366})