-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathslot-controller.ts
More file actions
238 lines (203 loc) · 7.32 KB
/
slot-controller.ts
File metadata and controls
238 lines (203 loc) · 7.32 KB
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
import type { ReactiveController, ReactiveElement } from 'lit';
interface AnonymousSlot {
hasContent: boolean;
elements: Element[];
slot: HTMLSlotElement | null;
}
interface NamedSlot extends AnonymousSlot {
name: string;
initialized: true;
}
export type Slot = NamedSlot | AnonymousSlot;
export type SlotName = string | null;
export interface SlotsConfig {
slots: SlotName[];
/**
* Object mapping new slot name keys to deprecated slot name values
* @example `pf-modal--header` is deprecated in favour of `header`
* ```js
* new SlotController(this, {
* slots: ['header'],
* deprecations: {
* 'header': 'pf-modal--header'
* }
* })
* ```
*/
deprecations?: Record<string, string>;
}
export type SlotControllerArgs = [SlotsConfig] | SlotName[];
export function isObjectSpread(config: SlotControllerArgs): config is [SlotsConfig] {
return config.length === 1 && typeof config[0] === 'object' && config[0] !== null;
}
/**
* If it's a named slot, return its children,
* for the default slot, look for direct children not assigned to a slot
* @param n slot name
*/
const isSlot =
<T extends Element = Element>(n: string | typeof SlotController.default) =>
(child: Element): child is T =>
n === SlotController.default ? !child.hasAttribute('slot')
: child.getAttribute('slot') === n;
export declare class SlotControllerPublicAPI implements ReactiveController {
static default: symbol;
public host: ReactiveElement;
constructor(host: ReactiveElement, ...args: SlotControllerArgs);
hostConnected?(): Promise<void>;
hostDisconnected?(): void;
hostUpdated?(): void;
/**
* Given a slot name or slot names, returns elements assigned to the requested slots as an array.
* If no value is provided, it returns all children not assigned to a slot (without a slot attribute).
* @param slotNames slots to query
* @example Get header-slotted elements
* ```js
* this.getSlotted('header')
* ```
* @example Get header- and footer-slotted elements
* ```js
* this.getSlotted('header', 'footer')
* ```
* @example Get default-slotted elements
* ```js
* this.getSlotted();
* ```
*/
getSlotted<T extends Element = Element>(...slotNames: string[]): T[];
/**
* Returns a boolean statement of whether or not any of those slots exists in the light DOM.
* @param names The slot names to check.
* @example this.hasSlotted('header');
*/
hasSlotted(...names: (string | null | undefined)[]): boolean;
/**
* Whether or not all the requested slots are empty.
* @param names The slot names to query. If no value is provided, it returns the default slot.
* @example this.isEmpty('header', 'footer');
* @example this.isEmpty();
* @returns
*/
isEmpty(...names: (string | null | undefined)[]): boolean;
}
export class SlotController implements SlotControllerPublicAPI {
public static default = Symbol('default slot') satisfies symbol as symbol;
/** @deprecated use `default` */
public static anonymous: symbol = this.default;
#nodes = new Map<string | typeof SlotController.default, Slot>();
#slotMapInitialized = false;
#slotNames: (string | null)[] = [];
#deprecations: Record<string, string> = {};
#mo = new MutationObserver(this.#initSlotMap.bind(this));
constructor(public host: ReactiveElement, ...args: SlotControllerArgs) {
this.#initialize(...args);
host.addController(this);
if (!this.#slotNames.length) {
this.#slotNames = [null];
}
}
#initialize(...config: SlotControllerArgs) {
if (isObjectSpread(config)) {
const [{ slots, deprecations }] = config;
this.#slotNames = slots;
this.#deprecations = deprecations ?? {};
} else if (config.length >= 1) {
this.#slotNames = config;
this.#deprecations = {};
}
}
async hostConnected(): Promise<void> {
this.#mo.observe(this.host, { childList: true });
// Map the defined slots into an object that is easier to query
this.#nodes.clear();
this.#initSlotMap();
// insurance for framework integrations
await this.host.updateComplete;
this.host.requestUpdate();
}
hostUpdated(): void {
if (!this.#slotMapInitialized) {
this.#initSlotMap();
}
}
hostDisconnected(): void {
this.#mo.disconnect();
}
#initSlotMap() {
// Loop over the properties provided by the schema
for (const slotName of this.#slotNames
.concat(Object.values(this.#deprecations))) {
const slotId = slotName || SlotController.default;
const name = slotName ?? '';
const elements = this.#getChildrenForSlot(slotId);
const slot = this.#getSlotElement(slotId);
const hasContent =
!!elements.length || !!slot?.assignedNodes?.()?.filter(x => x.textContent?.trim()).length;
this.#nodes.set(slotId, { elements, name, hasContent, slot });
}
this.host.requestUpdate();
this.#slotMapInitialized = true;
}
#getSlotElement(slotId: string | symbol) {
const selector =
slotId === SlotController.default ? 'slot:not([name])' : `slot[name="${slotId as string}"]`;
return this.host.shadowRoot?.querySelector?.<HTMLSlotElement>(selector) ?? null;
}
#getChildrenForSlot<T extends Element = Element>(
name: string | typeof SlotController.default,
): T[] {
if (this.#nodes.has(name)) {
return (this.#nodes.get(name)!.slot?.assignedElements?.() ?? []) as T[];
} else {
const children = Array.from(this.host.children) as T[];
return children.filter(isSlot(name));
}
}
/**
* Given a slot name or slot names, returns elements assigned to the requested slots as an array.
* If no value is provided, it returns all children not assigned to a slot (without a slot attribute).
* @param slotNames slots to query
* @example Get header-slotted elements
* ```js
* this.getSlotted('header')
* ```
* @example Get header- and footer-slotted elements
* ```js
* this.getSlotted('header', 'footer')
* ```
* @example Get default-slotted elements
* ```js
* this.getSlotted();
* ```
*/
getSlotted<T extends Element = Element>(...slotNames: string[]): T[] {
if (!slotNames.length) {
return (this.#nodes.get(SlotController.default)?.elements ?? []) as T[];
} else {
return slotNames.flatMap(slotName =>
this.#nodes.get(slotName)?.elements ?? []) as T[];
}
}
/**
* Returns a boolean statement of whether or not any of those slots exists in the light DOM.
* @param names The slot names to check.
* @example this.hasSlotted('header');
*/
hasSlotted(...names: (string | null | undefined)[]): boolean {
const slotNames = Array.from(names, x => x == null ? SlotController.default : x);
if (!slotNames.length) {
slotNames.push(SlotController.default);
}
return slotNames.some(x => this.#nodes.get(x)?.hasContent ?? false);
}
/**
* Whether or not all the requested slots are empty.
* @param names The slot names to query. If no value is provided, it returns the default slot.
* @example this.isEmpty('header', 'footer');
* @example this.isEmpty();
* @returns
*/
isEmpty(...names: (string | null | undefined)[]): boolean {
return !this.hasSlotted(...names);
}
}