Преобразование текстовых аннотаций в компонент ReactJavascript

Форум по Javascript
Ответить
Anonymous
 Преобразование текстовых аннотаций в компонент React

Сообщение Anonymous »

Мне нужно преобразовать следующие текстовые аннотации в компонент реагирования, но в крайнем случае это не удается.
Аннотации:

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

[
{
"text": "",
"stop": [],
"start": [
{
"index": 0,
"length": 8,
"name": "bold",
"value": "true"
},
{
"index": 0,
"length": 133,
"name": "italic",
"value": "true"
}
]
},
{
"text": "Ra",
"stop": [],
"start": [
{
"index": 2,
"length": 3,
"name": "underline",
"value": "true"
}
]
},
{
"text": "van",
"stop": [
{
"index": 2,
"length": 3,
"name": "underline",
"value": "true"
}
],
"start": []
},
{
"text": "a: ",
"stop": [
{
"index": 0,
"length": 133,
"name": "italic",
"value": "true"
},
{
"index": 0,
"length": 8,
"name": "bold",
"value": "true"
}
],
"start": [
{
"index": 0,
"length": 133,
"name": "italic",
"value": "true"
}
]
},
{
"text": "Kubera would not allow me to borrow his vimana. When I asked if you could study it for reverse engineering, he refused again.",
"stop": [
{
"index": 0,
"length": 133,
"name": "italic",
"value": "true"
}
],
"start": []
},
{
"text": "\n",
"stop": [],
"start": [
{
"index": 134,
"length": 9,
"name": "bold",
"value": "true"
},
{
"index": 134,
"length": 206,
"name": "italic",
"value": "true"
}
]
},
{
"text": "Mayasura:",
"stop": [
{
"index": 134,
"length": 206,
"name": "italic",
"value": "true"
},
{
"index": 134,
"length": 9,
"name": "bold",
"value": "true"
}
],
"start": [
{
"index": 134,
"length": 206,
"name": "italic",
"value": "true"
}
]
},
{
"text": " Well, from Kubera’s perspective, he did the right thing. You lost your temper because your wish was rejected.  Instead of wasting your energy destroying things, why don’t we channelise it to build?",
"stop": [
{
"index": 134,
"length": 206,
"name": "italic",
"value": "true"
}
],
"start": []
}
]
Код для преобразования

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

export interface Annotation {
index: number;
length: number;
name: string;
value: string;
}

export interface AnnotationExtract {
text: string;
stop: Annotation[];
start: Annotation[];
}

function AnnotateText({ text, tag }: { text: React.ReactNode; tag: string }) {
const tagMapper: { [key: string]: string } = {
bold: "b",
italic: "i",
underline: "u",
};

if (!tagMapper[tag]) {
return React.Fragment({
children: text,
});
}

return React.createElement(tagMapper[tag], {}, text);
}

export function applyAnnotations(
operations: AnnotationExtract[]
): React.ReactNode[] {
const result: React.ReactNode[] = [];
let temp_result: React.ReactNode[] = [];
const tag_stack: string[] = [];

for (let i = 0; i < operations.length; i++) {
const op = operations[i];

if (tag_stack.length == 0) {
result.push(op.text);
} else {
temp_result.push(op.text);
}

if (op.stop.length > 0) {
for (let i = 0; i < op.stop.length; i++) {
const cur_op = op.stop[i];
if (
tag_stack[tag_stack.length - 1] == cur_op.name &&
temp_result.length > 0
) {
const text = temp_result.pop();
const t = tag_stack.pop();

if (t) {
temp_result.push(
AnnotateText({
tag: t,
text: text,
})
);
temp_result = [
temp_result.reduce(
(acc: React.ReactNode, cur: React.ReactNode) => {
return React.createElement(React.Fragment, {}, acc, cur);
},
React.createElement(React.Fragment)
),
];
}
}
}

if (tag_stack.length == 0) {
result.push(temp_result.pop());
}
}

if (op.start.length > 0) {
tag_stack.push(...op.start.map((e) => e.name));
}
}

console.log(result);

return result;
}

Ожидаемый результат

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

Ravana: Kubera would not allow me to borrow his vimana. When I asked if you could study it for reverse engineering, he refused again.
Mayasura:Well, from Kubera’s perspective, he did the right thing. You lost your temper because your wish was rejected. Instead of wasting your energy destroying things, why don’t we channelise it to build?
Фактический результат

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

Ravana: Kubera would not allow me to borrow his vimana. When I asked if you could study it for reverse engineering, he refused again.
Mayasura: Well, from Kubera’s perspective, he did the right thing. You lost your temper because your wish was rejected. Instead of wasting your energy destroying things, why don’t we channelise it to build?
Все работает нормально, пока я не столкнусь с перекрывающейся аннотацией.
Жирный шрифт и курсив должен быть оболочкой, например этот Ravana:
но он отображается следующим образом Равана:
Может ли кто-нибудь указать, что здесь не так?

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

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

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

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

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

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