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/app/app.js
Dan Gebhardt 0221855ba7
DEV: Normalize event handling to improve Glimmer + Classic component compat (Take 2) (#18742)
Classic Ember components (i.e. "@ember/component") rely upon "event
delegation" to listen for events at the application root and then dispatch
those events to any event handlers defined on individual Classic components.
This coordination is handled by Ember's EventDispatcher.

In contrast, Glimmer components (i.e. "@glimmer/component") expect event
listeners to be added to elements using modifiers (such as `{{on "click"}}`).
These event listeners are added directly to DOM elements using
`addEventListener`. There is no need for an event dispatcher.

Issues may arise when using Classic and Glimmer components together, since it
requires reconciling the two event handling approaches. For instance, event
propagation may not work as expected when a Classic component is nested
inside a Glimmer component.

`normalizeEmberEventHandling` helps an application standardize upon the
Glimmer event handling approach by eliminating usage of event delegation and
instead rewiring Classic components to directly use `addEventListener`.

Specifically, it performs the following:

- Invokes `eliminateClassicEventDelegation()` to remove all events associated
  with Ember's EventDispatcher to reduce its runtime overhead and ensure that
  it is effectively not in use.

- Invokes `rewireClassicComponentEvents(app)` to rewire each Classic
  component to add its own event listeners for standard event handlers (e.g.
  `click`, `mouseDown`, `submit`, etc.).

- Configures an instance initializer that invokes
  `rewireActionModifier(appInstance)` to redefine the `action` modifier with
    a substitute that uses `addEventListener`.

Additional changes include:
* d-button: only preventDefault / stopPropagation for handled actions
   This allows unhandled events to propagate as expected.
* d-editor: avoid adding duplicate event listener for tests
   This extra event listener causes duplicate paste events in tests.
* group-manage-email-settings: Monitor `input` instead of `change` event for checkboxes
2022-10-26 14:44:12 +01:00

131 lines
3.4 KiB
JavaScript

import Application from "@ember/application";
import { buildResolver } from "discourse-common/resolver";
import { isTesting } from "discourse-common/config/environment";
import { normalizeEmberEventHandling } from "./lib/ember-events";
const _pluginCallbacks = [];
let _unhandledThemeErrors = [];
const Discourse = Application.extend({
modulePrefix: "discourse",
rootElement: "#main",
customEvents: {
paste: "paste",
},
Resolver: buildResolver("discourse"),
_prepareInitializer(moduleName) {
const themeId = moduleThemeId(moduleName);
let module = null;
try {
module = requirejs(moduleName, null, null, true);
if (!module) {
throw new Error(moduleName + " must export an initializer.");
}
} catch (error) {
if (!themeId || isTesting()) {
throw error;
}
fireThemeErrorEvent({ themeId, error });
return;
}
const init = module.default;
const oldInitialize = init.initialize;
init.initialize = (app) => {
try {
return oldInitialize.call(init, app.__container__, app);
} catch (error) {
if (!themeId || isTesting()) {
throw error;
}
fireThemeErrorEvent({ themeId, error });
}
};
return init;
},
// Start up the Discourse application by running all the initializers we've defined.
start() {
document.querySelector("noscript")?.remove();
// Rewire event handling to eliminate event delegation for better compat
// between Glimmer and Classic components.
normalizeEmberEventHandling(this);
if (Error.stackTraceLimit) {
// We need Errors to have full stack traces for `lib/source-identifier`
Error.stackTraceLimit = Infinity;
}
Object.keys(requirejs._eak_seen).forEach((key) => {
if (/\/pre\-initializers\//.test(key)) {
const initializer = this._prepareInitializer(key);
if (initializer) {
this.initializer(initializer);
}
} else if (/\/(api\-)?initializers\//.test(key)) {
const initializer = this._prepareInitializer(key);
if (initializer) {
this.instanceInitializer(initializer);
}
}
});
// Plugins that are registered via `<script>` tags.
const withPluginApi = requirejs("discourse/lib/plugin-api").withPluginApi;
let initCount = 0;
_pluginCallbacks.forEach((cb) => {
this.instanceInitializer({
name: `_discourse_plugin_${++initCount}`,
after: "inject-objects",
initialize: () => withPluginApi(cb.version, cb.code),
});
});
},
_registerPluginCode(version, code) {
_pluginCallbacks.push({ version, code });
},
ready() {
performance.mark("discourse-ready");
const event = new CustomEvent("discourse-ready");
document.dispatchEvent(event);
},
});
function moduleThemeId(moduleName) {
const match = moduleName.match(/^discourse\/theme\-(\d+)\//);
if (match) {
return parseInt(match[1], 10);
}
}
function fireThemeErrorEvent({ themeId, error }) {
const event = new CustomEvent("discourse-error", {
cancelable: true,
detail: { themeId, error },
});
const unhandled = document.dispatchEvent(event);
if (unhandled) {
_unhandledThemeErrors.push(event);
}
}
export function getAndClearUnhandledThemeErrors() {
const copy = _unhandledThemeErrors;
_unhandledThemeErrors = [];
return copy;
}
export default Discourse;