Skip to content

fix: stop cursor jump with ampersands #139

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
28 changes: 5 additions & 23 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 @@ -21,12 +21,13 @@
"autoprefixer": "10.4.14",
"eslint": "8.41.0",
"eslint-config-next": "13.4.4",
"fast-deep-equal": "^3.1.3",
"next": "13.4.4",
"pdfjs": "^2.5.0",
"pdfjs-dist": "^3.7.107",
"postcss": "8.4.24",
"prop-types": "^15.8.1",
"react": "18.2.0",
"react-contenteditable": "^3.3.7",
"react-dom": "18.2.0",
"react-frame-component": "^5.2.6",
"react-redux": "^8.0.7",
Expand Down
161 changes: 161 additions & 0 deletions src/app/components/ResumeForm/Form/ContentEditable.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import * as React from "react";
import deepEqual from "fast-deep-equal";
import * as PropTypes from "prop-types";

function normalizeHtml(str: string): string {
return (
str &&
str
.replace(/ |\u202F|\u00A0/g, " ")
.replace(/<br \/>/g, "<br>")
.replaceAll("&amp;", "&")
);
}

function replaceCaret(el: HTMLElement) {
// Place the caret at the end of the element
const target = document.createTextNode("");
el.appendChild(target);
// do not move caret if element was not focused
const isTargetFocused = document.activeElement === el;
if (target !== null && target.nodeValue !== null && isTargetFocused) {
var sel = window.getSelection();
if (sel !== null) {
var range = document.createRange();
range.setStart(target, target.nodeValue.length);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
if (el instanceof HTMLElement) el.focus();
}
}

/**
* A simple component for an html element with editable contents.
*/
export class ContentEditable extends React.Component<Props> {
lastHtml: string = this.props.html;
el: any =
typeof this.props.innerRef === "function"
? { current: null }
: React.createRef<HTMLElement>();

getEl = () =>
(this.props.innerRef && typeof this.props.innerRef !== "function"
? this.props.innerRef
: this.el
).current;

render() {
const { tagName, html, innerRef, ...props } = this.props;

// eslint-disable-next-line react/no-danger-with-children
return React.createElement(
tagName || "div",
{
...props,
ref:
typeof innerRef === "function"
? (current: HTMLElement) => {
innerRef(current);
this.el.current = current;
}
: innerRef || this.el,
onInput: this.emitChange,
onBlur: this.props.onBlur || this.emitChange,
onKeyUp: this.props.onKeyUp || this.emitChange,
onKeyDown: this.props.onKeyDown || this.emitChange,
contentEditable: !this.props.disabled,
dangerouslySetInnerHTML: { __html: html },
},
this.props.children
);
}

shouldComponentUpdate(nextProps: Props): boolean {
const { props } = this;
const el = this.getEl();

// We need not rerender if the change of props simply reflects the user's edits.
// Rerendering in this case would make the cursor/caret jump

// Rerender if there is no element yet... (somehow?)
if (!el) return true;

// ...or if html really changed... (programmatically, not by user edit)
if (normalizeHtml(nextProps.html) !== normalizeHtml(el.innerHTML)) {
console.log(1);
return true;
}

// Handle additional properties
return (
props.disabled !== nextProps.disabled ||
props.tagName !== nextProps.tagName ||
props.className !== nextProps.className ||
props.innerRef !== nextProps.innerRef ||
props.placeholder !== nextProps.placeholder ||
!deepEqual(props.style, nextProps.style)
);
}

componentDidUpdate() {
const el = this.getEl();
if (!el) return;

// Perhaps React (whose VDOM gets outdated because we often prevent
// rerendering) did not update the DOM. So we update it manually now.
if (this.props.html !== el.innerHTML) {
el.innerHTML = this.props.html;
}
this.lastHtml = this.props.html;
replaceCaret(el);
}

emitChange = (originalEvt: React.SyntheticEvent<any>) => {
const el = this.getEl();
if (!el) return;

const html = el.innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
// Clone event with Object.assign to avoid
// "Cannot assign to read only property 'target' of object"
const evt = Object.assign({}, originalEvt, {
target: {
value: html,
},
});
this.props.onChange(evt);
}
this.lastHtml = html;
};

static propTypes = {
html: PropTypes.string.isRequired,
onChange: PropTypes.func,
disabled: PropTypes.bool,
tagName: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
innerRef: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
};
}

export type ContentEditableEvent = React.SyntheticEvent<any, Event> & {
target: { value: string };
};
type Modify<T, R> = Pick<T, Exclude<keyof T, keyof R>> & R;
type DivProps = Modify<
JSX.IntrinsicElements["div"],
{ onChange: (event: ContentEditableEvent) => void }
>;

export interface Props extends DivProps {
html: string;
disabled?: boolean;
tagName?: string;
className?: string;
style?: Object;
innerRef?: React.RefObject<HTMLElement> | Function;
}
2 changes: 1 addition & 1 deletion src/app/components/ResumeForm/Form/InputGroup.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState, useEffect } from "react";
import ContentEditable from "react-contenteditable";
import { useAutosizeTextareaHeight } from "lib/hooks/useAutosizeTextareaHeight";
import { ContentEditable } from "./ContentEditable";

interface InputProps<K extends string, V extends string | string[]> {
label: string;
Expand Down