Skip to content

feat: add event-debugging environment #167

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
Jun 16, 2020
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
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-toastify": "^6.0.5",
"react-virtualized-auto-sizer": "^1.0.2"
"react-virtualized-auto-sizer": "^1.0.2",
"react-window": "^1.8.5"
},
"devDependencies": {
"@babel/core": "^7.10.2",
Expand Down
10 changes: 7 additions & 3 deletions src/components/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@ import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Playground from './Playground';
import Layout from './Layout';
import Embedded from './Embedded';
import { ToastContainer } from 'react-toastify';
import DomEvents from './DomEvents';

function App() {
return (
<Router>
<Switch>
<Route path="/embed/">
<Route path="/embed">
<Embedded />
</Route>
<Route path="/events">
<Layout>
<DomEvents />
</Layout>
</Route>
<Route path="/">
<Layout>
<Playground />
<ToastContainer />
</Layout>
</Route>
</Switch>
Expand Down
209 changes: 209 additions & 0 deletions src/components/DomEvents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import React, { useRef, useCallback, useState } from 'react';

import Preview from './Preview';
import MarkupEditor from './MarkupEditor';
import usePlayground from '../hooks/usePlayground';
import state from '../lib/state';
import { eventMap } from '@testing-library/dom/dist/event-map';
import { VirtualScrollable } from './Scrollable';
import { FixedSizeList as List } from 'react-window';
import throttle from 'lodash.throttle';
import AutoSizer from 'react-virtualized-auto-sizer';
import IconButton from './IconButton';
import TrashcanIcon from './TrashcanIcon';
import EmptyStreetImg from '../images/EmptyStreetImg';

function onStateChange({ markup, query, result }) {
state.save({ markup, query });
state.updateTitle(result?.expression?.expression);
}

const initialValues = state.load() || {};

function targetToString() {
return [
this.tagName.toLowerCase(),
this.id && `#${this.id}`,
this.name && `[name="${this.name}"]`,
this.htmlFor && `[for="${this.htmlFor}"]`,
this.value && `[value="${this.value}"]`,
this.checked !== null && `[checked=${this.checked}]`,
]
.filter(Boolean)
.join('');
}

function getElementData(element) {
const value =
element.tagName === 'SELECT' && element.multiple
? element.selectedOptions.length > 0
? JSON.stringify(
Array.from(element.selectedOptions).map((o) => o.value),
)
: null
: element.value;

const hasChecked = element.type === 'checkbox' || element.type === 'radio';

return {
tagName: element.tagName.toLowerCase(),
id: element.id || null,
name: element.name || null,
htmlFor: element.htmlFor || null,
value: value || null,
checked: hasChecked ? !!element.checked : null,
toString: targetToString,
};
}

function addLoggingEvents(node, log) {
function createEventLogger(eventType) {
return function logEvent(event) {
if (event.target === event.currentTarget) {
return;
}

log({
event: eventType,
target: getElementData(event.target),
});
};
}

Object.keys(eventMap).forEach((name) => {
node.addEventListener(
name.toLowerCase(),
createEventLogger({ name, ...eventMap[name] }),
true,
);
});
}

function EventRecord({ index, style, data }) {
const { id, event, target } = data[index];

return (
<div
className={`w-full h-8 flex items-center text-sm ${
index % 2 ? 'bg-gray-100' : ''
}`}
style={style}
>
<div className="p-2 flex-none w-16">{id}</div>

<div className="p-2 flex-none w-32">{event.EventType}</div>
<div className="p-2 flex-none w-32">{event.name}</div>

<div className="p-2 flex-none w-40">{target.tagName}</div>
<div className="p-2 flex-auto whitespace-no-wrap">
{target.toString()}
</div>
</div>
);
}

const noop = () => {};
function DomEvents() {
const [{ markup, result }, dispatch] = usePlayground({
onChange: onStateChange,
...initialValues,
});

const buffer = useRef([]);
const previewRef = useRef();
const listRef = useRef();

const [eventCount, setEventCount] = useState(0);

const reset = () => {
buffer.current = [];
setEventCount(0);
};

const flush = useCallback(
throttle(() => setEventCount(buffer.current.length), 16, {
leading: false,
}),
[setEventCount],
);

const setPreviewRef = useCallback((node) => {
previewRef.current = node;

if (!node) return;

addLoggingEvents(node, (event) => {
// insert at index 0
event.id = buffer.current.length;
buffer.current.splice(0, 0, event);
setTimeout(flush, 0);
});
}, []);

return (
<div className="flex flex-col h-auto md:h-full w-full">
<div className="editor markup-editor gap-4 md:gap-8 md:h-56 flex-auto grid-cols-1 md:grid-cols-2">
<div className="flex-auto relative h-56 md:h-full">
<MarkupEditor markup={markup} dispatch={dispatch} />
</div>

<div className="flex-auto h-56 md:h-full" ref={setPreviewRef}>
<Preview
markup={markup}
elements={result.elements}
accessibleRoles={result.accessibleRoles}
dispatch={noop}
variant="minimal"
/>
</div>
</div>

<div className="flex-none h-8" />

<div className="editor md:h-56 flex-auto overflow-hidden">
<div className="h-56 md:h-full w-full flex flex-col">
<div className="h-8 flex items-center w-full text-sm font-bold">
<div className="p-2 w-16">#</div>

<div className="p-2 w-32">type</div>
<div className="p-2 w-32">name</div>

<div className="p-2 w-40">element</div>
<div className="flex-auto p-2 flex justify-between">
<span>selector</span>
<IconButton title="clear event log" onClick={reset}>
<TrashcanIcon />
</IconButton>
</div>
</div>

<div className="flex-auto relative overflow-hidden">
{eventCount === 0 ? (
<div className="flex w-full h-full opacity-50 items-end justify-center">
<EmptyStreetImg height="80%" />
</div>
) : (
<AutoSizer>
{({ width, height }) => (
<List
ref={listRef}
height={height}
itemCount={eventCount}
itemData={buffer.current}
itemSize={32}
width={width}
outerElementType={VirtualScrollable}
>
{EventRecord}
</List>
)}
</AutoSizer>
)}
</div>
</div>
</div>
</div>
);
}

export default DomEvents;
3 changes: 2 additions & 1 deletion src/components/IconButton.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';

function IconButton({ children, variant, onClick, className }) {
function IconButton({ children, title, variant, onClick, className }) {
return (
<button
className={[
Expand All @@ -13,6 +13,7 @@ function IconButton({ children, variant, onClick, className }) {
.filter(Boolean)
.join(' ')}
onClick={onClick}
title={title}
>
{children}
</button>
Expand Down
3 changes: 3 additions & 0 deletions src/components/Layout.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import Header from './Header';
import Footer from './Footer';
import { ToastContainer } from 'react-toastify';

function Layout({ children }) {
return (
Expand All @@ -14,6 +15,8 @@ function Layout({ children }) {
<div className="flex-none">
<Footer />
</div>

<ToastContainer />
</div>
);
}
Expand Down
8 changes: 5 additions & 3 deletions src/components/Preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ function selectByCssPath(rootNode, cssPath) {
return rootNode?.querySelector(cssPath.toString().replace(/^body > /, ''));
}

function Preview({ markup, accessibleRoles, elements, dispatch }) {
function Preview({ markup, accessibleRoles, elements, dispatch, variant }) {
// Okay, listen up. `highlighted` can be a number of things, as I wanted to
// keep a single variable to represent the state. This to reduce bug count
// by creating out-of-sync states.
Expand Down Expand Up @@ -147,7 +147,7 @@ function Preview({ markup, accessibleRoles, elements, dispatch }) {
onMouseEnter={() => setHighlighted(true)}
onMouseLeave={() => setHighlighted(false)}
>
<div className="flex-auto relative overflow-hidden h-1">
<div className="flex-auto relative overflow-hidden">
<Scrollable>
<div
id="view"
Expand All @@ -162,7 +162,9 @@ function Preview({ markup, accessibleRoles, elements, dispatch }) {
</Scrollable>
</div>

<PreviewHint roles={roles} suggestion={suggestion} />
{variant !== 'minimal' && (
<PreviewHint roles={roles} suggestion={suggestion} />
)}
</div>
) : (
<div className="w-full h-full flex flex-col relative overflow-hidden">
Expand Down
Loading