Message instance that generates the message with code highlighting

This commit is contained in:
Falko Victor Habel 2024-05-18 21:05:01 +02:00
parent bd452e51f0
commit a7585d3a50
1 changed files with 69 additions and 0 deletions

69
scripts/Message.py Normal file
View File

@ -0,0 +1,69 @@
import re
import tkinter as tk
CODE_PREFIX = "[1337]"
class Reply(tk.Frame):
def __init__(self, master, message,reply_type, font_size=12, background="#252525", text_color="white"):
super().__init__(master)
# Define style configurations
self.font = ("Helvetica", font_size)
self.background = background
self.text_color = text_color
self.reply_type = reply_type
self.message = self.extract_code(message)
self.reply_scope = []
# Adjust the overall background of the ttk.Notebook
self.configure(background=self.background)
label = tk.Label(master=self, text=self.reply_type, background=background, foreground="#a51c30",
font=self.font, wraplength=500 )
label.grid(row=0, column=0, padx=5, pady=5, sticky='ew')
row_index = 1 # Track the current grid row for widgets
for part in self.message:
if part.startswith(CODE_PREFIX):
part = part[len(CODE_PREFIX):]
code = tk.Text(master=self, width=50, font=self.font,
bg=self.background, fg=self.text_color, wrap="word")
code.grid(row=row_index, column=0, padx=5, pady=5, sticky='ew')
code.insert("1.0", part)
line_count = int(code.index('end-1c').split('.')[0])
code.config(height=line_count, state="disabled")
self.reply_scope.append(code)
else:
label = tk.Label(master=self, text=part, background=background, foreground=text_color,
font=self.font, wraplength=500 )
label.grid(row=row_index, column=0, padx=5, pady=5, sticky='nsew')
self.reply_scope.append(label)
row_index += 1
def extract_code(self, input_string, replacement=CODE_PREFIX):
split_parts = re.split(r'(```)', input_string)
output_array = []
previously_delimiter = False
for part in split_parts:
if part == "```":
previously_delimiter = True
continue
if previously_delimiter:
part = re.sub(r'^\b\w+\b', replacement, part, count=1)
previously_delimiter = False
if part.strip():
output_array.append(part)
return output_array