This repository has been archived on 2023-03-18. You can view files and clone it, but cannot push or open issues or pull requests.
osr-discourse-src/app/assets/javascripts/discourse/widgets/component-connector.js.es6
Joffrey JAFFEUX 0431942f3d
DEV: select-kit 2 (#7998)
This new iteration of select-kit focuses on following best principales and disallowing mutations inside select-kit components. A best effort has been made to avoid breaking changes, however if you content was a flat array, eg: ["foo", "bar"] You will need to set valueProperty=null and nameProperty=null on the component.

Also almost every component should have an `onChange` handler now to decide what to do with the updated data. **select-kit will not mutate your data by itself anymore**
2020-02-03 14:22:14 +01:00

62 lines
1.7 KiB
JavaScript

import { next } from "@ember/runloop";
import { setOwner, getOwner } from "@ember/application";
export default class ComponentConnector {
constructor(widget, componentName, opts, trackedProperties) {
this.widget = widget;
this.opts = opts;
this.componentName = componentName;
this.trackedProperties = trackedProperties || [];
}
init() {
const $elem = $(
'<div style="display: inline-flex;" class="widget-component-connector"></div>'
);
const elem = $elem[0];
const { opts, widget, componentName } = this;
next(() => {
const mounted = widget._findView();
const view = widget.register
.lookupFactory(`component:${componentName}`)
.create(opts);
if (setOwner) {
setOwner(view, getOwner(mounted));
}
// component connector is not triggering didReceiveAttrs
// we force it for selectKit components
if (view.selectKit) {
view.didReceiveAttrs();
}
mounted._connected.push(view);
view.renderer.appendTo(view, $elem[0]);
});
return elem;
}
update(prev) {
// mutated external properties might not correctly update the underlying component
// in this case we can define trackedProperties, if different from previous
// state we will re-init the whole component, be careful when using this
// to not track a property which would be updated too often (on scroll for example)
let shouldInit = false;
this.trackedProperties.forEach(prop => {
if (prev.opts[prop] !== this.opts[prop]) {
shouldInit = true;
}
});
if (shouldInit) return this.init();
return null;
}
}
ComponentConnector.prototype.type = "Widget";