Implement CustomEvent (#48922)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/48922

Changelog: [internal]

This is a basic subclass of Event that allows setting custom values (as opposed to `Event` that is meant to be used as a superclass).

Reviewed By: yungsters

Differential Revision: D67804060

fbshipit-source-id: 9e140cc436f8e230f37275a74df23efd4841071b
This commit is contained in:
Rubén Norte
2025-01-27 07:48:50 -08:00
committed by Facebook GitHub Bot
parent 8445ebc248
commit f282baa26a
3 changed files with 94 additions and 1 deletions
@@ -0,0 +1,40 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
* @format
*/
/**
* This module implements the `CustomEvent` interface from the DOM.
* See https://dom.spec.whatwg.org/#interface-customevent.
*/
// flowlint unsafe-getters-setters:off
import type {EventInit} from './Event';
import Event from './Event';
export type CustomEventInit = {
...EventInit,
detail?: mixed,
};
export default class CustomEvent extends Event {
_detail: mixed;
constructor(type: string, options?: ?CustomEventInit) {
const {detail, ...eventOptions} = options ?? {};
super(type, eventOptions);
this._detail = detail;
}
get detail(): mixed {
return this._detail;
}
}
@@ -36,7 +36,7 @@ import {
setStopPropagationFlag,
} from './internals/EventInternals';
type EventInit = {
export type EventInit = {
bubbles?: boolean,
cancelable?: boolean,
composed?: boolean,
@@ -0,0 +1,53 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
* @fantom_flags enableAccessToHostTreeInFabric:true
*/
import '../../../../../../Libraries/Core/InitializeCore.js';
import CustomEvent from '../CustomEvent';
import Event from '../Event';
describe('CustomEvent', () => {
it('extends Event', () => {
const event = new CustomEvent('foo', {
bubbles: true,
cancelable: true,
composed: true,
});
expect(event.type).toBe('foo');
expect(event.bubbles).toBe(true);
expect(event.cancelable).toBe(true);
expect(event.composed).toBe(true);
expect(event).toBeInstanceOf(Event);
});
it('allows passing a detail value', () => {
const detail = Symbol('detail');
const event = new CustomEvent('foo', {detail});
expect(event.detail).toBe(detail);
});
it('does NOT allow changing the detail value after construction', () => {
const detail = Symbol('detail');
const event = new CustomEvent('foo', {detail});
expect(() => {
'use strict';
// Use strict mode to throw an error instead of silently failing
// $FlowExpectedError[cannot-write]
event.detail = 'bar';
}).toThrow();
});
});