Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Controller: @phase2/outline-controller-slot-manager #389

Open
wants to merge 9 commits into
base: next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions packages/controllers/slot-manager/README.md
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add code examples for usage with ShadowDOM, LightDOM and how to handle a single unnamed (default) slot.

Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Slot Manager

The `SlotManager` is a reactive controller that allows cloning slots into the shadow DOM of a component. It provides methods for managing slots, adding annotations, and dispatching events from cloned slots in the shadow DOM to the equivalent slots in the light DOM.

## Installation

To use the `SlotManager`, you need to install the required dependencies:

```bash
yarn add -D @phase2/slot-manager
```

## Usage

Import the `SlotManager` and instantiate it in your component:

```javascript
import { SlotManager } from './slot-manager';

class MyComponent extends LitElement {
constructor() {
super();
const SlotManager = new SlotManager(this);
// ... @todo Add more usage examples
// default slot example
// slot exist function
// renderInShadow example
// conditionalSlot example
}
}
```
himerus marked this conversation as resolved.
Show resolved Hide resolved

## API

### SlotManager(host: ReactiveControllerHost & HTMLElement)

Creates a new instance of the `SlotManager` for the given host element.

- `host`: The host element that will be controlled by the `SlotManager`.

#### Methods

##### getSlottedNodes(slotName?: string | null): Array<Node>

Returns an array of slotted nodes for the specified slot name.

- `slotName`: The name of the slot. If not provided, returns the default slot nodes.

##### exist(slotName?: string | null): boolean

Checks if a slot exists.

- `slotName`: The name of the slot. If not provided, checks for the default slot.

##### addAnnotations(slotName: string, lightDomSlot: ChildNode): HTMLElement

Adds annotations to a slot, such as cloned-slot attributes and comments in the light DOM.

- `slotName`: The name of the slot.
- `lightDomSlot`: The light DOM slot to annotate.

##### dispatchEventsToLightDom(eventsToDispatch: string[], clonedSlot: HTMLElement): void

Dispatches events from cloned slots in the shadow DOM to the equivalent slots in the light DOM.

- `eventsToDispatch`: An array of event types to dispatch.
- `clonedSlot`: The cloned slot in the shadow DOM.

##### renderInShadow(slotName?: string, wrapperElement?: string | null, eventsToDispatch?: string[], addAnnotations?: boolean): Array<HTMLElement> | null

Renders the specified slot in the shadow DOM.

- `slotName`: The name of the slot. If not provided, renders the default slot.
- `wrapperElement`: Optional wrapper element for each slot.
- `eventsToDispatch`: An array of event types to dispatch from the cloned slots.
- `addAnnotations`: Whether to add annotations to the slot. Defaults to `true`.

##### conditionalSlot(slotName: string, renderInShadow?: boolean, extraClasses?: string | null, extraAttributes?: { name: string, value: string }[]): TemplateResult | null

Conditionally renders a slot with a wrapper and additional classes.

- `slotName`: The name of the slot.
- `renderInShadow`: Whether to render the slot in the shadow DOM. Defaults to `true`.
- `extraClasses`: Additional classes to add to the wrapper element. Defaults to `null`.
- `extraAttributes`: Additional attributes to add to the wrapper element. Defaults to an empty array.
1 change: 1 addition & 0 deletions packages/controllers/slot-manager/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { SlotManager } from './src/slot-manager';
42 changes: 42 additions & 0 deletions packages/controllers/slot-manager/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@phase2/outline-controller-slot-manager",
"version": "0.0.1",
"description": "Controller to help with slots (renderInShadow, exist, etc.)",
"keywords": [
"outline components",
"outline design",
"slots",
"shadow DOM"
],
"main": "index.ts",
"types": "index.ts",
"typings": "index.d.ts",
"files": [
"/dist/",
"/src/",
"!/dist/tsconfig.build.tsbuildinfo"
],
"author": "Phase2 Technology",
"repository": {
"type": "git",
"url": "https://github.com/phase2/outline.git",
"directory": "packages/controllers/slot-manager"
},
"license": "BSD-3-Clause",
"scripts": {
"build": "node ../../../scripts/build.js",
"package": "yarn publish"
},
"dependencies": {
"lit": "^2.3.1"
},
"devDependencies": {
"tslib": "^2.1.0"
},
"publishConfig": {
"access": "public"
},
"exports": {
".": "./index.ts"
}
}
122 changes: 122 additions & 0 deletions packages/controllers/slot-manager/src/slot-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { ReactiveControllerHost } from 'lit';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { html } from 'lit/static-html.js';

