Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
giswqs
GitHub Repository: giswqs/geemap
Path: blob/master/js/lit_widget.ts
2313 views
1
import { LitElement, PropertyValues } from "lit";
2
3
import { reverseMap } from "./utils";
4
5
export abstract class LitWidget<
6
ModelType,
7
SubclassType extends LitWidget<any, any>
8
> extends LitElement {
9
private _model: any | undefined = undefined; // AnyModel<ModelType>
10
11
abstract modelNameToViewName(): Map<
12
keyof ModelType,
13
keyof SubclassType | null
14
>;
15
16
onCustomMessage?(_msg: any): void {}
17
18
viewNameToModelName(): Map<keyof SubclassType | null, keyof ModelType> {
19
return reverseMap(this.modelNameToViewName());
20
}
21
22
set model(model: any) {
23
// TODO(naschmitz): model should be of type AnyModel<ModelType>. AnyModel
24
// requires a type that conforms to a non-exported member of anywidget.
25
this._model = model;
26
for (const [modelKey, widgetKey] of this.modelNameToViewName()) {
27
if (widgetKey) {
28
// Get initial values from the Python model.
29
(this as any)[widgetKey] = model.get(modelKey);
30
// Listen for updates to the model.
31
model.on(`change:${String(modelKey)}`, () => {
32
(this as any)[widgetKey] = model.get(modelKey);
33
});
34
}
35
}
36
model.on("msg:custom", (msg: any) => {
37
this.onCustomMessage?.(msg);
38
});
39
}
40
41
get model(): any {
42
// TODO(naschmitz): model should be of type AnyModel<ModelType>. AnyModel
43
// requires a type that conforms to a non-exported member of anywidget.
44
return this._model;
45
}
46
47
override updated(changedProperties: PropertyValues<SubclassType>): void {
48
// Update the model properties so they're reflected in Python.
49
const viewToModelMap = this.viewNameToModelName();
50
for (const [viewProp, _] of changedProperties) {
51
const castViewProp = viewProp as keyof SubclassType;
52
if (viewToModelMap.has(castViewProp)) {
53
const modelProp = viewToModelMap.get(castViewProp);
54
this._model?.set(
55
modelProp as any,
56
this[castViewProp as keyof this] as any
57
);
58
}
59
}
60
this._model?.save_changes();
61
}
62
}
63
64