Skip to content

[Site] More Functional Code, 2x Complex Live Components Examples, few fixes #804

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
Apr 21, 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
4 changes: 2 additions & 2 deletions src/LiveComponent/doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2302,7 +2302,7 @@ Stimulus controller - like this for Bootstrap's modal:

// assets/controllers/bootstrap-modal-controller.js
import { Controller } from '@hotwired/stimulus';
import { Modal } from 'bootstrap';
import Modal from 'bootstrap/js/dist/modal';

export default class extends Controller {
modal = null;
Expand All @@ -2317,7 +2317,7 @@ Just make sure this controller is attached to the modal element:

.. code-block:: html+twig

<div class="modal fade" {{ stimulus_controller('bootstrap-modal') }}">
<div class="modal fade" {{ stimulus_controller('bootstrap-modal') }}>
<div class="modal-dialog">
... content ...
</div>
Expand Down
21 changes: 19 additions & 2 deletions src/TwigComponent/src/Twig/ComponentExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\UX\TwigComponent\ComponentFactory;
use Symfony\UX\TwigComponent\ComponentRenderer;
use Twig\Error\RuntimeError;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

Expand Down Expand Up @@ -53,11 +54,27 @@ public function getTokenParsers(): array

public function render(string $name, array $props = []): string
{
return $this->container->get(ComponentRenderer::class)->createAndRender($name, $props);
try {
return $this->container->get(ComponentRenderer::class)->createAndRender($name, $props);
} catch (\Throwable $e) {
$this->throwRuntimeError($name, $e);
}
}

public function embeddedContext(string $name, array $props, array $context): array
{
return $this->container->get(ComponentRenderer::class)->embeddedContext($name, $props, $context);
try {
return $this->container->get(ComponentRenderer::class)->embeddedContext($name, $props, $context);
} catch (\Throwable $e) {
$this->throwRuntimeError($name, $e);
}
}

private function throwRuntimeError(string $name, \Throwable $e): void
{
if (!($e instanceof \Exception)) {
$e = new \Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
}
throw new RuntimeError(sprintf('Error rendering "%s" component: %s', $name, $e->getMessage()), previous: $e);
Copy link
Member Author

Choose a reason for hiding this comment

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

I snuck this feature in. We may need some trial and error. But throwing a RuntimeError allows Twig to show the actual template + line number where the error occurred. The nested exception will be the one from your component (e.g. maybe you are passing null to a property in your component that only accepts string).

}
}
44 changes: 29 additions & 15 deletions src/TwigComponent/src/Twig/TwigPreLexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\UX\TwigComponent\Twig;

use Twig\Error\SyntaxError;

/**
* Rewrites <twig:component> syntaxes to {% component %} syntaxes.
*/
Expand Down Expand Up @@ -46,12 +48,12 @@ public function preLexComponents(string $input): string
$this->currentComponents[\count($this->currentComponents) - 1]['hasDefaultBlock'] = false;
}

$output .= $this->consumeBlock();
$output .= $this->consumeBlock($componentName);

continue;
}

$attributes = $this->consumeAttributes();
$attributes = $this->consumeAttributes($componentName);
$isSelfClosing = $this->consume('/>');
if (!$isSelfClosing) {
$this->consume('>');
Expand Down Expand Up @@ -79,7 +81,7 @@ public function preLexComponents(string $input): string
$lastComponentName = $lastComponent['name'];

if ($closingComponentName !== $lastComponentName) {
throw new \RuntimeException("Expected closing tag '</twig:{$lastComponentName}>' but found '</twig:{$closingComponentName}>' at line {$this->line}");
throw new SyntaxError("Expected closing tag '</twig:{$lastComponentName}>' but found '</twig:{$closingComponentName}>'", $this->line);
Copy link
Member Author

Choose a reason for hiding this comment

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

This is just a correction: allows the lexing error to show the template + line number in the exception.

}

// we've reached the end of this component. If we're inside the
Expand Down Expand Up @@ -112,28 +114,40 @@ public function preLexComponents(string $input): string

if (!empty($this->currentComponents)) {
$lastComponent = array_pop($this->currentComponents)['name'];
throw new \RuntimeException(sprintf('Expected closing tag "</twig:%s>" not found at line %d.', $lastComponent, $this->line));
throw new SyntaxError(sprintf('Expected closing tag "</twig:%s>" not found.', $lastComponent), $this->line);
}

return $output;
}

