Reduce boilerplate associated with lit tasks

This commit is contained in:
Dermot Duffy
2022-08-06 12:26:29 -07:00
parent e9557ffb0e
commit 85d7c653cd
6 changed files with 61 additions and 48 deletions
+32
View File
@@ -0,0 +1,32 @@
import { Task } from '@lit-labs/task';
import { html, TemplateResult } from 'lit';
import {
dispatchFrigateCardErrorEvent,
renderProgressIndicator,
} from '../components/message';
import { errorToConsole } from './basic';
/**
* Render the result of a Lit task.
* @param host The host object.
* @param task The Lit task.
* @param completeFunc The function to call with the result.
* @param inProgressFunc The function to call whilst in progress.
* @returns A template.
*/
export const renderTask = <R>(
host: EventTarget,
task: Task<unknown[], R>,
completeFunc: (result: R) => TemplateResult | void,
inProgressFunc?: () => TemplateResult | void,
): TemplateResult => {
return html` ${task.render({
initial: () => inProgressFunc?.() ?? renderProgressIndicator(),
pending: () => inProgressFunc?.() ?? renderProgressIndicator(),
error: (e: unknown) => {
errorToConsole(e as Error);
dispatchFrigateCardErrorEvent(host, e as Error);
},
complete: completeFunc,
})}`;
};
+5 -3
View File
@@ -42,6 +42,8 @@ export const fetchThumbnail = async (
});
};
type FetchThumbnailTaskArgs = [boolean, string | undefined];
/**
* Create a Lit task to fetch a thumbnail.
* @param host The Lit Element.
@@ -53,10 +55,10 @@ export const createFetchThumbnailTask = (
host: ReactiveControllerHost,
getHASS: () => HomeAssistant | undefined,
getThumbnailURL: () => string | undefined,
): Task => {
): Task<FetchThumbnailTaskArgs, string | null> => {
return new Task(
host,
async ([haveHASS, thumbnailURL]: [boolean, string | undefined]): Promise<
async ([haveHASS, thumbnailURL]: FetchThumbnailTaskArgs): Promise<
string | null
> => {
const hass = getHASS();
@@ -66,6 +68,6 @@ export const createFetchThumbnailTask = (
return fetchThumbnail(hass, thumbnailURL);
},
// Do not re-run the task if hass changes, unless it was previously undefined.
(): [boolean, string | undefined] => [!!getHASS(), getThumbnailURL()],
(): FetchThumbnailTaskArgs => [!!getHASS(), getThumbnailURL()],
);
};