Есть ли способ показать LaTeX в Markdown – React NativeJavascript

Форум по Javascript
Ответить
Anonymous
 Есть ли способ показать LaTeX в Markdown – React Native

Сообщение Anonymous »

Я создаю приложение-помощник с искусственным интеллектом и изо всех сил пытаюсь отобразить контент LaTeX рядом с текстом, визуализированным с помощью Markdown. В настоящее время я использую React-native-markdown-display для поддержки Markdown и (устаревший) React-native-math-view для LaTeX.
Одним из решений, которое я попытался, было проанализировать содержимое с помощью регулярного выражения, чтобы разделить сегменты Markdown и LaTeX, а затем условно отобразить их с помощью или . Хотя это в некоторой степени работает, это приводит к серьезным проблемам с выравниванием и форматированием.
Ниже приведен мой текущий компонент MessageRenderer, который реализует этот подход:

Код: Выделить всё

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import MathView, {MathText} from 'react-native-math-view';
import {textStyle} from "../styles/common.style";
import Markdown from "react-native-markdown-display";
import {MsgType} from "./class/MessageItem";

const MessageRenderer = ({message, type}) => {
const parts = parseMessage(message);

return (

{parts.map((part, index) => {
if (part.type === 'text') {
return (

{part.content}

);
} else if (part.type === 'math') {
return (

);
}
return null;
})}

);
};

const parseMessage = (message) => {
const regex = /\\\(([\s\S]*?)\\\)|\\\[([\s\S]*?)\\]/g; // Matches math expressions within \(...\) or \[...\]
const parts = [];
let lastIndex = 0;

try {
message.replace(regex, (match, group1, group2, index) => {
// Add text content before the current match
if (lastIndex < index) {
parts.push({ type: 'text', content: message.slice(lastIndex, index) });
}

// Add the matched math content
const formula = group1 || group2;
parts.push({ type: 'math', content: formula });

// Update the lastIndex to the end of the current match
lastIndex = index + match.length;
});

// Add any remaining text after the last match
if (lastIndex < message.length) {
parts.push({ type: 'text', content: message.slice(lastIndex) });
}
} catch (e) {
console.log("error", e);
return parts;
}

return parts;
};

const styles = () => {
return StyleSheet.create({
main: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'center'
},
normalText: {
...textStyle.Body_4,
color: 'white'
},
mathText: {
...textStyle.Body_4,
marginHorizontal: 2,
color: 'white'
},
assistantNormalText: {
...textStyle.Body3,
color: 'white'
}
});
};

export default MessageRenderer;
Пример тестовых данных

Код: Выделить всё

const message = `

- This is a paragraph with some inline math: \\(E = mc^2\\).

- Some text with inline math \\(a^2 + b^2 = c^2\\)

- And block math

\\[
e = sum_(n=0)^oo 1/n!
\\]

\\[
\\int_{a}^{b} x^2 dx
\\]

Here is a JavaScript code block:

\`\`\`javascript
function greet() {
console.log("Hello, world!");
}
\`\`\`

And some more inline math: \\(a^2 + b^2 = c^2\\).
`;
Вопрос

Есть ли более надежный или простой метод для совместной визуализации Markdown и LaTeX в React Native, не прибегая к ручному анализу содержимого с помощью регулярных выражений?


Подробнее здесь: https://stackoverflow.com/questions/793 ... act-native
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»