private function consumeComponentName(): string
private function consumeComponentName(string $customExceptionMessage = null): string
{
$start = $this->position;
while ($this->position < $this->length && preg_match('/[A-Za-z0-9_:@\-\/.]/', $this->input[$this->position])) {
++$this->position;
}

$componentName = substr($this->input, $start, $this->position - $start);

if (empty($componentName)) {
throw new \RuntimeException("Expected component name at line {$this->line}");
$exceptionMessage = $customExceptionMessage;
if (null == $exceptionMessage) {
$exceptionMessage = 'Expected component name when resolving the "<twig:" syntax.';
}
throw new SyntaxError($exceptionMessage, $this->line);
}

return $componentName;
}

private function consumeAttributes(): string
private function consumeAttributeName(string $componentName): string
{
$message = sprintf('Expected attribute name when parsing the "<twig:%s" syntax.', $componentName);

return $this->consumeComponentName($message);
}

private function consumeAttributes(string $componentName): string
{
$attributes = [];

Expand All @@ -151,7 +165,7 @@ private function consumeAttributes(): string
$isAttributeDynamic = true;
}

$key = $this->consumeComponentName();
$key = $this->consumeAttributeName($componentName);

// <twig:component someProp> -> someProp: true
if (!$this->check('=')) {
Expand Down Expand Up @@ -202,13 +216,13 @@ private function consume(string $string): bool
private function consumeChar($validChars = null): string
{
if ($this->position >= $this->length) {
throw new \RuntimeException('Unexpected end of input');
throw new SyntaxError('Unexpected end of input', $this->line);
}

$char = $this->input[$this->position];

if (null !== $validChars && !\in_array($char, (array) $validChars, true)) {
throw new \RuntimeException('Expected one of ['.implode('', (array) $validChars)."] but found '{$char}' at line {$this->line}");
throw new SyntaxError('Expected one of ['.implode('', (array) $validChars)."] but found '{$char}'.", $this->line);
}

++$this->position;
Expand Down Expand Up @@ -255,7 +269,7 @@ private function expectAndConsumeChar(string $char): void
}

if ($this->position >= $this->length || $this->input[$this->position] !== $char) {
throw new \RuntimeException("Expected '{$char}' but found '{$this->input[$this->position]}' at line {$this->line}");
throw new SyntaxError("Expected '{$char}' but found '{$this->input[$this->position]}'.", $this->line);
}
++$this->position;
}
Expand All @@ -276,9 +290,9 @@ private function check(string $chars): bool
return true;
}

private function consumeBlock(): string
private function consumeBlock(string $componentName): string
{
$attributes = $this->consumeAttributes();
$attributes = $this->consumeAttributes($componentName);
$this->consume('>');

$blockName = '';
Expand All @@ -291,14 +305,14 @@ private function consumeBlock(): string
}

if (empty($blockName)) {
throw new \RuntimeException("Expected block name at line {$this->line}");
throw new SyntaxError('Expected block name.', $this->line);
}

$output = "{% block {$blockName} %}";

$closingTag = '</twig:block>';
if (!$this->doesStringEventuallyExist($closingTag)) {
throw new \RuntimeException("Expected closing tag '{$closingTag}' for block '{$blockName}' at line {$this->line}");
throw new SyntaxError("Expected closing tag '{$closingTag}' for block '{$blockName}'.", $this->line);
}
$blockContents = $this->consumeUntil($closingTag);

Expand Down
2 changes: 0 additions & 2 deletions ux.symfony.com/assets/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ export const app = startStimulusApp(require.context(
/\.[jt]sx?$/
));

app.debug = process.env.NODE_ENV === 'development';

app.register('clipboard', Clipboard);
// register any custom, 3rd party controllers here

