Move spread directive to framework library

This commit is contained in:
Danny McGee
2023-10-11 10:28:05 -04:00
parent db9f377f2c
commit a34f31751f
3 changed files with 47 additions and 16 deletions
+1
View File
@@ -1 +1,2 @@
export * from "./lib/decorators/on";
export { default as spread } from "./lib/directives/spread";
+44
View File
@@ -0,0 +1,44 @@
import { ElementPart, nothing } from "lit";
import { directive, Directive } from "lit/directive.js";
interface Stringable {
toString(): string;
}
/**
* A simple implementation of React's spread operator (`...`) for Lit. Assigns
* each `{ [key]: value }` entry in the provided object as an HTML attribute to
* the element it's invoked on.
*
* React:
* @example
* ```jsx
* export default (props) => <div {...props} />
* ```
*
* Lit:
* @example
* ```typescript
* export class FooElement extends LitElement {
* props: Record<string, string> = {};
* override render = () => html`<div ${spread(props)}></div>`
* }
* ```
*
* @note
* The object entries are assigned as HTML _attributes_, not _properties_, so
* each enumerable value in the provided object must have a meaningnful
* `toString()` implementation.
*/
export default directive(class Spread extends Directive {
override render(_: Record<string, Stringable>) {
return nothing;
}
override update(part: ElementPart, [attrs]: [Record<string, Stringable>]) {
for (let [key, value] of Object.entries(attrs)) {
part.element.setAttribute(key, value.toString());
}
return part;
}
});
+2 -16
View File
@@ -1,7 +1,7 @@
import { spread } from "@storyteller/framework";
import { match } from "@storyteller/utility";
import { ElementPart, LitElement, TemplateResult, html, nothing, unsafeCSS } from "lit";
import { LitElement, TemplateResult, html, nothing, unsafeCSS } from "lit";
import { customElement, property } from "lit/decorators.js";
import { Directive, directive } from "lit/directive.js";
import { unsafeSVG } from "lit/directives/unsafe-svg.js";
import fasCircleInfo from "@fortawesome/fontawesome-pro/svgs/solid/circle-info.svg?raw";
@@ -59,17 +59,3 @@ function renderSvg(iconId: string) {
</svg>
`;
}
// TODO: Definitely move this
const spread = directive(class extends Directive {
override render(_: Record<string, string>) {
return nothing;
}
override update(part: ElementPart, [attrs]: [Record<string, string>]) {
for (let [key, value] of Object.entries(attrs)) {
part.element.setAttribute(key, value);
}
return part;
}
});