summaryrefslogtreecommitdiff
path: root/preact/test/ts/custom-elements.tsx
blob: 0f8d29e7b182cdb5251a5c6b603d8a4c32cf507d (plain)
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
import { createElement, Component, createContext } from '../../';

declare module '../../' {
	namespace createElement.JSX {
		interface IntrinsicElements {
			// Custom element can use JSX EventHandler definitions
			'clickable-ce': {
				optionalAttr?: string;
				onClick?: MouseEventHandler<HTMLElement>;
			};

			// Custom Element that extends HTML attributes
			'color-picker': HTMLAttributes & {
				// Required attribute
				space: 'rgb' | 'hsl' | 'hsv';
				// Optional attribute
				alpha?: boolean;
			};

			// Custom Element with custom interface definition
			'custom-whatever': WhateveElAttributes;
		}
	}
}

// Whatever Element definition

interface WhateverElement {
	instanceProp: string;
}

interface WhateverElementEvent {
	eventProp: number;
}

// preact.JSX.HTMLAttributes also appears to work here but for consistency,
// let's use createElement.JSX
interface WhateveElAttributes extends createElement.JSX.HTMLAttributes {
	someattribute?: string;
	onsomeevent?: (this: WhateverElement, ev: WhateverElementEvent) => void;
}

// Ensure context still works
const { Provider, Consumer } = createContext({ contextValue: '' });

// Sample component that uses custom elements

class SimpleComponent extends Component {
	componentProp = 'componentProp';
	render() {
		// Render inside div to ensure standard JSX elements still work
		return (
			<Provider value={{ contextValue: 'value' }}>
				<div>
					<clickable-ce
						onClick={e => {
							// `this` should be instance of SimpleComponent since this is an
							// arrow function
							console.log(this.componentProp);

							// Validate `currentTarget` is HTMLElement
							console.log('clicked ', e.currentTarget.style.display);
						}}
					></clickable-ce>
					<color-picker space="rgb" dir="rtl"></color-picker>
					<custom-whatever
						dir="auto" // Inherited prop from HTMLAttributes
						someattribute="string"
						onsomeevent={function(e) {
							// Validate `this` and `e` are the right type
							console.log('clicked', this.instanceProp, e.eventProp);
						}}
					></custom-whatever>

					{/* Ensure context still works */}
					<Consumer>
						{({ contextValue }) => contextValue.toLowerCase()}
					</Consumer>
				</div>
			</Provider>
		);
	}
}

const component = <SimpleComponent />;