20 changes: 20 additions & 0 deletions ux.symfony.com/assets/controllers/bootstrap-modal-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Controller } from '@hotwired/stimulus';
import Modal from 'bootstrap/js/dist/modal';

/**
* Allows you to dispatch a "modal:close" JavaScript event to close it.
*
* This is useful inside a LiveComponent, where you can emit a browser event
* to open or close the modal.
*
* See templates/components/BootstrapModal.html.twig to see how this is
* attached to Bootstrap modal.
*/
export default class extends Controller {
modal = null;

connect() {
this.modal = Modal.getOrCreateInstance(this.element);
document.addEventListener('modal:close', () => this.modal.hide());
}
}
28 changes: 28 additions & 0 deletions ux.symfony.com/assets/controllers/code-expander-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
static targets = ['useStatements', 'expandCodeButton', 'codeContent'];

connect() {
if (this.#isOverflowing(this.codeContentTarget)) {
this.expandCodeButtonTarget.style.display = 'block';
// add extra padding so the button doesn't block the code
this.codeContentTarget.classList.add('pb-5');
}
}

expandUseStatements(event) {
this.useStatementsTarget.style.display = 'block';
event.currentTarget.remove();
}

expandCode(event) {
this.codeContentTarget.style.height = 'auto';
this.codeContentTarget.classList.remove('pb-5');
this.expandCodeButtonTarget.remove();
}

#isOverflowing(element) {
return element.scrollHeight > element.clientHeight;
}
}
20 changes: 20 additions & 0 deletions ux.symfony.com/assets/controllers/ux-clipboard-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Clipboard from 'stimulus-clipboard'

export default class extends Clipboard {
static values = {
source: String,
}

/**
* Overridden so we can simply pass the value in via a value.
*/
copy(event) {
if (!this.sourceValue) {
super.copy(event);
}

event.preventDefault();

navigator.clipboard.writeText(this.sourceValue).then(() => this.copied());
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 24 additions & 1 deletion ux.symfony.com/assets/styles/_terminal.scss
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@
.terminal-code {
background-color: $n-900;
border-radius: 12px;
padding: 0px;
padding: 0;
color: #fff;
font-size: 12px;
}

.terminal-code.terminal-code-no-filename {
padding-top: 0;
}
.terminal-code a.filename-header {
color: white;
display: inline-block;
}

.terminal-wrapper .terminal-controls {
position: absolute;
Expand Down Expand Up @@ -51,6 +55,25 @@
color: #FFF;
border-radius: 0px 0px 12px 12px;
}
.terminal-code .btn-copy, .terminal-code .btn-copy:active {
background-color: $n-700;
color: $n-200;
}
.terminal-code .btn-copy:hover {
background-color: $n-600;
}
/* copy button inside the code block itself */
.terminal-code .terminal-body .code-buttons {
position: absolute;
top: .5em;
right: .5em;
}
.terminal-code .btn-link {
color: $n-200;
}
.terminal-code .btn-link:hover {
color: $n-100;
}
.terminal-code.terminal-code-no-filename .terminal-body {
border-radius: 12px;
}
Expand Down
5 changes: 5 additions & 0 deletions ux.symfony.com/assets/styles/_type.scss
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,8 @@ h4.ubuntu {
color: $n-300;
font-weight: lighter;
}

blockquote {
border-left: 5px solid $n-200;
padding-left: 1rem;
}
16 changes: 16 additions & 0 deletions ux.symfony.com/assets/styles/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,19 @@ footer {
background-color: $n-700;
border-color: $n-700;
}

.btn-expand-code {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
color: rgb(156 163 175);
background-color: rgb(55 65 81);
}
.btn-expand-code:hover, .btn-expand-code:active {
background-color: rgb(55 65 81) !important;
color: #fff !important;
}
.code-description a {
text-decoration: underline;
}
5 changes: 0 additions & 5 deletions ux.symfony.com/code_snippets/README.md

This file was deleted.

30 changes: 0 additions & 30 deletions ux.symfony.com/code_snippets/_ChartController.php

This file was deleted.

Loading