Last active
April 12, 2025 21:18
-
-
Save CatzHoekk/3a5935f730ad483f2c398431cb6ae8ae to your computer and use it in GitHub Desktop.
BBCode sanitizer for Godot RichTextLabel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends RichTextLabel | |
@export var whitelisted_tags : PackedStringArray = ["url"] | |
@export_multiline var unsanitized_text: String = """ 1. This text is normal, but [b]this part is bold[/b]. | |
2. You can also make text [i]italic[/i] for emphasis. | |
3. Or, if needed, [u]underline important words[/u]. | |
4. Combine styles like [b][i]bold and italic[/i][/b]. | |
5. Change text color using names: [color=green]This is green.[/color] | |
6. Use hex codes for specific colors: [color=#ff8800]This is orange.[/color] | |
7. [s]Strike through[/s] text that is no longer relevant. | |
8. Make text [font_size=24]larger[/font_size] or [font_size=10]smaller[/font_size]. | |
9. [center]Center-align a line of text.[/center] | |
10. Create a clickable link: Visit the [url=https://godotengine.org]Godot Website[/url]! | |
[url={"thread": "453", "category": "2"}]Awesome Puzzle[/url]""" | |
func _ready() -> void: | |
self.meta_clicked.connect(_on_meta_clicked) | |
_custom_set_text(unsanitized_text) | |
func _on_meta_clicked(meta: Variant) -> void: | |
match typeof(meta): | |
TYPE_STRING: | |
var json = JSON.new() | |
print("Meta clicked:", meta) | |
var error: Error = json.parse(meta as String) | |
if error == OK: | |
# example uses string because godot json parses all numbers as floats | |
var target_thread = json.data.get("thread", "-1") | |
var target_category = json.data.get("category", "-1") | |
print("Thread ID: %s\nCategory ID: %s" % [target_thread, target_category]) | |
else: | |
printerr("Not proper json? We don't care!") | |
_: | |
print("Unsupported variant type") | |
func _custom_set_text(new_text: String) -> void: | |
text = _remove_non_whitelisted_tags(new_text, whitelisted_tags) | |
func _remove_non_whitelisted_tags(unsanitized: String, whitelist: PackedStringArray) -> String: | |
var pattern: String | |
if whitelist.is_empty(): | |
pattern = "\\[[^\\]]*\\]" | |
else: | |
var whitelist_pattern_part = "|".join(whitelist) | |
pattern = "\\[(?!/?(?i:" + whitelist_pattern_part + ")\\b)[^\\]]*\\]" | |
var regex = RegEx.new() | |
var err = regex.compile(pattern) | |
if err != OK: | |
printerr("Failed to compile regex pattern: ", pattern, " Error code: ", err) | |
return unsanitized | |
return regex.sub(unsanitized, "", true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment