-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
index.tsx
1188 lines (1014 loc) · 30.9 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as ReactDOMServer from 'react-dom/server';
import styled, {
css,
createGlobalStyle,
isStyledComponent,
keyframes,
ServerStyleSheet,
StyleSheetManager,
ThemeProps,
ThemeProvider,
withTheme,
ThemeConsumer,
StyledComponent,
ThemedStyledComponentsModule,
FlattenSimpleInterpolation,
SimpleInterpolation,
FlattenInterpolation,
} from 'styled-components';
import {} from 'styled-components/cssprop';
/**
* general usage
*/
// Create a <Title> react component that renders an <h1> which is
// centered, palevioletred and sized at 1.5em
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a <Wrapper> react component that renders a <section> with
// some padding and a papayawhip background
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
const Input = styled.input`
font-size: 1.25em;
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
&:hover {
box-shadow: inset 1px 1px 2px rgba(0, 0, 0, 0.1);
}
`;
interface MyTheme {
primary: string;
}
interface ButtonProps {
name: string;
primary?: boolean;
theme: MyTheme;
}
class MyButton extends React.Component<ButtonProps> {
render() {
return <button>Custom button</button>;
}
}
const TomatoButton = styled(MyButton)`
color: tomato;
border-color: tomato;
`;
const CustomizableButton = styled(MyButton)`
/* Adapt the colors based on primary prop */
background: ${props => (props.primary ? 'palevioletred' : 'white')};
color: ${props => (props.primary ? 'white' : 'palevioletred')};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid ${props => props.theme.primary};
border-radius: 3px;
`;
const example = css`
font-size: 1.5em;
text-align: center;
color: ${props => props.theme.primary};
border-color: ${'red'};
`;
const fadeIn = keyframes`
0% {
opacity: 0;
}
100% {
opacity: 1;
}
`;
const showAnimation = css`
opacity: 1;
transform: scale(1) translateY(0);
`;
const hideAnimation = css`
opacity: 0;
transform: scale(0.95, 0.8) translateY(20px);
`;
const entryAnimation = keyframes`
from { ${hideAnimation} }
to { ${showAnimation} }
`;
const animationRule = css`
${fadeIn} 1s infinite alternate;
`;
const ComponentWithKeyframe = styled.div`
animation: ${animationRule};
`;
const theme = {
main: 'mediumseagreen',
};
const ExampleGlobalStyle = createGlobalStyle`
@font-face {
font-family: 'Operator Mono';
src: url('../fonts/Operator-Mono.ttf');
}
body {
margin: 0;
}
`;
class Example extends React.Component {
render() {
return (
<ThemeProvider theme={theme}>
<>
<ExampleGlobalStyle />
<Wrapper>
<Title>Hello World, this is my first styled component!</Title>
<Input placeholder="@mxstbr" type="text" />
<TomatoButton name="demo" />
</Wrapper>
</>
</ThemeProvider>
);
}
}
// css which only uses simple interpolations without functions
const cssWithValues1 = css`
font-size: ${14} ${'pt'};
`;
// css which uses other simple interpolations without functions
const cssWithValues2 = css`
${cssWithValues1}
${[cssWithValues1, cssWithValues1]}
font-weight: ${'bold'};
`;
// css which uses function interpolations with common props
const cssWithFunc1 = css`
font-size: ${props => props.theme.fontSizePt}pt;
`;
const cssWithFunc2 = css`
${cssWithFunc1}
${props => cssWithFunc1}
${[cssWithFunc1, cssWithValues1]}
`;
// such css can be used in styled components
const styledButton = styled.button`
${cssWithValues1} ${[cssWithValues1, cssWithValues2]}
${cssWithFunc1} ${[cssWithFunc1, cssWithFunc2]}
${() => [cssWithFunc1, cssWithFunc2]}
`;
const name = 'hey';
const ThemedMyButton = withTheme(MyButton);
<ThemedMyButton name={name} />;
/**
* nested styles
*/
const Link = styled.a`
color: red;
`;
const AlternativeLink = styled.a`
color: blue;
`;
const freeStyles = css`
background-color: black;
color: white;
${Link} {
color: blue;
}
`;
const Article = styled.section`
color: red;
${freeStyles}
& > ${Link} {
color: green;
}
${p => (p.theme.useAlternativeLink ? AlternativeLink : Link)} {
color: black;
}
`;
// A Link instance should be backed by an HTMLAnchorElement
const ComposedLink = () => <Link onClick={(e: React.MouseEvent<HTMLAnchorElement>) => undefined} />;
/**
* construction via string tag
*/
// Create a <LinkFromString> react component that renders an <a> which is
// centered, palevioletred and sized at 1.5em
const LinkFromString = styled('a')`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// A LinkFromString instance should be backed by an HTMLAnchorElement
const MyOtherComponent = () => <LinkFromString onClick={(e: React.MouseEvent<HTMLAnchorElement>) => undefined} />;
// Create a <LinkFromStringWithProps> react component that renders an <a>
// which takes extra props
interface LinkProps {
canClick: boolean;
}
const LinkFromStringWithProps = styled('a')`
font-size: 1.5em;
text-align: center;
color: ${(a: LinkProps) => (a.canClick ? 'palevioletred' : 'gray')};
`;
// A LinkFromStringWithProps instance should be backed by an HTMLAnchorElement
const MyOtherComponentWithProps = () => (
<LinkFromStringWithProps canClick={false} onClick={(e: React.MouseEvent<HTMLAnchorElement>) => undefined} />
);
// Create a <LinkFromStringWithPropsAndGenerics> react component that renders an <a>
// which takes extra props passed as a generic type argument
const LinkFromStringWithPropsAndGenerics = styled('a')<LinkProps>`
font-size: 1.5em;
text-align: center;
color: ${a => (a.canClick ? 'palevioletred' : 'gray')};
`;
// A LinkFromStringWithPropsAndGenerics instance should be backed by an HTMLAnchorElement
const MyOtherComponentWithPropsAndGenerics = () => (
<LinkFromStringWithPropsAndGenerics
canClick={false}
onClick={(e: React.MouseEvent<HTMLAnchorElement>) => undefined}
/>
);
/**
* object styles
*/
interface ObjectStyleProps {
size: string;
}
const functionReturningStyleObject = (props: ObjectStyleProps) => ({
padding: props.size === 'big' ? '10px' : 2,
});
const ObjectStylesBox = styled.div`
${functionReturningStyleObject} ${{
backgroundColor: 'red',
// Supports nested objects (pseudo selectors, media queries, etc)
'@media screen and (min-width: 800px)': {
backgroundColor: 'blue',
},
fontSize: 2,
}};
`;
<ObjectStylesBox size="big" />;
/**
* attrs
*/
const AttrsInput = styled.input.attrs({
// we can define static props
type: 'password',
// or we can define dynamic ones
margin: (props: any) => (props.size as string) || '1em',
padding: (props: any) => (props.size as string) || '1em',
})`
color: palevioletred;
font-size: 1em;
border: 2px solid palevioletred;
border-radius: 3px;
/* here we use the dynamically computed props */
margin: ${props => props.margin};
padding: ${props => props.padding};
`;
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/30042
const AttrsWithOnlyNewProps = styled.h2.attrs({ as: 'h1' })`
color: ${props => (props.as === 'h1' ? 'red' : 'blue')};
font-size: ${props => (props.as === 'h1' ? 2 : 1)};
`;
const AttrsInputExtra = styled(AttrsInput).attrs({ autoComplete: 'off' })``;
<AttrsInputExtra />;
/**
* withConfig
*/
/**
* shouldForwardProp
*/
// $ExpectError
const WithConfig = styled('div').withConfig()`
color: red;
`;
styled('div').withConfig({})`
color: red;
`;
styled('div').withConfig<{ myProp: boolean }>({
shouldForwardProp: (prop, defaultValidatorFn) => prop === 'myProp',
})<{ otherProp: string }>`
color: red;
${p => {
// $ExpectType boolean
p.myProp;
return css``;
}}
${p => {
// $ExpectType string
p.otherProp;
return css``;
}}
`;
styled('input').withConfig({
shouldForwardProp: prop => prop === 'disabled',
})`
color: red;
`;
styled('div').withConfig({
shouldForwardProp: (prop, defaultValidatorFn) => ['filterThis'].indexOf(prop) !== -1,
})`
color: red;
`;
styled('div').withConfig({
shouldForwardProp: (prop, defaultValidatorFn) => defaultValidatorFn(prop),
})`
color: red;
`;
styled('div').withConfig<{ test: boolean }>({
// $ExpectError
shouldForwardProp: (prop, defaultValidatorFn) => prop === 'invalidProp' && true,
})`
color: red;
${p => p.test && css``}
${p => p.invalidProp && css``} // $ExpectError
`;
/**
* component type
*/
declare const A: React.ComponentClass;
declare const B: React.StatelessComponent;
declare const C: React.ComponentType;
styled(A); // succeeds
styled(B); // succeeds
styled(C); // used to fail; see issue trail linked below
// https://github.com/mui-org/material-ui/pull/8781#issuecomment-349460247
// https://github.com/mui-org/material-ui/issues/9838
// https://github.com/styled-components/styled-components/pull/1420
// https://github.com/Microsoft/TypeScript/issues/21175
// https://github.com/styled-components/styled-components/pull/1427
/**
* function themes
*/
// Define our button, but with the use of props.theme this time
const ThemedButton = styled.button`
color: ${props => props.theme.fg};
border: 2px solid ${props => props.theme.fg};
background: ${props => props.theme.bg};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
`;
// Define our `fg` and `bg` on the theme
const theme2 = {
fg: 'palevioletred',
bg: 'white',
};
// This theme swaps `fg` and `bg`
const invertTheme = ({ fg, bg }: { fg: string; bg: string }) => ({
fg: bg,
bg: fg,
});
const MyApp = (
<ThemeProvider theme={theme2}>
<div>
<ThemedButton>Default Theme</ThemedButton>
<ThemeProvider theme={invertTheme}>
<ThemedButton>Inverted Theme</ThemedButton>
</ThemeProvider>
</div>
</ThemeProvider>
);
/**
* withTheme HOC
*/
class MyComponent extends React.Component<ThemeProps<{}>> {
render() {
const { theme } = this.props;
console.log('Current theme: ', theme);
return <h1>Hello</h1>;
}
}
const ThemedMyComponent = withTheme(MyComponent);
<ThemedMyComponent
ref={ref => {
// $ExpectType MyComponent | null
ref;
}}
/>;
const themedRef = React.createRef<MyComponent>();
<ThemedMyComponent ref={themedRef} />;
interface WithThemeProps {
theme: {
color: string;
};
text: string;
}
const Component = (props: WithThemeProps) => <div style={{ color: props.theme.color }}>{props.text}</div>;
const ComponentWithTheme = withTheme(Component);
<ComponentWithTheme text={'hi'} />; // ok
<ComponentWithTheme text={'hi'} theme={{ color: 'red' }} />; // ok
<ThemeConsumer>{theme => <Component text="hi" theme={theme} />}</ThemeConsumer>;
/**
* isStyledComponent utility
*/
const StyledComponent = styled.h1``;
const StatelessComponent = () => <div />;
class ClassComponent extends React.Component {
render() {
return <div />;
}
}
isStyledComponent(StyledComponent);
isStyledComponent(StatelessComponent);
isStyledComponent(ClassComponent);
isStyledComponent('div');
/**
* server side rendering
*/
const SSRTitle = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
const sheet = new ServerStyleSheet();
const html = sheet.collectStyles(<SSRTitle>Hello world</SSRTitle>);
const styleHtml = sheet.getStyleTags();
const styleElement = sheet.getStyleElement();
sheet.seal();
const sheet2 = new ServerStyleSheet();
const element = (
<StyleSheetManager sheet={sheet2.instance} disableCSSOMInjection>
<SSRTitle>Hello world</SSRTitle>
</StyleSheetManager>
);
const css2 = sheet2.getStyleElement();
// Wrapping a node stream returned from renderToNodeStream with interleaveWithNodeStream
const sheet3 = new ServerStyleSheet();
const appStream = ReactDOMServer.renderToNodeStream(<Title>Hello world</Title>);
const wrappedCssStream: NodeJS.ReadableStream = sheet3.interleaveWithNodeStream(appStream);
/**
* StyledComponent.withComponent
*/
const WithComponentH1 = styled.h1`
color: palevioletred;
font-size: 1em;
`;
function getRandomInt(min: number, max: number) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
class Random extends React.Component<any, any> {
render() {
const i = getRandomInt(1, 6);
switch (i) {
case 1:
return <h1>Hello World</h1>;
case 2:
return <h2>Hello World</h2>;
case 3:
return <h3>Hello World</h3>;
case 4:
return <h4>Hello World</h4>;
case 5:
return <h5>Hello World</h5>;
case 6:
return <h6>Hello World</h6>;
default:
return null;
}
}
}
const WithComponentH2 = WithComponentH1.withComponent('h2');
const WithComponentAbbr = WithComponentH1.withComponent('abbr');
const WithComponentAnchor = WithComponentH1.withComponent('a');
const AnchorContainer = () => (
<WithComponentAnchor href="https://example.com">withComponent Anchor</WithComponentAnchor>
);
const WithComponentRandomHeading = WithComponentH1.withComponent(Random);
const WithComponentCompA: React.SFC<{ a: number; className?: string }> = ({ className }) => (
<div className={className} />
);
const WithComponentCompB: React.SFC<{ b: number; className?: string }> = ({ className }) => (
<div className={className} />
);
const WithComponentStyledA = styled(WithComponentCompA)`
color: ${(props: { color: string }) => props.color};
`;
const WithComponentFirstStyledA = styled(WithComponentStyledA).attrs({
a: 1,
})``;
const WithComponentFirstStyledB = WithComponentFirstStyledA.withComponent(WithComponentCompB);
const WithComponentFirstStyledANew = styled(WithComponentStyledA).attrs(props => ({ a: 1 }))``;
const test = () => [
<WithComponentFirstStyledA color={'black'} />,
<WithComponentFirstStyledB b={2} color={'black'} />,
<WithComponentFirstStyledANew color={'black'} />,
];
const WithComponentRequired = styled((props: { to: string }) => <a href={props.to} />)``;
// These tests pass in tsservice, but they fail in dtslint. I do not know why.
// <WithComponentRequired href=''/>; // $ExpectError
// <WithComponentRequired to=''/>;
const WithComponentRequired2 = WithComponentRequired.withComponent('a');
// These tests pass in tsservice, but they fail in dtslint. I do not know why.
// <WithComponentRequired2 href=''/>;
// <WithComponentRequired2 to=''/>; // $ExpectError
// 4.0 With Component
const asTest = (
<>
<WithComponentH1 as="h2" />
<WithComponentH1 as={WithComponentH2} />
</>
);
const ForwardedAsNestedComponent = styled.div``;
const ForwardedAsComponent = styled(ForwardedAsNestedComponent)``;
const forwardedAsTest = (
<>
<ForwardedAsComponent forwardedAs="h2" />
<ForwardedAsComponent forwardedAs={WithComponentH2} />
</>
);
interface ExternalAsComponentProps {
as?: string | React.ComponentType<any>;
type: 'primitive' | 'complex';
}
const ExternalAsComponent: React.FC<ExternalAsComponentProps> = () => null;
const WrappedExternalAsComponent = styled(ExternalAsComponent)``;
const ForwardedAsWithWrappedExternalTest = (
<>
<WrappedExternalAsComponent forwardedAs="h2" type="primitive" />
<WrappedExternalAsComponent forwardedAs={WithComponentH2} type="complex" />
</>
);
const ForwardedAsWithNestedAsExternalTest = (
<>
<ForwardedAsNestedComponent as={ExternalAsComponent} forwardedAs="h2" type="primitive" />
<ForwardedAsNestedComponent as={ExternalAsComponent} forwardedAs={WithComponentH2} type="complex" />
</>
);
interface TestContainerProps {
size: 'big' | 'small';
test?: boolean;
}
const TestContainer = ({ size, test }: TestContainerProps) => {
return null;
};
const StyledTestContainer = styled(TestContainer)`
background: red;
`;
interface Test2ContainerProps {
type: 'foo' | 'bar';
}
class Test2Container extends React.Component<Test2ContainerProps> {
render() {
return null;
}
}
const containerTest = <StyledTestContainer as={Test2Container} type="foo" />;
// 4.0 refs
const divFnRef = (ref: HTMLDivElement | null) => {
/* empty */
};
const divRef = React.createRef<HTMLDivElement>();
const StyledDiv = styled.div``;
<StyledDiv ref={divRef} />;
<StyledDiv ref={divFnRef} />;
<StyledDiv ref="string" />; // $ExpectError
const StyledStyledDiv = styled(StyledDiv)``;
<StyledStyledDiv ref={divRef} />;
<StyledStyledDiv ref={divFnRef} />;
<StyledStyledDiv ref="string" />; // $ExpectError
const StyledA = StyledDiv.withComponent('a');
// No longer generating a type error as of Feb. 6th, 2019
// <StyledA ref={divRef} />; // $ExpectError
<StyledA
ref={ref => {
// $ExpectType HTMLAnchorElement | null
ref;
}}
/>;
async function typedThemes() {
const theme = {
color: 'green',
};
// abuse "await import(...)" to be able to reference the styled-components namespace
// without actually doing a top level namespace import
const { default: styled, css, createGlobalStyle, ThemeProvider, ThemeConsumer } = ((await import(
'styled-components'
)) as any) as ThemedStyledComponentsModule<typeof theme>;
const ThemedDiv = styled.div`
background: ${props => {
// $ExpectType string
props.theme.color;
// $ExpectType number | undefined
props.tabIndex;
return props.theme.color;
}};
`;
const ThemedDiv2 = styled.div(props => {
// $ExpectType string
props.theme.color;
// $ExpectType number | undefined
props.tabIndex;
return {
background: props.theme.color,
};
});
const ThemedDiv3 = styled.div(props => {
// $ExpectType string
props.theme.color;
// $ExpectType number | undefined
props.tabIndex;
return css`
background: ${props.theme.color};
`;
});
const themedCss = css`
background: ${props => {
// $ExpectType string
props.theme.color;
// $ExpectType "theme"
type Keys = keyof typeof props;
return props.theme.color;
}};
`;
// can't use a FlattenInterpolation as the first argument, would make broken css
// $ExpectError
const ThemedDiv4 = styled.div(themedCss);
const themedCssWithNesting = css(props => ({
color: props.theme.color,
[ThemedDiv3]: {
color: 'green',
},
}));
const Global = createGlobalStyle`
${themedCssWithNesting}
`;
const WithProp = styled.div`
${({ ok, theme: { color } }: { ok: boolean; theme: typeof theme }) =>
ok &&
css`
color: ${color};
`}
`;
const WithPropNested = styled.div`
${({ ok }: { ok: boolean }) =>
ok &&
css`
color: ${({ theme: { color } }) => color};
`}
`;
return (
<ThemeProvider theme={theme}>
<>
<Global />
<ThemedDiv />
<ThemedDiv2 />
<ThemedDiv3 />
<ThemeConsumer>
{theme => {
// $ExpectType string
theme.color;
return theme.color;
}}
</ThemeConsumer>
<WithProp ok />
<WithPropNested ok />
</>
</ThemeProvider>
);
}
async function reexportCompatibility() {
const sc = await import('styled-components');
const themed = sc as ThemedStyledComponentsModule<any>;
let { ...scExports } = sc;
let { ...themedExports } = themed;
// both branches must be assignable to each other
if (Math.random()) {
scExports = themedExports;
} else {
themedExports = scExports;
}
}
async function themeAugmentation() {
interface BaseTheme {
background: string;
}
interface ExtraTheme extends BaseTheme {
accent: string;
}
const base = ((await import('styled-components')) as any) as ThemedStyledComponentsModule<BaseTheme>;
const extra = ((await import('styled-components')) as any) as ThemedStyledComponentsModule<ExtraTheme, BaseTheme>;
return (
<base.ThemeProvider
theme={{
background: 'black',
}}
>
<>
<extra.ThemeProvider
theme={base => base} // $ExpectError
>
<extra.ThemeConsumer>{() => null}</extra.ThemeConsumer>
</extra.ThemeProvider>
<extra.ThemeProvider
theme={base => ({
...base,
accent: 'blue',
})}
>
<extra.ThemeConsumer>{() => null}</extra.ThemeConsumer>
</extra.ThemeProvider>
</>
</base.ThemeProvider>
);
}
// NOTE: this is needed for some tests inside cssProp,
// but actually running this module augmentation will cause
// tests elsewhere to break, and there is no way to contain it.
// Uncomment out as needed to run tests.
// declare module "styled-components" {
// interface DefaultTheme {
// background: string;
// }
// }
function cssProp() {
function Custom(props: React.ComponentPropsWithoutRef<'div'>) {
return <div {...props} />;
}
const myCss = 'background: blue;';
return (
<>
<div css="background: blue;" />
<div css={{ background: 'blue' }} />
<div
// would be nice to be able to turn this into an error as it also crashes the plugin,
// but this is how optional properties work in TypeScript...
css={undefined}
/>
<div
// css used as tagged function is fine and is correctly handled by the plugin
css={css`
background: blue;
`}
/>
<div
// but this crashes the plugin, even though it's valid type-wise and we can't forbid it
css={css({ background: 'blue' })}
/>
<div
// this also crashes the plugin, only inline strings or css template tag work
css={myCss}
/>
<div
css={css`
background: ${() => 'blue'};
`}
/>
<div
css={css`
background: ${props => {
// This requires the DefaultTheme augmentation
// // $ExpectType string
// props.theme.background;
return props.theme.background;
}};
`}
/>
<Custom css="background: blue;" />
<Custom css={undefined} />
<Custom
css={css`
background: blue;
`}
/>
<Custom
css={css`
background: ${() => 'blue'};
`}
/>
<Custom
css={css`
background: ${props => {
// This requires the DefaultTheme augmentation
// // $ExpectType string
// props.theme.background;
return props.theme.background;
}};
`}
/>
</>
);
}
function validateArgumentsAndReturns() {
const t1: FlattenSimpleInterpolation[] = [
css({ color: 'blue' }),
css`
color: blue;
`,
css`
color: ${'blue'};
`,
];
const t4: FlattenInterpolation<any> = [
css`
color: ${() => 'blue'};
`,
css(() => ({ color: 'blue' })),
css(
() =>
css`
color: 'blue';
`,
),
];
// if the first argument is array-like it's always treated as a string[], this breaks things
css(
// $ExpectError
css`
${{ color: 'blue' }}
`,
);
// _technically_ valid as styled-components doesn't look at .raw but best not to support it
// $ExpectError
css([]);
styled.div({ color: 'blue' });
styled.div(props => ({ color: props.theme.color }));
styled.div`
color: ${'blue'};
`;
// These don't work for the same reason css doesn't work
styled.div(
// $ExpectError
css`
${{ color: 'blue' }}
`,
);
// $ExpectError
styled.div([]);
createGlobalStyle({
':root': {
color: 'blue',
},
});
createGlobalStyle`
:root {
color: blue;
}
`;