Skip to content

[Live] Emit system for component-to-component communication! #765

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

Merged
merged 1 commit into from
Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions src/LiveComponent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public User $user;
the DOM inside a live component, those changes will now be _kept_ when
the component is re-rendered. This has limitations - see the documentation.

- You can now `emit()` events to communicate between components.

- Boolean checkboxes are now supported. Of a checkbox does **not** have a
`value` attribute, then the associated `LiveProp` will be set to a boolean
when the input is checked/unchecked.
Expand Down
12 changes: 12 additions & 0 deletions src/LiveComponent/assets/dist/Component/ElementDriver.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,22 @@ export interface ElementDriver {
getComponentProps(rootElement: HTMLElement): any;
findChildComponentElement(id: string, element: HTMLElement): HTMLElement | null;
getKeyFromElement(element: HTMLElement): string | null;
getEventsToEmit(element: HTMLElement): Array<{
event: string;
data: any;
target: string | null;
componentName: string | null;
}>;
}
export declare class StandardElementDriver implements ElementDriver {
getModelName(element: HTMLElement): string | null;
getComponentProps(rootElement: HTMLElement): any;
findChildComponentElement(id: string, element: HTMLElement): HTMLElement | null;
getKeyFromElement(element: HTMLElement): string | null;
getEventsToEmit(element: HTMLElement): Array<{
event: string;
data: any;
target: string | null;
componentName: string | null;
}>;
}
14 changes: 13 additions & 1 deletion src/LiveComponent/assets/dist/Component/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import { ElementDriver } from './ElementDriver';
import { PluginInterface } from './plugins/PluginInterface';
import BackendResponse from '../Backend/BackendResponse';
import { ModelBinding } from '../Directive/get_model_binding';
export type ComponentFinder = (currentComponent: Component, onlyParents: boolean, onlyMatchName: string | null) => Component[];
export default class Component {
readonly element: HTMLElement;
readonly name: string;
readonly listeners: Map<string, string[]>;
private readonly componentFinder;
private backend;
private readonly elementDriver;
id: string | null;
Expand All @@ -23,7 +27,10 @@ export default class Component {
private children;
private parent;
private externalMutationTracker;
constructor(element: HTMLElement, props: any, fingerprint: string | null, id: string | null, backend: BackendInterface, elementDriver: ElementDriver);
constructor(element: HTMLElement, name: string, props: any, listeners: Array<{
event: string;
action: string;
}>, componentFinder: ComponentFinder, fingerprint: string | null, id: string | null, backend: BackendInterface, elementDriver: ElementDriver);
_swapBackend(backend: BackendInterface): void;
addPlugin(plugin: PluginInterface): void;
connect(): void;
Expand All @@ -39,6 +46,11 @@ export default class Component {
removeChild(child: Component): void;
getParent(): Component | null;
getChildren(): Map<string, Component>;
emit(name: string, data: any, onlyMatchingComponentsNamed?: string | null): void;
emitUp(name: string, data: any, onlyMatchingComponentsNamed?: string | null): void;
emitSelf(name: string, data: any): void;
private performEmit;
private doEmit;
updateFromNewElement(toEl: HTMLElement): boolean;
onChildComponentModelUpdate(modelName: string, value: any, childComponent: Component): void;
private tryStartingRequest;
Expand Down
12 changes: 6 additions & 6 deletions src/LiveComponent/assets/dist/ComponentRegistry.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Component from './Component';
declare class ComponentRegistry {
private components;
registerComponent(element: HTMLElement, definition: Component): void;
unregisterComponent(element: HTMLElement): void;
export default class {
private componentMapByElement;
private componentMapByComponent;
registerComponent(element: HTMLElement, component: Component): void;
unregisterComponent(component: Component): void;
getComponent(element: HTMLElement): Promise<Component>;
findComponents(currentComponent: Component, onlyParents: boolean, onlyMatchName: string | null): Component[];
}
declare const _default: ComponentRegistry;
export default _default;
16 changes: 16 additions & 0 deletions src/LiveComponent/assets/dist/live_controller.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Controller } from '@hotwired/stimulus';
import Component from './Component';
import ComponentRegistry from './ComponentRegistry';
export { Component };
export declare const getComponent: (element: HTMLElement) => Promise<Component>;
export interface LiveEvent extends CustomEvent {
Expand All @@ -14,32 +15,47 @@ export interface LiveController {
}
export default class LiveControllerDefault extends Controller<HTMLElement> implements LiveController {
static values: {
name: StringConstructor;
url: StringConstructor;
props: ObjectConstructor;
csrf: StringConstructor;
listeners: {
type: ArrayConstructor;
default: never[];
};
debounce: {
type: NumberConstructor;
default: number;
};
id: StringConstructor;
fingerprint: StringConstructor;
};
readonly nameValue: string;
readonly urlValue: string;
readonly propsValue: any;
readonly csrfValue: string;
readonly listenersValue: Array<{
event: string;
action: string;
}>;
readonly hasDebounceValue: boolean;
readonly debounceValue: number;
readonly fingerprintValue: string;
private proxiedComponent;
component: Component;
pendingActionTriggerModelElement: HTMLElement | null;
private elementEventListeners;
static componentRegistry: ComponentRegistry;
initialize(): void;
connect(): void;
disconnect(): void;
update(event: any): void;
action(event: any): void;
$render(): Promise<import("./Backend/BackendResponse").default>;
emit(event: Event): void;
emitUp(event: Event): void;
emitSelf(event: Event): void;
private getEmitDirectives;
$updateModel(model: string, value: any, shouldRender?: boolean, debounce?: number | boolean): Promise<import("./Backend/BackendResponse").default>;
private handleInputEvent;
private handleChangeEvent;
Expand Down
136 changes: 124 additions & 12 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -1728,7 +1728,7 @@ class ChildComponentWrapper {
}
}
class Component {
constructor(element, props, fingerprint, id, backend, elementDriver) {
constructor(element, name, props, listeners, componentFinder, fingerprint, id, backend, elementDriver) {
this.defaultDebounce = 150;
this.backendRequest = null;
this.pendingActions = [];
Expand All @@ -1737,10 +1737,20 @@ class Component {
this.children = new Map();
this.parent = null;
this.element = element;
this.name = name;
this.componentFinder = componentFinder;
this.backend = backend;
this.elementDriver = elementDriver;
this.id = id;
this.fingerprint = fingerprint;
this.listeners = new Map();
listeners.forEach((listener) => {
var _a;
if (!this.listeners.has(listener.event)) {
this.listeners.set(listener.event, []);
}
(_a = this.listeners.get(listener.event)) === null || _a === void 0 ? void 0 : _a.push(listener.action);
});
this.valueStore = new ValueStore(props);
this.unsyncedInputsTracker = new UnsyncedInputsTracker(this, elementDriver);
this.hooks = new HookManager();
Expand Down Expand Up @@ -1833,6 +1843,30 @@ class Component {
});
return children;
}
emit(name, data, onlyMatchingComponentsNamed = null) {
return this.performEmit(name, data, false, onlyMatchingComponentsNamed);
}
emitUp(name, data, onlyMatchingComponentsNamed = null) {
return this.performEmit(name, data, true, onlyMatchingComponentsNamed);
}
emitSelf(name, data) {
return this.doEmit(name, data);
}
performEmit(name, data, emitUp, matchingName) {
const components = this.componentFinder(this, emitUp, matchingName);
components.forEach((component) => {
component.doEmit(name, data);
});
}
doEmit(name, data) {
if (!this.listeners.has(name)) {
return;
}
const actions = this.listeners.get(name) || [];
actions.forEach((action) => {
this.action(action, data, 1);
});
}
updateFromNewElement(toEl) {
const props = this.elementDriver.getComponentProps(toEl);
if (props === null) {
Expand Down Expand Up @@ -1937,13 +1971,25 @@ class Component {
}
const newProps = this.elementDriver.getComponentProps(newElement);
this.valueStore.reinitializeAllProps(newProps);
const eventsToEmit = this.elementDriver.getEventsToEmit(newElement);
this.externalMutationTracker.handlePendingChanges();
this.externalMutationTracker.stop();
executeMorphdom(this.element, newElement, this.unsyncedInputsTracker.getUnsyncedInputs(), (element) => getValueFromElement(element, this.valueStore), Array.from(this.getChildren().values()), this.elementDriver.findChildComponentElement, this.elementDriver.getKeyFromElement, this.externalMutationTracker);
this.externalMutationTracker.start();
Object.keys(modifiedModelValues).forEach((modelName) => {
this.valueStore.set(modelName, modifiedModelValues[modelName]);
});
eventsToEmit.forEach(({ event, data, target, componentName }) => {
if (target === 'up') {
this.emitUp(event, data, componentName);
return;
}
if (target === 'self') {
this.emitSelf(event, data);
return;
}
this.emit(event, data, componentName);
});
this.hooks.triggerHook('render:finished', this);
}
calculateDebounce(debounce) {
Expand Down Expand Up @@ -2165,6 +2211,11 @@ class StandardElementDriver {
getKeyFromElement(element) {
return element.dataset.liveId || null;
}
getEventsToEmit(element) {
var _a;
const eventsJson = (_a = element.dataset.liveEmit) !== null && _a !== void 0 ? _a : '[]';
return JSON.parse(eventsJson);
}
}

class LoadingPlugin {
Expand Down Expand Up @@ -2540,20 +2591,23 @@ function getModelBinding (modelDirective) {

class ComponentRegistry {
constructor() {
this.components = new WeakMap();
this.componentMapByElement = new WeakMap();
this.componentMapByComponent = new Map();
}
registerComponent(element, definition) {
this.components.set(element, definition);
registerComponent(element, component) {
this.componentMapByElement.set(element, component);
this.componentMapByComponent.set(component, component.name);
}
unregisterComponent(element) {
this.components.delete(element);
unregisterComponent(component) {
this.componentMapByElement.delete(component.element);
this.componentMapByComponent.delete(component);
}
getComponent(element) {
return new Promise((resolve, reject) => {
let count = 0;
const maxCount = 10;
const interval = setInterval(() => {
const component = this.components.get(element);
const component = this.componentMapByElement.get(element);
if (component) {
resolve(component);
}
Expand All @@ -2565,10 +2619,23 @@ class ComponentRegistry {
}, 5);
});
}
findComponents(currentComponent, onlyParents, onlyMatchName) {
const components = [];
this.componentMapByComponent.forEach((componentName, component) => {
if (onlyParents &&
(currentComponent === component || !component.element.contains(currentComponent.element))) {
return;
}
if (onlyMatchName && componentName !== onlyMatchName) {
return;
}
components.push(component);
});
return components;
}
}
var ComponentRegistry$1 = new ComponentRegistry();

const getComponent = (element) => ComponentRegistry$1.getComponent(element);
const getComponent = (element) => LiveControllerDefault.componentRegistry.getComponent(element);
class LiveControllerDefault extends Controller {
constructor() {
super(...arguments);
Expand All @@ -2582,7 +2649,7 @@ class LiveControllerDefault extends Controller {
initialize() {
this.handleDisconnectedChildControllerEvent = this.handleDisconnectedChildControllerEvent.bind(this);
const id = this.element.dataset.liveId || null;
this.component = new Component(this.element, this.propsValue, this.fingerprintValue, id, new Backend(this.urlValue, this.csrfValue), new StandardElementDriver());
this.component = new Component(this.element, this.nameValue, this.propsValue, this.listenersValue, (currentComponent, onlyParents, onlyMatchName) => LiveControllerDefault.componentRegistry.findComponents(currentComponent, onlyParents, onlyMatchName), this.fingerprintValue, id, new Backend(this.urlValue, this.csrfValue), new StandardElementDriver());
this.proxiedComponent = proxifyComponent(this.component);
this.element.__component = this.proxiedComponent;
if (this.hasDebounceValue) {
Expand All @@ -2600,19 +2667,19 @@ class LiveControllerDefault extends Controller {
});
}
connect() {
LiveControllerDefault.componentRegistry.registerComponent(this.element, this.component);
this.component.connect();
this.elementEventListeners.forEach(({ event, callback }) => {
this.component.element.addEventListener(event, callback);
});
ComponentRegistry$1.registerComponent(this.element, this.component);
this.dispatchEvent('connect');
}
disconnect() {
LiveControllerDefault.componentRegistry.unregisterComponent(this.component);
this.component.disconnect();
this.elementEventListeners.forEach(({ event, callback }) => {
this.component.element.removeEventListener(event, callback);
});
ComponentRegistry$1.unregisterComponent(this.element);
this.dispatchEvent('disconnect');
}
update(event) {
Expand Down Expand Up @@ -2659,6 +2726,48 @@ class LiveControllerDefault extends Controller {
$render() {
return this.component.render();
}
emit(event) {
this.getEmitDirectives(event).forEach(({ name, data, nameMatch }) => {
this.component.emit(name, data, nameMatch);
});
}
emitUp(event) {
this.getEmitDirectives(event).forEach(({ name, data, nameMatch }) => {
this.component.emitUp(name, data, nameMatch);
});
}
emitSelf(event) {
this.getEmitDirectives(event).forEach(({ name, data }) => {
this.component.emitSelf(name, data);
});
}
getEmitDirectives(event) {
const element = event.currentTarget;
if (!element.dataset.event) {
throw new Error(`No data-event attribute found on element: ${getElementAsTagText(element)}`);
}
const eventInfo = element.dataset.event;
const directives = parseDirectives(eventInfo);
const emits = [];
directives.forEach((directive) => {
let nameMatch = null;
directive.modifiers.forEach((modifier) => {
switch (modifier.name) {
case 'name':
nameMatch = modifier.value;
break;
default:
throw new Error(`Unknown modifier ${modifier.name} in event "${eventInfo}".`);
}
});
emits.push({
name: directive.action,
data: directive.named,
nameMatch,
});
});
return emits;
}
$updateModel(model, value, shouldRender = true, debounce = true) {
return this.component.set(model, value, shouldRender, debounce);
}
Expand Down Expand Up @@ -2739,12 +2848,15 @@ class LiveControllerDefault extends Controller {
}
}
LiveControllerDefault.values = {
name: String,
url: String,
props: Object,
csrf: String,
listeners: { type: Array, default: [] },
debounce: { type: Number, default: 150 },
id: String,
fingerprint: String,
};
LiveControllerDefault.componentRegistry = new ComponentRegistry();

export { Component, LiveControllerDefault as default, getComponent };
Loading