Skip to content

Commit

Permalink
Better conversion from html attributes to react props (#130)
Browse files Browse the repository at this point in the history
* Disable react/prop-types lint rule

* Flesh out conversion from html attributes to react props

* Properly merge decorations/props with outputspecs

* Use CSSOM to parse style attributes

* Re-enable react/prop-types rule
  • Loading branch information
smoores-dev authored Sep 4, 2024
1 parent c32cc45 commit ff0afd1
Show file tree
Hide file tree
Showing 5 changed files with 258 additions and 68 deletions.
34 changes: 17 additions & 17 deletions docs/assets/index-e2175326.js → docs/assets/index-3279a106.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React-ProseMirror Demo</title>
<script type="module" crossorigin src="/react-prosemirror/assets/index-e2175326.js"></script>
<script type="module" crossorigin src="/react-prosemirror/assets/index-3279a106.js"></script>
<link rel="stylesheet" href="/react-prosemirror/assets/index-523693cd.css">
</head>
<body>
Expand Down
44 changes: 5 additions & 39 deletions src/components/ChildNodeViews.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import classnames from "classnames/dedupe";
import { Mark, Node } from "prosemirror-model";
import { Decoration, DecorationSource } from "prosemirror-view";
import React, {
Expand All @@ -14,6 +13,7 @@ import { ReactWidgetDecoration } from "../decorations/ReactWidgetType.js";
import { iterDeco } from "../decorations/iterDeco.js";
import { useEditorState } from "../hooks/useEditorState.js";
import { useReactKeys } from "../hooks/useReactKeys.js";
import { htmlAttrsToReactProps, mergeReactProps } from "../props.js";

import { MarkView } from "./MarkView.js";
import { NativeWidgetView } from "./NativeWidgetView.js";
Expand All @@ -23,57 +23,23 @@ import { TextNodeView } from "./TextNodeView.js";
import { TrailingHackView } from "./TrailingHackView.js";
import { WidgetView } from "./WidgetView.js";

function cssToStyles(css: string) {
const cssJson = `{"${css
.replace(/;? *$/, "")
.replace(/;+ */g, '","')
.replace(/: */g, '":"')}"}`;

const obj = JSON.parse(cssJson);

return Object.keys(obj).reduce((acc, key) => {
const camelCased = key.startsWith("--")
? key
: key.replace(/-[a-z]/g, (g) => g[1]?.toUpperCase() ?? "");
return { ...acc, [camelCased]: obj[key] };
}, {});
}

export function wrapInDeco(reactNode: JSX.Element | string, deco: Decoration) {
const {
nodeName,
class: className,
style: css,
contenteditable: contentEditable,
spellcheck: spellCheck,
...attrs
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} = (deco as any).type.attrs;

const props = htmlAttrsToReactProps(attrs);

// We auto-wrap text nodes in spans so that we can apply attributes
// and styles, but we want to avoid double-wrapping the same
// text node
if (nodeName || typeof reactNode === "string") {
return createElement(
nodeName ?? "span",
{
className,
contentEditable,
spellCheck,
style: css && cssToStyles(css),
...attrs,
},
reactNode
);
return createElement(nodeName ?? "span", props, reactNode);
}

return cloneElement(reactNode, {
className: classnames(reactNode.props.className, className),
contentEditable,
spellCheck,
style: { ...reactNode.props.style, ...(css && cssToStyles(css)) },
...attrs,
});
return cloneElement(reactNode, mergeReactProps(reactNode.props, props));
}

type ChildWidget = {
Expand Down
23 changes: 12 additions & 11 deletions src/components/OutputSpec.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { DOMOutputSpec } from "prosemirror-model";
import React, { ReactNode, createElement, forwardRef } from "react";
import React, { HTMLProps, ReactNode, createElement, forwardRef } from "react";

type Props = {
import { htmlAttrsToReactProps, mergeReactProps } from "../props.js";

type Props = HTMLProps<HTMLElement> & {
outputSpec: DOMOutputSpec;
children?: ReactNode;
};

const ForwardedOutputSpec = forwardRef(function OutputSpec(
{ outputSpec, children, ...initialProps }: Props,
const ForwardedOutputSpec = forwardRef<HTMLElement, Props>(function OutputSpec(
{ outputSpec, children, ...propOverrides }: Props,
ref
) {
if (typeof outputSpec === "string") {
Expand All @@ -24,7 +26,10 @@ const ForwardedOutputSpec = forwardRef(function OutputSpec(
const tagName = tagSpec.replace(" ", ":");
const attrs = outputSpec[1];

const props: Record<string, unknown> = { ...initialProps, ref };
let props: HTMLProps<HTMLElement> = {
ref,
...propOverrides,
};
let start = 1;
if (
attrs &&
Expand All @@ -33,13 +38,9 @@ const ForwardedOutputSpec = forwardRef(function OutputSpec(
!Array.isArray(attrs)
) {
start = 2;
for (const name in attrs)
if (attrs[name] != null) {
const attrName =
name === "class" ? "className" : name.replace(" ", ":");
props[attrName] = attrs[name];
}
props = mergeReactProps(htmlAttrsToReactProps(attrs), propOverrides);
}

const content: ReactNode[] = [];
for (let i = start; i < outputSpec.length; i++) {
const child = outputSpec[i] as DOMOutputSpec | 0;
Expand Down
223 changes: 223 additions & 0 deletions src/props.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import cx from "classnames";
import { HTMLProps } from "react";

export function kebabCaseToCamelCase(str: string) {
return str.replaceAll(/-[a-z]/g, (g) => g[1]?.toUpperCase() ?? "");
}

/**
* Converts a CSS style string to an object
* that can be passed to a React component's
* `style` prop.
*/
export function cssToStyles(css: string) {
const stylesheet = new CSSStyleSheet();
stylesheet.insertRule(`* { ${css} }`);

const insertedRule = stylesheet.cssRules[0] as CSSStyleRule;
const declaration = insertedRule.style;
const styles: Record<string, string> = {};

for (let i = 0; i < declaration.length; i++) {
const property = declaration.item(i);
const value = declaration.getPropertyValue(property);
const camelCasePropertyName = kebabCaseToCamelCase(property);
styles[camelCasePropertyName] = value;
}

return styles;
}

/**
* Merges two sets of React props. Class names
* will be concatenated and style objects
* will be merged.
*/
export function mergeReactProps(
a: HTMLProps<HTMLElement>,
b: HTMLProps<HTMLElement>
) {
return {
...a,
...b,
className: cx(a.className, b.className),
style: {
...a.style,
...b.style,
},
};
}

/**
* Given a record of HTML attributes, returns tho
* equivalent React props.
*/
export function htmlAttrsToReactProps(
attrs: Record<string, string>
): HTMLProps<HTMLElement> {
const props: Record<string, unknown> = {};
for (const [attrName, attrValue] of Object.entries(attrs)) {
switch (attrName.toLowerCase()) {
case "class": {
props.className = attrValue;
break;
}
case "style": {
props.style = cssToStyles(attrValue);
break;
}
case "autocapitalize": {
props.autoCapitalize = attrValue;
break;
}
case "contenteditable": {
props.contentEditable = attrValue != null;
break;
}
case "draggable": {
props.draggable = attrValue != null;
break;
}
case "enterkeyhint": {
props.enterKeyHint = attrValue;
break;
}
case "for": {
props.htmlFor = attrValue;
break;
}
case "hidden": {
props.hidden = attrValue;
break;
}
case "inputmode": {
props.inputMode = attrValue;
break;
}
case "itemprop": {
props.itemProp = attrValue;
break;
}
case "spellcheck": {
if (attrValue === "" || attrValue === "true") {
props.spellCheck = true;
break;
}
if (attrValue === "false") {
props.spellCheck = false;
}
props.spellCheck = null;
break;
}
case "tabindex": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.tabIndex = numValue;
}
break;
}
case "autocomplete": {
props.autoComplete = attrValue;
break;
}
case "autofocus": {
props.autoFocus = attrValue != null;
break;
}
case "formaction": {
props.formAction = attrValue;
break;
}
case "formenctype": {
props.formEnctype = attrValue;
break;
}
case "formmethod": {
props.formMethod = attrValue;
break;
}
case "formnovalidate": {
props.formNoValidate = attrValue;
break;
}
case "formtarget": {
props.formTarget = attrValue;
break;
}
case "maxlength": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.maxLength = attrValue;
}
break;
}
case "minlength": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.minLength = attrValue;
}
break;
}
case "max": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.max = attrValue;
}
break;
}
case "min": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.min = attrValue;
}
break;
}
case "multiple": {
props.multiple = attrValue != null;
break;
}
case "readonly": {
props.readOnly = attrValue != null;
break;
}
case "required": {
props.required = attrValue != null;
break;
}
case "size": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.size = attrValue;
}
break;
}
case "step": {
if (attrValue === "any") {
props.step = attrValue;
break;
}
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue) && numValue > 0) {
props.step = attrValue;
}
break;
}
case "disabled": {
props.disabled = attrValue != null;
break;
}
case "rows": {
const numValue = parseInt(attrValue, 10);
if (!Number.isNaN(numValue)) {
props.rows = attrValue;
}
break;
}
default: {
props[attrName] = attrValue;
break;
}
}
}
return props;
}

0 comments on commit ff0afd1

Please sign in to comment.