Skip to content
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

Introduce UX React component #329

Merged
merged 1 commit into from
Jun 6, 2022
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
17 changes: 17 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ jobs:
run: php vendor/bin/simple-phpunit
working-directory: src/LazyImage

- name: React Dependencies
uses: ramsey/composer-install@v2
with:
working-directory: src/React
dependency-versions: lowest
- name: React Tests
run: php vendor/bin/simple-phpunit
working-directory: src/React

tests-php8-low-deps:
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -184,6 +193,14 @@ jobs:
working-directory: src/LiveComponent
run: php vendor/bin/simple-phpunit

- name: React Dependencies
uses: ramsey/composer-install@v2
with:
working-directory: src/React
- name: React Tests
working-directory: src/React
run: php vendor/bin/simple-phpunit

tests-php81-high-deps:
runs-on: ubuntu-latest
steps:
Expand Down
1 change: 1 addition & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/react',
'@babel/preset-typescript',
],
};
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ module.exports = {
path.join(__dirname, 'test/setup.js'),
],
transform: {
'\\.(j|t)s$': ['babel-jest', { configFile: path.join(__dirname, './babel.config.js') }]
'\\.(j|t)s': ['babel-jest', { configFile: path.join(__dirname, './babel.config.js') }]
},
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"devDependencies": {
"@babel/core": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"@babel/preset-typescript": "^7.15.0",
"@babel/preset-react": "^7.15.8",
"@babel/preset-typescript": "^7.15.8",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-typescript": "^8.3.0",
"@symfony/stimulus-testing": "^2.0.1",
Expand Down
13 changes: 8 additions & 5 deletions src/LiveComponent/assets/dist/live_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -971,11 +971,14 @@ function haveRenderedValuesChanged(originalDataJson, currentDataJson, newDataJso
}

function normalizeAttributesForComparison(element) {
if (element.value) {
element.setAttribute('value', element.value);
}
else if (element.hasAttribute('value')) {
element.setAttribute('value', '');
const isFileInput = element instanceof HTMLInputElement && element.type === 'file';
if (!isFileInput) {
if (element.value) {
element.setAttribute('value', element.value);
}
else if (element.hasAttribute('value')) {
element.setAttribute('value', '');
}
jderusse marked this conversation as resolved.
Show resolved Hide resolved
}
Array.from(element.children).forEach((child) => {
normalizeAttributesForComparison(child);
Expand Down
5 changes: 5 additions & 0 deletions src/React/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.gitattributes export-ignore
/.gitignore export-ignore
/phpunit.xml.dist export-ignore
/Resources/assets/test export-ignore
/Tests export-ignore
4 changes: 4 additions & 0 deletions src/React/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vendor
composer.lock
.php_cs.cache
.phpunit.result.cache
3 changes: 3 additions & 0 deletions src/React/.symfony.bundle.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
branches: ["2.x"]
maintained_branches: ["2.x"]
doc_dir: "Resources/doc"
5 changes: 5 additions & 0 deletions src/React/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# CHANGELOG

## 2.2

- Component added
36 changes: 36 additions & 0 deletions src/React/DependencyInjection/ReactExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\React\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\UX\React\Twig\ReactComponentExtension;

/**
* @author Titouan Galopin <[email protected]>
*
* @internal
*/
class ReactExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$container
->setDefinition('twig.extension.react', new Definition(ReactComponentExtension::class))
->setArgument(0, new Reference('webpack_encore.twig_stimulus_extension'))
->addTag('twig.extension')
->setPublic(false)
;
}
}
19 changes: 19 additions & 0 deletions src/React/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2020-2021 Fabien Potencier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
14 changes: 14 additions & 0 deletions src/React/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Symfony UX React

Symfony UX React integrates [React](https://reactjs.org/) into Symfony applications.
It provides tools to render React components from Twig.

**This repository is a READ-ONLY sub-tree split**. See
https://github.com/symfony/ux to create issues or submit pull requests.

## Resources

- [Documentation](https://symfony.com/bundles/ux-react/current/index.html)
- [Report issues](https://github.com/symfony/ux/issues) and
[send Pull Requests](https://github.com/symfony/ux/pulls)
in the [main Symfony UX repository](https://github.com/symfony/ux)
24 changes: 24 additions & 0 deletions src/React/ReactBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\React;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
* @author Titouan Galopin <[email protected]>
*
* @final
* @experimental
*/
class ReactBundle extends Bundle
{
}
16 changes: 16 additions & 0 deletions src/React/Resources/assets/dist/register_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function registerReactControllerComponents(context) {
const reactControllers = {};
const importAllReactComponents = (r) => {
r.keys().forEach((key) => (reactControllers[key] = r(key).default));
};
importAllReactComponents(context);
window.resolveReactComponent = (name) => {
const component = reactControllers['./' + name + '.jsx'] || reactControllers['./' + name + '.tsx'];
if (typeof component === 'undefined') {
throw new Error('React controller "' + name + '" does not exist');
}
return component;
};
}

export { registerReactControllerComponents };
43 changes: 43 additions & 0 deletions src/React/Resources/assets/dist/render_controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React from 'react';
import { Controller } from '@hotwired/stimulus';

class default_1 extends Controller {
connect() {
this._dispatchEvent('react:connect', { component: this.componentValue, props: this.propsValue });
const component = window.resolveReactComponent(this.componentValue);
this._renderReactElement(React.createElement(component, this.propsValue, null));
this._dispatchEvent('react:mount', {
componentName: this.componentValue,
component: component,
props: this.propsValue,
});
}
disconnect() {
this.element.unmount();
this._dispatchEvent('react:unmount', { component: this.componentValue, props: this.propsValue });
}
_renderReactElement(reactElement) {
if (parseInt(React.version) >= 18) {
const root = require('react-dom/client').createRoot(this.element);
root.render(reactElement);
this.element.unmount = () => {
root.unmount();
};
return;
}
const reactDom = require('react-dom');
reactDom.render(reactElement, this.element);
this.element.unmount = () => {
reactDom.unmountComponentAtNode(this.element);
};
}
_dispatchEvent(name, payload) {
this.element.dispatchEvent(new CustomEvent(name, { detail: payload, bubbles: true }));
}
}
default_1.values = {
component: String,
props: Object,
};

export { default_1 as default };
1 change: 1 addition & 0 deletions src/React/Resources/assets/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('../../../../jest.config.js');
30 changes: 30 additions & 0 deletions src/React/Resources/assets/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@symfony/ux-react",
"description": "Integration of React in Symfony",
"license": "MIT",
"version": "1.0.0",
"main": "dist/register_controller.js",
"symfony": {
"controllers": {
"react": {
"main": "dist/render_controller.js",
"webpackMode": "eager",
"fetch": "eager",
"enabled": true
}
}
},
"peerDependencies": {
"@hotwired/stimulus": "^3.0.0",
"react": "^18.0",
"react-dom": "^18.0"
},
"devDependencies": {
"@hotwired/stimulus": "^3.0.0",
"@types/react": "^18.0",
"@types/react-dom": "^18.0",
"@types/webpack-env": "^1.16",
"react": "^18.0",
"react-dom": "^18.0"
}
}
30 changes: 30 additions & 0 deletions src/React/Resources/assets/src/register_controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

'use strict';

export function registerReactControllerComponents(context: __WebpackModuleApi.RequireContext) {
const reactControllers: { [key: string]: object } = {};

const importAllReactComponents = (r: __WebpackModuleApi.RequireContext) => {
r.keys().forEach((key) => (reactControllers[key] = r(key).default));
};

importAllReactComponents(context);

// Expose a global React loader to allow rendering from the Stimulus controller
(window as any).resolveReactComponent = (name: string): object => {
const component = reactControllers[`./${name}.jsx`] || reactControllers[`./${name}.tsx`];
if (typeof component === 'undefined') {
throw new Error('React controller "' + name + '" does not exist');
}

return component;
};
}
53 changes: 53 additions & 0 deletions src/React/Resources/assets/src/render_controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

'use strict';

import React, { ReactElement } from 'react';
import { createRoot } from 'react-dom/client';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, actually this is proving problematic. I merged, thinking the yarn build failure was something unrelated, but it's not. yarn build fails here with:

Error: 'createRoot' is not exported by node_modules/react-dom/client.js, imported by src/React/Resources/assets/src/render_controller.ts

That is not correct... as createRoot IS an export of that file. I'm not sure if we may need commonjs for rollup (https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module... also ref similar issue: JedWatson/react-select#3956 (comment)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like I fixed it over here: #330

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! I was going to have a look :)

import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
readonly componentValue: string;
readonly propsValue: object;

static values = {
component: String,
props: Object,
};

connect() {
this._dispatchEvent('react:connect', { component: this.componentValue, props: this.propsValue });

const component = window.resolveReactComponent(this.componentValue);
this._renderReactElement(React.createElement(component, this.propsValue, null));

this._dispatchEvent('react:mount', {
componentName: this.componentValue,
component: component,
props: this.propsValue,
});
}

disconnect() {
(this.element as any).root.unmount();
this._dispatchEvent('react:unmount', { component: this.componentValue, props: this.propsValue });
}

_renderReactElement(reactElement: ReactElement) {
const root = createRoot(this.element);
root.render(reactElement);

(this.element as any).root = root;
}

_dispatchEvent(name: string, payload: any) {
this.element.dispatchEvent(new CustomEvent(name, { detail: payload, bubbles: true }));
}
}
3 changes: 3 additions & 0 deletions src/React/Resources/assets/test/fixtures/MyJsxComponent.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function () {
return <div>Hello</div>;
tgalopin marked this conversation as resolved.
Show resolved Hide resolved
}
5 changes: 5 additions & 0 deletions src/React/Resources/assets/test/fixtures/MyTsxComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

export default function () {
return <div>Hello</div>;
}
Loading