Skip to content
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

Implement code and pre blocks support on web #456

Open
wants to merge 91 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
f853061
Add refactor changes
Skalakid Jun 25, 2024
c4108c1
Fix parserUtils
Skalakid Jun 25, 2024
38693c4
Add tree building when creating markdown HTML structure
Skalakid Jun 26, 2024
6a1eaf1
Refactor function and type names
Skalakid Jun 26, 2024
75d6afd
Fix TS errors
Skalakid Jun 26, 2024
db68b78
Update parser structure
Skalakid Jun 26, 2024
31711ab
Move BrowserUtils into an object
Skalakid Jun 26, 2024
cab8ca7
Move utils to separate folder
Skalakid Jun 26, 2024
2f829cc
Add block utils
Skalakid Jun 26, 2024
b9b2984
Move functions from above the web component to utils
Skalakid Jun 26, 2024
3fbc456
Fix unit tests
Skalakid Jun 27, 2024
d74e0e4
Fix cursor positioning bugs
Skalakid Jun 28, 2024
220395b
Remove scrollCursorIntoView function
Skalakid Jun 28, 2024
4d95382
Rename variable names
Skalakid Jun 28, 2024
907c73b
Replace textContent with ref value
Skalakid Jun 28, 2024
1017ebc
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jun 28, 2024
1f1fefd
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jul 1, 2024
ff41dd7
Fix crashes and cursor positioning in E/App
Skalakid Jul 1, 2024
d1d8a49
Fix copying and pasting text with markdown
Skalakid Jul 1, 2024
153ead8
Fix pasting text starting with newlines
Skalakid Jul 1, 2024
ea6aad8
Fix errors when replacing text
Skalakid Jul 2, 2024
87953bb
Fix HTML injestions and pasted text parsing
Skalakid Jul 2, 2024
3d30621
Fix paste text trimming condiftion
Skalakid Jul 2, 2024
471f53a
Fix cutting text
Skalakid Jul 2, 2024
92a224c
Change handlePaste logic to fix newlines in pasted text
Skalakid Jul 2, 2024
c14add4
Fix cursor positioning when undoing/redoing previously pasted text
Skalakid Jul 2, 2024
e9d8ec3
Fix text coloring
Skalakid Jul 2, 2024
e24d259
Add review changes
Skalakid Jul 3, 2024
092775d
Move updateTextColor function
Skalakid Jul 3, 2024
a0c1dfa
Fix cursor positioning when changing text and styles at the same time
Skalakid Jul 3, 2024
d04ad32
Fix newlines on FireFox
Skalakid Jul 3, 2024
63de148
Fix cursor position value update when entering newline inside codeblock
Skalakid Jul 3, 2024
f06d10f
Fix removing characters when cursor is at the beginning of the line o…
Skalakid Jul 3, 2024
34eabe2
Fix writing in empty line on Firefox
Skalakid Jul 3, 2024
a52e3f5
Fix cursor position value on Cmd+A on FireFox
Skalakid Jul 3, 2024
b5515cf
Fix getting value in e2e tests
Skalakid Jul 4, 2024
5a043a3
Fix input e2e tests
Skalakid Jul 4, 2024
5a1dae2
Fix style e2e tests
Skalakid Jul 4, 2024
60f4f4b
Fix text manipulation e2e tests
Skalakid Jul 4, 2024
55e78b4
Update checkCursorPosition function in e2e tests
Skalakid Jul 4, 2024
8a0a7be
Update checkCursorPosition function in e2e tests
Skalakid Jul 4, 2024
96a9b5c
Fix cursor position after redoing pasted text
Skalakid Jul 5, 2024
8c85473
Merge branch '@Skalakid/web-parser-refactor' of github.com:Expensify/…
Skalakid Jul 5, 2024
401febe
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jul 5, 2024
862e74a
Fix e2e tests on CI/CD
Skalakid Jul 5, 2024
0580f45
Uncomment undo test
Skalakid Jul 5, 2024
6682c9d
Fix TS errors
Skalakid Jul 5, 2024
8165fb9
Change line merging funciton
Skalakid Jul 5, 2024
9e2b943
Fix selection event sending on paste
Skalakid Jul 5, 2024
0f5b86a
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jul 8, 2024
5f369ec
Fix scrolling cursor into view on Safari browser
Skalakid Jul 8, 2024
7cdaf9a
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jul 9, 2024
6bada78
Enhance cursor positioning on input
Skalakid Jul 9, 2024
d9c097d
Merge branch 'main' into @Skalakid/web-parser-refactor
Skalakid Jul 10, 2024
309bccf
Fix diacritics after CMD+A
Skalakid Jul 10, 2024
90d2ea3
Fix autocorrect cursor positioning
Skalakid Jul 10, 2024
111fd6b
Fix deleting codeBlock lines with CMD+backspace
Skalakid Jul 10, 2024
d14f4ba
Fix text color on undo/redo
Skalakid Jul 10, 2024
82d58ca
Fix removing last letter from the line
Skalakid Jul 10, 2024
2b9e56a
Fix cursor position when replacing text with the same text
Skalakid Jul 11, 2024
5861a21
Change parseInnerHTMLToText function
Skalakid Jul 15, 2024
68ae9be
Fix input behavior when interracting with display: block element
Skalakid Jul 15, 2024
0bc882a
Fix getTreeNodeByIndex function
Skalakid Jul 16, 2024
cc8e307
Fix replacing whole content of the input
Skalakid Jul 16, 2024
3da3989
Fix set cursor position when content changes
Skalakid Jul 16, 2024
ccb251e
Fix removing selection on paste
Skalakid Jul 16, 2024
e759170
Fix set cursor position on paste
Skalakid Jul 16, 2024
4db4441
Fix dissapearing cursor bug
Skalakid Jul 16, 2024
0480cb8
Fix pasting text into empty input
Skalakid Jul 16, 2024
5faac50
Fix newline deletion
Skalakid Jul 17, 2024
14d0eed
Improve parseInnerHTMLToText function and fix pasted text correct val…
Skalakid Jul 18, 2024
0c204f5
Remove buildTree function
Skalakid Jul 18, 2024
de12aca
Fix tests
Skalakid Jul 18, 2024
8648205
Replacing text by text cursor position
Skalakid Jul 19, 2024
eb1502a
Fix cursor positioning on custom text pasting (E/App)
Skalakid Jul 19, 2024
3486303
Add function comments
Skalakid Jul 19, 2024
fd2be10
feat: code block background with proper handling
BartoszGrajdek Jul 25, 2024
df04ba0
feat: adjust styles for background width
BartoszGrajdek Jul 25, 2024
3958bc3
feat: support for custom styles
BartoszGrajdek Jul 29, 2024
c57b91f
fix: refactor stylesheet handling
BartoszGrajdek Aug 21, 2024
07ce864
chore: resolve merge conflicts
BartoszGrajdek Sep 12, 2024
9485690
feat: improve styling
BartoszGrajdek Sep 19, 2024
b5a09d6
chore: resolve merge conflicts
BartoszGrajdek Sep 19, 2024
5bea3f1
fix: paddings & autocorrect
BartoszGrajdek Oct 1, 2024
5eb25b3
chore: resolve merge conflicts
BartoszGrajdek Oct 1, 2024
457ea25
feat: add support for vertical & horizontal padding
BartoszGrajdek Oct 1, 2024
561e0ec
fix: jumping background
BartoszGrajdek Oct 14, 2024
6f1c32f
chore: merge main
BartoszGrajdek Oct 14, 2024
e54929e
fix: background issues
BartoszGrajdek Oct 17, 2024
6379bb5
fix: cursor positioning
BartoszGrajdek Oct 28, 2024
a7fc650
fix: background sizing
BartoszGrajdek Oct 30, 2024
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
2 changes: 1 addition & 1 deletion parser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ function parseTreeToTextAndRanges(tree: StackItem): [string, MarkdownRange[]] {
} else if (node.tag === '<br />') {
text += '\n';
} else if (node.tag.startsWith('<pre')) {
appendSyntax('```');
appendSyntax(`\`\`\`${unescapeText(node.tag.match(/new-line-char="([^"]*)"/)![1]!)}`);
const content = node.children.join('').replaceAll('&#32;', ' ');
addChildrenWithStyle(content, 'pre');
appendSyntax('```');
Expand Down
13 changes: 10 additions & 3 deletions src/MarkdownTextInput.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {
TextInputContentSizeChangeEventData,
GestureResponderEvent,
} from 'react-native';
import React, {useEffect, useRef, useCallback, useMemo, useLayoutEffect} from 'react';
import React, {useEffect, useRef, useCallback, useMemo, useLayoutEffect, useState} from 'react';
import type {CSSProperties, MutableRefObject, ReactEventHandler, FocusEventHandler, MouseEvent, KeyboardEvent, SyntheticEvent, ClipboardEventHandler, TouchEvent} from 'react';
import {StyleSheet} from 'react-native';
import {updateInputStructure} from './web/utils/parserUtils';
Expand All @@ -21,8 +21,9 @@ import {getCurrentCursorPosition, removeSelection, setCursorPosition} from './we
import './web/MarkdownTextInput.css';
import type {MarkdownStyle} from './MarkdownTextInputDecoratorViewNativeComponent';
import {getElementHeight, getPlaceholderValue, isEventComposing, normalizeValue, parseInnerHTMLToText} from './web/utils/inputUtils';
import {parseToReactDOMStyle, processMarkdownStyle} from './web/utils/webStyleUtils';
import {parseToReactDOMStyle, configureCustomWebStylesheet, handleCustomStyles, idGenerator, processMarkdownStyle} from './web/utils/webStyleUtils';
import {forceRefreshAllImages} from './web/inputElements/inlineImage';
import type {PartialMarkdownStyle} from './styleUtils';
import type {InlineImagesInputProps} from './commonTypes';

require('../parser/react-native-live-markdown-parser.js');
Expand Down Expand Up @@ -60,6 +61,7 @@ let focusTimeout: NodeJS.Timeout | null = null;
type MarkdownTextInputElement = HTMLDivElement &
HTMLInputElement & {
tree: TreeNode;
uniqueId: string;
selection: Selection;
};

Expand Down Expand Up @@ -112,7 +114,7 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
const divRef = useRef<MarkdownTextInputElement | null>(null);
const currentlyFocusedField = useRef<HTMLDivElement | null>(null);
const contentSelection = useRef<Selection | null>(null);
const className = `react-native-live-markdown-input-${multiline ? 'multiline' : 'singleline'}`;
const [className, setClassName] = useState(`react-native-live-markdown-input-${multiline ? 'multiline' : 'singleline'}`);
const history = useRef<InputHistory>();
const dimensions = useRef<Dimensions | null>(null);
const pasteContent = useRef<string | null>(null);
Expand Down Expand Up @@ -684,6 +686,11 @@ const MarkdownTextInput = React.forwardRef<TextInput, MarkdownTextInputProps>(
if (autoFocus) {
divRef.current.focus();
}

configureCustomWebStylesheet();
divRef.current.uniqueId = idGenerator.next().value as string;
setClassName(`${className} ${divRef.current.uniqueId}`);
handleCustomStyles(divRef.current, markdownStyle as PartialMarkdownStyle);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down
10 changes: 10 additions & 0 deletions src/MarkdownTextInputDecoratorViewNativeComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,22 @@ interface MarkdownStyle {
fontSize: Float;
color: ColorValue;
backgroundColor: ColorValue;
borderColor: ColorValue;
borderWidth: Float;
borderRadius: Float;
borderStyle: string;
padding: Float;
};
pre: {
fontFamily: string;
fontSize: Float;
color: ColorValue;
backgroundColor: ColorValue;
borderColor: string;
borderRadius: Float;
padding: Float;
paddingVertical?: Float;
paddingHorizontal?: Float;
};
mentionHere: {
color: ColorValue;
Expand Down
13 changes: 12 additions & 1 deletion src/styleUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,16 @@ function makeDefaultMarkdownStyle(): MarkdownStyle {
fontSize: 20,
color: 'black',
backgroundColor: 'lightgray',
borderColor: 'gray',
borderWidth: 1,
borderRadius: 4,
borderStyle: 'solid',
padding: 0,
},
pre: {
borderColor: 'gray',
borderRadius: 4,
padding: 2,
fontFamily: FONT_FAMILY_MONOSPACE,
fontSize: 20,
color: 'black',
Expand Down Expand Up @@ -89,7 +97,10 @@ function mergeMarkdownStyleWithDefault(input: PartialMarkdownStyle | undefined):
return output;
}

function parseStringWithUnitToNumber(value: string | null): number {
function parseStringWithUnitToNumber(value: string | number | null): number {
if (typeof value === 'number') {
return value;
}
return value ? parseInt(value.replace('px', ''), 10) : 0;
}

Expand Down
26 changes: 25 additions & 1 deletion src/web/MarkdownTextInput.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
display: none;
}

.react-native-live-markdown-input-singleline span[data-type="text"] {
.react-native-live-markdown-input-singleline span[data-type='text'] {
vertical-align: middle;
}

Expand All @@ -29,6 +29,30 @@
content: attr(placeholder);
}

*[data-type='pre']::before {
margin: 0;
display: block;
color: transparent;
border: 1px solid grey;
content: attr(data-content);
position: absolute;
z-index: -1;
left: 0;
box-sizing: border-box;
}

*[data-type='line'] *[data-type='syntax']:has(+ *[data-type='pre']) {
display: grid;
}

*[data-type='line'] *[data-type='syntax']:has(+ *[data-type='pre']) > *:last-child {
display: none;
}

*[data-type='line'] *[data-type='pre'] + *[data-type='syntax'] {
display: grid;
}

@keyframes react-native-live-markdown-spin {
0% {
transform: rotate(0deg);
Expand Down
34 changes: 30 additions & 4 deletions src/web/utils/blockUtils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import type {InlineImagesInputProps} from '../../commonTypes';
import type {MarkdownTextInputElement} from '../../MarkdownTextInput.web';
import type {InlineImagesInputProps, MarkdownRange} from '../../commonTypes';
import {parseStringWithUnitToNumber} from '../../styleUtils';
import type {PartialMarkdownStyle} from '../../styleUtils';
import {addInlineImagePreview} from '../inputElements/inlineImage';
import type {MarkdownRange} from './parserUtils';
import type {NodeType, TreeNode} from './treeUtils';

function addStyleToBlock(targetElement: HTMLElement, type: NodeType, markdownStyle: PartialMarkdownStyle) {
const node = targetElement;

const defaultPrePadding = markdownStyle.pre?.padding ?? 2;
const preHorizontalPadding = parseStringWithUnitToNumber(markdownStyle.pre?.paddingHorizontal ?? defaultPrePadding).toString();
const preVerticalPadding = parseStringWithUnitToNumber(markdownStyle.pre?.paddingVertical ?? defaultPrePadding).toString();

switch (type) {
case 'line':
Object.assign(node.style, {
Expand Down Expand Up @@ -44,10 +51,21 @@ function addStyleToBlock(targetElement: HTMLElement, type: NodeType, markdownSty
});
break;
case 'code':
Object.assign(node.style, markdownStyle.code);
Object.assign(node.style, {...markdownStyle.code, lineHeight: 1.5});
break;
case 'pre':
Object.assign(node.style, markdownStyle.pre);
Object.assign(node.style, {
...markdownStyle.pre,
backgroundColor: 'transparent',
padding: 0,
});
Object.assign((node.parentNode as HTMLElement).style, {
padding: `${preVerticalPadding}px ${preHorizontalPadding}px`,
position: 'relative',
width: 'fit-content',
maxWidth: '100%',
boxSizing: 'border-box',
});
break;

case 'blockquote':
Expand Down Expand Up @@ -110,4 +128,12 @@ function extendBlockStructure(
return targetNode;
}

export {addStyleToBlock, extendBlockStructure, isBlockMarkdownType, getFirstBlockMarkdownRange};
function getTopParentTreeNode(node: TreeNode) {
let currentParentNode = node.parentNode;
while (currentParentNode && ['text', 'br', 'line', 'syntax'].includes(currentParentNode.parentNode?.type || '')) {
currentParentNode = currentParentNode?.parentNode || null;
}
return currentParentNode;
}

export {addStyleToBlock, extendBlockStructure, isBlockMarkdownType, getFirstBlockMarkdownRange, getTopParentTreeNode};
12 changes: 10 additions & 2 deletions src/web/utils/cursorUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {MarkdownTextInputElement} from '../../MarkdownTextInput.web';
import {getTopParentTreeNode} from './blockUtils';
import {findHTMLElementInTree, getTreeNodeByIndex} from './treeUtils';
import type {TreeNode} from './treeUtils';

Expand All @@ -17,8 +18,15 @@ function setCursorPosition(target: MarkdownTextInputElement, startIndex: number,
const range = document.createRange();
range.selectNodeContents(target);

const startTreeNode = getTreeNodeByIndex(target.tree, start);
const endTreeNode = end && startTreeNode && (end < startTreeNode.start || end >= startTreeNode.start + startTreeNode.length) ? getTreeNodeByIndex(target.tree, end) : startTreeNode;
let startTreeNode = getTreeNodeByIndex(target.tree, start);
let endTreeNode = end && startTreeNode && (end < startTreeNode.start || end >= startTreeNode.start + startTreeNode.length) ? getTreeNodeByIndex(target.tree, end) : startTreeNode;

const parentLine = startTreeNode?.type === 'br' && getTopParentTreeNode(startTreeNode);
if (parentLine && parentLine?.childNodes?.some((e) => e.type === 'pre')) {
startTreeNode = getTreeNodeByIndex(target.tree, start - 1);
endTreeNode = startTreeNode;
}

if (!startTreeNode || !endTreeNode) {
console.error('Invalid start or end tree node');
return;
Expand Down
4 changes: 2 additions & 2 deletions src/web/utils/inputUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {CSSProperties} from 'react';
import type {MarkdownTextInputElement} from '../../MarkdownTextInput.web';
import type {HTMLMarkdownElement, MarkdownTextInputElement} from '../../MarkdownTextInput.web';

const ZERO_WIDTH_SPACE = '\u200B';

Expand Down Expand Up @@ -37,7 +37,7 @@ function normalizeValue(value: string) {
}

// Parses the HTML structure of a MarkdownTextInputElement to a plain text string. Used for getting the correct value of the input element.
function parseInnerHTMLToText(target: MarkdownTextInputElement, inputType: string, cursorPosition: number): string {
function parseInnerHTMLToText(target: MarkdownTextInputElement | HTMLMarkdownElement, inputType: string, cursorPosition: number): string {
// Returns the parent of a given node that is higher in the hierarchy and is of a different type than 'text', 'br' or 'line'
function getTopParentNode(node: ChildNode) {
let currentParentNode = node.parentNode;
Expand Down
11 changes: 7 additions & 4 deletions src/web/utils/parserUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import {addNodeToTree, createRootTreeNode, updateTreeElementRefs} from './treeUt
import type {NodeType, TreeNode} from './treeUtils';
import type {PartialMarkdownStyle} from '../../styleUtils';
import {getCurrentCursorPosition, moveCursorToEnd, setCursorPosition} from './cursorUtils';
import {handleCustomStyles} from './webStyleUtils';
import {addStyleToBlock, extendBlockStructure, getFirstBlockMarkdownRange, isBlockMarkdownType} from './blockUtils';
import type {InlineImagesInputProps, MarkdownRange} from '../../commonTypes';
import type {InlineImagesInputProps, MarkdownRange, MarkdownType} from '../../commonTypes';
import {getAnimationCurrentTimes, updateAnimationsTime} from './animationUtils';

type Paragraph = {
Expand Down Expand Up @@ -217,13 +218,12 @@ function parseRangesToHTMLNodes(
// create markdown span element
const span = document.createElement('span') as HTMLMarkdownElement;
span.setAttribute('data-type', range.type);
const spanNode = appendNode(span, currentParentNode, range.type, range.length);

if (!disableInlineStyles) {
addStyleToBlock(span, range.type, markdownStyle);
}

const spanNode = appendNode(span, currentParentNode, range.type, range.length);

if (isMultiline && !disableInlineStyles && currentInput) {
currentParentNode = extendBlockStructure(currentInput, currentParentNode, range, lineMarkdownRanges, text, markdownStyle, inlineImagesProps);
}
Expand Down Expand Up @@ -301,7 +301,7 @@ function updateInputStructure(
if (text) {
const {dom, tree} = parseRangesToHTMLNodes(text, markdownRanges, isMultiline, markdownStyle, false, targetElement, inlineImagesProps);

if (shouldForceDOMUpdate || targetElement.innerHTML !== dom.innerHTML) {
if (shouldForceDOMUpdate || targetElement.innerHTML.replaceAll(/ data-content="([^"]*)"/g, '') !== dom.innerHTML) {
const animationTimes = getAnimationCurrentTimes(targetElement);
targetElement.innerHTML = '';
targetElement.innerText = '';
Expand All @@ -317,7 +317,10 @@ function updateInputStructure(
targetElement.tree = createRootTreeNode(targetElement);
}

handleCustomStyles(target, markdownStyle);
return {text, cursorPosition: cursorPosition || 0};
}

export {updateInputStructure, parseRangesToHTMLNodes};

export type {MarkdownRange, MarkdownType};
5 changes: 5 additions & 0 deletions src/web/utils/treeUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {HTMLMarkdownElement} from '../../MarkdownTextInput.web';
import type {MarkdownRange, MarkdownType} from '../../commonTypes';
import {parseInnerHTMLToText} from './inputUtils';

type NodeType = MarkdownType | 'line' | 'text' | 'br' | 'block' | 'root';

Expand Down Expand Up @@ -74,6 +75,10 @@ function updateTreeElementRefs(treeRoot: TreeNode, element: HTMLMarkdownElement)
if (currentElement) {
node.element = currentElement;
}

if (currentElement?.dataset.type === 'pre') {
currentElement.setAttribute('data-content', parseInnerHTMLToText(currentElement, '', 0));
}
}

return treeRoot;
Expand Down
Loading
Loading