Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sisilicon
GitHub Repository: sisilicon/worldedit-be
Path: blob/master/src/library/utils/rawtext.ts
1784 views
1
import { Player, system } from "@minecraft/server";
2
3
type textElement = {
4
text: string;
5
};
6
type translateElement = {
7
translate: string;
8
with: string[];
9
};
10
type rawTextElement = textElement | translateElement;
11
12
export class RawText {
13
private rawtext: rawTextElement[] = [];
14
private lastElementIdx: number;
15
16
public with(text: string | number) {
17
const raw = new RawText();
18
raw.rawtext = this.rawtext;
19
raw.lastElementIdx = this.lastElementIdx;
20
const element = <translateElement>raw.rawtext[this.lastElementIdx];
21
if (element?.translate) {
22
element.with.push(`${text}`);
23
}
24
return raw;
25
}
26
27
public prepend(type: "text" | "translate", data: string) {
28
const raw = new RawText();
29
raw.rawtext = this.rawtext;
30
if (type == "text") {
31
raw.rawtext.unshift({
32
text: data,
33
});
34
} else {
35
raw.rawtext.unshift({
36
translate: data,
37
with: [],
38
});
39
}
40
raw.lastElementIdx = 0;
41
return raw;
42
}
43
44
public append(type: "text" | "translate", data: string) {
45
const raw = new RawText();
46
raw.rawtext = this.rawtext;
47
if (type == "text") {
48
raw.rawtext.push({
49
text: data,
50
});
51
} else {
52
raw.rawtext.push({
53
translate: data,
54
with: [],
55
});
56
}
57
raw.lastElementIdx = raw.rawtext.length - 1;
58
return raw;
59
}
60
61
public static translate(translationKey: string) {
62
const raw = new RawText();
63
raw.rawtext.push({
64
translate: translationKey,
65
with: [],
66
});
67
raw.lastElementIdx = 0;
68
return raw;
69
}
70
71
public static text(text: string) {
72
const raw = new RawText();
73
raw.rawtext.push({
74
text: text,
75
});
76
raw.lastElementIdx = 0;
77
return raw;
78
}
79
80
public toString(): string {
81
const optimized: rawTextElement[] = [];
82
for (const element of this.rawtext) {
83
if ("text" in element && optimized.length && "text" in optimized[optimized.length - 1]) {
84
(optimized[optimized.length - 1] as textElement).text += element.text;
85
} else {
86
optimized.push(element);
87
}
88
}
89
90
const temp = this.rawtext;
91
this.rawtext = optimized;
92
const json = JSON.stringify(this);
93
this.rawtext = temp;
94
return json;
95
}
96
97
print(player: Player) {
98
system.run(() => (player.isValid ? player.runCommand(`tellraw @s ${this.toString()}`) : undefined));
99
}
100
101
printError(player: Player) {
102
this.prepend("text", "§c").print(player);
103
}
104
}
105
106