Giter VIP home page Giter VIP logo

Comments (4)

sellmeadog avatar sellmeadog commented on June 30, 2024

I have a pretty simple use case, but require nested matching nonetheless. After playing around with react-native-parsed-text, it was easier to roll my own component that meets my specific needs. The entire component and pattern matching logic is shown below and its simplicity matches that of my use case but perhaps it can be used as inspiration to provide more comprehensive nested pattern matching.

import React, { FunctionComponent, useState } from 'react';
import { StyleProp, Text, TextProps, TextStyle } from 'react-native';

interface P9TextParserConfig {
  pattern: RegExp;
  style?: StyleProp<TextStyle>;
  transform?(text: string): string;
}

interface P9TextParseResult {
  match: string;
  style?: StyleProp<TextStyle>;
}

export interface P9ParsedTextProps extends TextProps {
  parsers: P9TextParserConfig[];
}

export const P9ParsedText: FunctionComponent<P9ParsedTextProps> = ({
  children,
  parsers,
  style: rootStyle,
  ...rest
}) => {
  const [parsed] = useState(parseText([{ match: children as string }], parsers, 0, []));

  return (
    <>
      <Text {...rest} style={rootStyle}>
        {parsed.map(({ match, style }, index) =>
          style ? (
            <Text key={index.toString()} style={[rootStyle, style]}>
              {match}
            </Text>
          ) : (
            match
          )
        )}
      </Text>
    </>
  );
};

function parseText(
  input: P9TextParseResult[],
  parsers: P9TextParserConfig[],
  current: number,
  matches: P9TextParseResult[]
): P9TextParseResult[] {
  if (current === parsers.length) {
    return matches;
  }

  const { pattern, style, transform } = parsers[current];

  matches = input
    .map(({ match: parent, style: parentStyle }) =>
      parent
        .split(pattern)
        .map((match) =>
          pattern.test(match) ? { match: transform ? transform(match) : match, style } : { match, style: parentStyle }
        )
    )
    .reduce((output, next) => output.concat(next), []);

  return parseText(matches, parsers, ++current, matches);
}

from react-native-parsed-text.

fbartho avatar fbartho commented on June 30, 2024

@sellmeadog -- this is great! Were you proposing this as a way to rewrite this library? or just as an example on how to do it if people need this feature?

A. I'm just the steward of react-native-parsed-text, not the originator, so I'm probably not going to completely rewrite this library.
B. If it's just an example on how to do this if your application needs it, then I'd be comfortable closing this Feature request then!

from react-native-parsed-text.

sellmeadog avatar sellmeadog commented on June 30, 2024

It's not a strict proposal, I was just trying to showcase what worked for me and see what value it might add to the overall discussion. I think it could be the base of a rewrite, but react-native-parsed-text seems to do a bit more like supporting click interaction, limits on matching, etc., which I have not taken into consideration.

from react-native-parsed-text.

d11wtq avatar d11wtq commented on June 30, 2024

Can I propose a simple way to fix this would be to allow renderText to return a React Element? Then you could do like:

{
  pattern: /\w+-\d+/,
  renderText: (str, matches) => (
    <ParsedText
      parse={[ ... ]}
    >{str}</ParsedText>
  ),
}

This avoid complicating the parsing logic and moves the recursion onto the caller.

from react-native-parsed-text.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.