/**
* @typedef SlotName
* @type {string | null}
* @description A type for slot name.
*/
type SlotName = string | null;

/**
* @class SlotManager
* @description The SlotManager ReactiveController.
* This controller allows cloning slots into the shadow DOM,
* by calling a function inside render() of the component.
* Any changes in the light DOM trigger requestUpdate() and thus re-cloning
* of the slots into the shadow DOM.
* The controller dispatches any events that were specified when they are triggered
* in the cloned slots in shadow DOM to the equivalent light DOM slot.
* @param {ReactiveControllerHost & Element} host - The host element.
*/
export class SlotManager {
host: ReactiveControllerHost & Element;

/**
* @constructor
* @description Store a reference to the host.
* @param {ReactiveControllerHost & Element} host - The host element.
*/
constructor(host: ReactiveControllerHost & Element) {
this.host = host;
}

/**
* @method getSlottedNodes
* @description Get slotted nodes by slot name.
* @param {SlotName} slotName - The name of the slot to search for. If null or empty string, the method will return the default slot nodes.
* @returns {Node[] | false} An array of slotted nodes if any are found, or `false` if no slotted nodes are found.
*/
getSlottedNodes(slotName: SlotName = null) {
const defaultSlot = slotName === '' || slotName === null;
let slottedNodes = [];

if (defaultSlot) {
slottedNodes = Array.from(this.host.childNodes).filter(
node => this.isDefaultSlotText(node) || this.isDefaultSlotElement(node)
);
} else {
slottedNodes = Array.from(
this.host.querySelectorAll(`[slot=${slotName}]`)
);
}

if (slottedNodes.length) {
return slottedNodes;
} else {
return false;
}
}

/**
* @method doesSlotExist
* @description Check if a slot exists.
* @param {SlotName} slotName - The slot name to check for.
* @returns {boolean} True if the slot exists, false otherwise.
*/
doesSlotExist(slotName: SlotName = null) {
return Boolean(this.getSlottedNodes(slotName));
}

/**
* @method isDefaultSlotText
* @description Check if a node is a default slot text.
* @param {Node} node - The node to check.
* @returns {boolean} True if the node is a default slot text, false otherwise.
*/
isDefaultSlotText(node: Node) {
return node.nodeType === node.TEXT_NODE && node.textContent!.trim() !== '';
}

/**
* @method isDefaultSlotElement
* @description Check if a node is a default slot element.
* @param {Node} node - The node to check.
* @returns {boolean} True if the node is a default slot element, false otherwise.
*/
isDefaultSlotElement(node: Node) {
return (
node.nodeType === node.ELEMENT_NODE &&
(node as HTMLElement).getAttribute('slot') === null
);
}

/**
* @method conditionalSlot
* @description Conditionally render a slot with a wrapper and additional classes.
* @param {SlotName} slotName - The slot name.
* @param {string | null} [extraClasses=null] - Additional classes to add to the wrapper.
* @returns {TemplateResult | null} The rendered slot or null if the slot does not exist.
*/
conditionalSlot(
slotName: SlotName = null,
extraClasses: string | null = null
) {
const defaultSlot = slotName === '' || slotName === null;
const wrapperClasses = {
'slot-default': defaultSlot,
[`slot-${slotName}`]: !defaultSlot,
[`${extraClasses}`]: extraClasses !== null,
};

if (this.doesSlotExist(slotName)) {
return html`<div class="${classMap(wrapperClasses)}">
<slot name="${ifDefined(defaultSlot ? undefined : slotName)}"></slot>
</div>`;
} else {
return null;
}
}
}
9 changes: 9 additions & 0 deletions packages/controllers/slot-manager/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "./dist"
},
"include": ["index.ts", "src/**/*", "tests/**/*"],
"references": [{ "path": "../../outline-core/tsconfig.build.json" }]
}
Loading