Skip to content

Commit bc5c72c

Browse files
authored
feat: Find where component is created in code by clicking in UI (#15590)
* Change styles to an array * feat: Find where component is created in code by clicking in UI
1 parent 7ea96be commit bc5c72c

6 files changed

Lines changed: 958 additions & 600 deletions

File tree

‎vaadin-dev-server/src/main/java/com/vaadin/base/devserver/DebugWindowConnection.java‎

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,22 +21,28 @@
2121
import java.util.EnumMap;
2222
import java.util.List;
2323
import java.util.Map;
24+
import java.util.Optional;
2425
import java.util.concurrent.ConcurrentLinkedQueue;
2526
import java.util.stream.Collectors;
2627

28+
import org.atmosphere.cpr.AtmosphereResource;
29+
import org.slf4j.Logger;
30+
import org.slf4j.LoggerFactory;
31+
2732
import com.fasterxml.jackson.databind.ObjectMapper;
2833
import com.vaadin.base.devserver.stats.DevModeUsageStatistics;
2934
import com.vaadin.experimental.FeatureFlags;
35+
import com.vaadin.flow.component.Component;
36+
import com.vaadin.flow.dom.Element;
3037
import com.vaadin.flow.internal.BrowserLiveReload;
3138
import com.vaadin.flow.server.VaadinContext;
39+
import com.vaadin.flow.server.VaadinSession;
40+
import com.vaadin.flow.server.startup.ApplicationConfiguration;
3241
import com.vaadin.pro.licensechecker.BuildType;
3342
import com.vaadin.pro.licensechecker.LicenseChecker;
43+
import com.vaadin.pro.licensechecker.LocalProKey;
3444
import com.vaadin.pro.licensechecker.Product;
3545

36-
import org.atmosphere.cpr.AtmosphereResource;
37-
import org.slf4j.Logger;
38-
import org.slf4j.LoggerFactory;
39-
4046
import elemental.json.Json;
4147
import elemental.json.JsonObject;
4248

@@ -62,6 +68,8 @@ public class DebugWindowConnection implements BrowserLiveReload {
6268

6369
private final ObjectMapper objectMapper = new ObjectMapper();
6470

71+
private IdeIntegration ideIntegration;
72+
6573
static {
6674
IDENTIFIER_CLASSES.put(Backend.JREBEL, Collections.singletonList(
6775
"org.zeroturnaround.jrebel.vaadin.JRebelClassEventListener"));
@@ -79,6 +87,8 @@ public class DebugWindowConnection implements BrowserLiveReload {
7987
DebugWindowConnection(ClassLoader classLoader, VaadinContext context) {
8088
this.classLoader = classLoader;
8189
this.context = context;
90+
this.ideIntegration = new IdeIntegration(
91+
ApplicationConfiguration.get(context));
8292
}
8393

8494
@Override
@@ -126,6 +136,10 @@ public void onConnect(AtmosphereResource resource) {
126136
.get(context).getFeatures().stream()
127137
.filter(feature -> !feature.equals(FeatureFlags.EXAMPLE))
128138
.collect(Collectors.toList())));
139+
140+
if (LocalProKey.get() != null) {
141+
send(resource, "vaadin-dev-tools-code-ok", null);
142+
}
129143
}
130144

131145
private void send(AtmosphereResource resource, String command,
@@ -166,6 +180,7 @@ public void reload() {
166180
});
167181
}
168182

183+
@SuppressWarnings("FutureReturnValueIgnored")
169184
@Override
170185
public void onMessage(AtmosphereResource resource, String message) {
171186
if (message.isEmpty()) {
@@ -174,15 +189,13 @@ public void onMessage(AtmosphereResource resource, String message) {
174189
}
175190
JsonObject json = Json.parse(message);
176191
String command = json.getString("command");
192+
JsonObject data = json.getObject("data");
177193
if ("setFeature".equals(command)) {
178-
JsonObject data = json.getObject("data");
179194
FeatureFlags.get(context).setEnabled(data.getString("featureId"),
180195
data.getBoolean("enabled"));
181196
} else if ("reportTelemetry".equals(command)) {
182-
JsonObject data = json.getObject("data");
183197
DevModeUsageStatistics.handleBrowserData(data);
184198
} else if ("checkLicense".equals(command)) {
185-
JsonObject data = json.getObject("data");
186199
String name = data.getString("name");
187200
String version = data.getString("version");
188201
Product product = new Product(name, version);
@@ -207,6 +220,25 @@ public void onMessage(AtmosphereResource resource, String message) {
207220
errorMessage);
208221
send(resource, "license-check-failed", pm);
209222
}
223+
} else if ("showComponentCreateLocation".equals(command)
224+
|| "showComponentAttachLocation".equals(command)) {
225+
int nodeId = (int) data.getNumber("nodeId");
226+
int uiId = (int) data.getNumber("uiId");
227+
VaadinSession session = VaadinSession.getCurrent();
228+
session.access(() -> {
229+
Element element = session.findElement(uiId, nodeId);
230+
Optional<Component> c = element.getComponent();
231+
if (c.isPresent()) {
232+
if ("showComponentCreateLocation".equals(command)) {
233+
ideIntegration.showComponentCreateInIde(c.get());
234+
} else {
235+
ideIntegration.showComponentAttachInIde(c.get());
236+
}
237+
} else {
238+
getLogger().error(
239+
"Only component locations are tracked. The given node id refers to an element and not a component");
240+
}
241+
});
210242
} else {
211243
getLogger().info("Unknown command from the browser: " + command);
212244
}
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import { css, html, LitElement, PropertyValues } from 'lit';
2+
import { customElement, property, query, state } from 'lit/decorators.js';
3+
import { ComponentReference, getComponents } from './component-util.js';
4+
import './shim.js';
5+
import { Shim } from './shim.js';
6+
import { popupStyles } from './vaadin-dev-tools.js';
7+
8+
/**
9+
* When active, shows a component picker that allows the user to select an element with a server side counterpart.
10+
*/
11+
@customElement('vaadin-dev-tools-component-picker')
12+
export class ComponentPicker extends LitElement {
13+
@property({ type: Boolean })
14+
active: boolean = false;
15+
16+
@state()
17+
components: ComponentReference[] = [];
18+
@state()
19+
selected: number = 0;
20+
21+
highlighted?: HTMLElement;
22+
23+
@query('vaadin-dev-tools-shim')
24+
shim!: Shim;
25+
26+
static styles = [
27+
popupStyles,
28+
css`
29+
.component-picker-info {
30+
left: 1em;
31+
bottom: 1em;
32+
}
33+
34+
.component-picker-components-info {
35+
right: 3em;
36+
bottom: 1em;
37+
}
38+
39+
.component-picker-components-info .selected {
40+
font-weight: bold;
41+
}
42+
`
43+
];
44+
45+
connectedCallback() {
46+
super.connectedCallback();
47+
const globalStyles = new CSSStyleSheet();
48+
globalStyles.replaceSync(`
49+
.vaadin-dev-tools-highlight {
50+
outline: 1px solid red
51+
}`);
52+
53+
document.adoptedStyleSheets = [...document.adoptedStyleSheets, globalStyles];
54+
}
55+
render() {
56+
this.style.display = this.active ? 'block' : 'none';
57+
58+
return html`
59+
<vaadin-dev-tools-shim
60+
@keydown=${(e: KeyboardEvent) => {}}
61+
@shim-click=${this.shimClick}
62+
@shim-mousemove=${this.shimMove}
63+
@shim-keydown=${this.shimKeydown}
64+
></vaadin-dev-tools-shim>
65+
<div class="window popup component-picker-info">
66+
<div>
67+
<h3>Locate a component in source code</h3>
68+
<p>Use the mouse cursor to highligh components in the UI.</p>
69+
<p>Use arrow down/up to cycle through and highlight specific components under the cursor.</p>
70+
<p>
71+
Click the primary mouse button to open the corresponding source code line of the highlighted component in
72+
your IDE.
73+
</p>
74+
</div>
75+
</div>
76+
<div class="window popup component-picker-components-info">
77+
<div>
78+
${this.components.map(
79+
(component, index) =>
80+
html`<div class=${index === this.selected ? 'selected' : ''}>
81+
${component.element!.tagName.toLowerCase()}
82+
</div>`
83+
)}
84+
</div>
85+
</div>
86+
`;
87+
}
88+
89+
update(changedProperties: PropertyValues): void {
90+
super.update(changedProperties);
91+
if (changedProperties.has('selected') || changedProperties.has('components')) {
92+
this.highlight(this.components[this.selected]?.element);
93+
}
94+
if (changedProperties.has('active')) {
95+
const wasActive = changedProperties.get('active');
96+
const isActive = this.active;
97+
98+
if (!wasActive && isActive) {
99+
// Focus shim when created so that keyboard events go there
100+
requestAnimationFrame(() => this.shim.focus());
101+
} else if (wasActive && !isActive) {
102+
this.highlight(undefined);
103+
}
104+
}
105+
}
106+
shimKeydown(e: CustomEvent) {
107+
const keyEvent: KeyboardEvent = e.detail.originalEvent;
108+
if (keyEvent.key === 'Escape') {
109+
this.abort();
110+
e.stopPropagation();
111+
e.preventDefault();
112+
} else if (keyEvent.key === 'ArrowUp') {
113+
let selected = this.selected - 1;
114+
if (selected < 0) {
115+
selected = this.components.length - 1;
116+
}
117+
this.selected = selected;
118+
} else if (keyEvent.key === 'ArrowDown') {
119+
this.selected = (this.selected + 1) % this.components.length;
120+
} else if (keyEvent.key === 'Enter') {
121+
this.pickSelectedComponent();
122+
e.stopPropagation();
123+
e.preventDefault();
124+
}
125+
}
126+
shimMove(e: CustomEvent) {
127+
const targetElement = e.detail.target;
128+
129+
this.components = getComponents(targetElement);
130+
this.selected = this.components.length - 1;
131+
}
132+
shimClick(_e: CustomEvent) {
133+
this.pickSelectedComponent();
134+
}
135+
136+
abort() {
137+
this.dispatchEvent(new CustomEvent('component-picker-abort', {}));
138+
}
139+
140+
pickSelectedComponent() {
141+
const component = this.components[this.selected];
142+
this.dispatchEvent(
143+
new CustomEvent('component-picker-pick', {
144+
detail: { component: { nodeId: component.nodeId, uiId: component.uiId } }
145+
})
146+
);
147+
}
148+
149+
highlight(element: HTMLElement | undefined) {
150+
if (this.highlighted) {
151+
this.highlighted.classList.remove('vaadin-dev-tools-highlight');
152+
}
153+
this.highlighted = element;
154+
if (this.highlighted) {
155+
this.highlighted.classList.add('vaadin-dev-tools-highlight');
156+
}
157+
}
158+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
export type ComponentReference = {
2+
nodeId: number;
3+
uiId: number;
4+
element?: HTMLElement;
5+
};
6+
7+
export function getComponents(element: HTMLElement): ComponentReference[] {
8+
// Find all elements that are components
9+
const components = [];
10+
11+
while (element && element.parentNode) {
12+
const component = getComponent(element);
13+
if (component.nodeId !== -1) {
14+
if (component.element?.tagName.startsWith('FLOW-CONTAINER-')) {
15+
break;
16+
}
17+
components.push(component);
18+
}
19+
element = element.parentElement ? element.parentElement : ((element.parentNode as ShadowRoot).host as HTMLElement);
20+
}
21+
return components.reverse();
22+
}
23+
24+
function getComponent(element: HTMLElement): ComponentReference {
25+
const { clients } = (window as any).Vaadin.Flow;
26+
const appIds = Object.keys(clients);
27+
for (const appId of appIds) {
28+
const client = clients[appId];
29+
if (client.getNodeId) {
30+
const nodeId = client.getNodeId(element);
31+
if (nodeId >= 0) {
32+
return { nodeId, uiId: client.getUIId(), element };
33+
}
34+
}
35+
}
36+
return { nodeId: -1, uiId: -1, element: undefined };
37+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { css, html, LitElement } from 'lit';
2+
import { customElement } from 'lit/decorators.js';
3+
4+
/**
5+
* Blocks interaction with all elements on the page. Forwards mouse and key events as custom shim-* events.
6+
*/
7+
@customElement('vaadin-dev-tools-shim')
8+
export class Shim extends LitElement {
9+
highlighted?: HTMLElement;
10+
static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true };
11+
12+
static styles = [
13+
css`
14+
div {
15+
pointer-events: auto;
16+
background: rgba(255, 255, 255, 0);
17+
position: fixed;
18+
inset: 0px;
19+
z-index: 1000000;
20+
}
21+
`
22+
];
23+
render() {
24+
return html`<div
25+
tabindex="-1"
26+
@mousemove=${this.onMouseMove}
27+
@click=${this.onClick}
28+
@keydown=${this.onKeyDown}
29+
></div>`;
30+
}
31+
32+
onClick(e: MouseEvent) {
33+
const target = this.getTargetElement(e);
34+
this.dispatchEvent(new CustomEvent('shim-click', { detail: { target } }));
35+
}
36+
onMouseMove(e: MouseEvent) {
37+
const target = this.getTargetElement(e);
38+
this.dispatchEvent(new CustomEvent('shim-mousemove', { detail: { target } }));
39+
}
40+
onKeyDown(e: KeyboardEvent) {
41+
this.dispatchEvent(new CustomEvent('shim-keydown', { detail: { originalEvent: e } }));
42+
}
43+
44+
getTargetElement(e: MouseEvent): HTMLElement {
45+
this.style.display = 'none';
46+
const targetElement = document.elementFromPoint(e.clientX, e.clientY) as HTMLElement;
47+
this.style.display = '';
48+
49+
return targetElement;
50+
}
51+
}

0 commit comments

Comments
 (0)