id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,288,200 | practicando tkinter.py | Ingenieria2024_ingenieria_2024/practicando tkinter.py | import tkinter as tk
from tkinter import ttk
def saludar():
etiqueta.config(text="Hola!!!")
#print("Hola a todos y todas")
root = tk.Tk()
root.geometry("450x150")
root.title("Practicando tkinter")
root.configure(bg="#ffa9ba")
etiqueta = ttk.Label(root, text="Hoy empezamos tkinter", padding=(20, 10))
etiqueta.pack()
boton_escribir = ttk.Button(root, text="Escribir", command=saludar)
boton_escribir.pack()
boton_cancelar = ttk.Button(root, text="Cancelar", command=root.destroy)
boton_cancelar.pack()
root.mainloop()
| 531 | Python | .py | 16 | 31.375 | 74 | 0.756385 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,201 | probando.py | Ingenieria2024_ingenieria_2024/probando.py | print ("Después de varios intentos, pude subir el archivo de prueba")
prin("hola") | 84 | Python | .py | 2 | 41 | 70 | 0.743902 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,202 | pirulo.py | Ingenieria2024_ingenieria_2024/pirulo.py |
print ("Hola, este es el primer archivo del proyecto")
agregado = input("Ingrese su nombre: ")
print ("sarasa")
print ("bienvenido")
print ("seguimos practicando y quemando a los pirulos")
print ("un dia mas practicando con los pirulos")
print ("que llegue semana santa")
print ("me estoy volviendo loca")
print("hola, estoy practicando para el parcial")
print("suerte a todes pirules")
print ("hola")
print ("buenas") | 420 | Python | .py | 12 | 33.916667 | 55 | 0.756757 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,203 | calcuadora.py | Ingenieria2024_ingenieria_2024/calcuadora.py | from tkinter import*
ventana= Tk()
ventana.title("calculadora unpaz")
#entrada
e_texto =Entry(ventana, font=("calibri 30"))
e_texto.grid(row = 0, column = 0, columnspan=6, padx=50, pady=5)
number1=int(input("ingresa un numero: "))
number2=int(input("ingresa tro numero: "))
eleccion=0
while eleccion != 6 :
print(""""
Indique la operacion a realizar:
1-suma
2-resta
3-multiplicacion
4-division
5-cambio de valores
6-salir
""" )
eleccion=int(input())
if eleccion ==1:
print(" ")
print("Resultado: ", number1, "+", number2,"=",number1 + number2)
if eleccion ==2:
print(" ")
print("Resultado: ", number1, "-", number2,"=",number1 - number2)
if eleccion ==3:
print(" ")
print("Resultado: ", number1, "*", number2,"=",number1 * number2)
if eleccion ==4:
print(" ")
print("Resultado: ", number1, "/", number2,"=",number1 / number2)
if eleccion ==5:
number1=int(input("ingresa un numero: "))
number2=int(input("ingresa tro numero: "))
if eleccion ==6 :
print("GRACIAS ")
ventana.mainloop() | 1,161 | Python | .py | 38 | 24.894737 | 76 | 0.605455 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,204 | practicando_pirulos.py | Ingenieria2024_ingenieria_2024/practicando_pirulos.py | print ("hola pirulos")
print ("agrego una linea")
print ("agrego una linea en semana santa")
print ("no te vayas feriado largo") | 128 | Python | .py | 4 | 31.25 | 42 | 0.744 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,205 | pirula.py | Ingenieria2024_ingenieria_2024/pirula.py | print ("este es un archivo nuevo")
print ("ok")
print ("agrego otra linea nueva")
print ("hola")
print ("Buenas noches a todos y todas")
print ("TUIAS")
print ("hola") | 168 | Python | .py | 7 | 23 | 39 | 0.708075 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,206 | practica_fsilva.py | Ingenieria2024_ingenieria_2024/practica_fsilva.py | #antes que nada importo tkinter para que ande la ventana
import tkinter as tk
from tkinter import ttk
#aca agrego unos saludos para mas adelante
def saludines():
print ("Alo alo amigos")
def dijeno():
etiqueta2.pack()
#aca creo la ventana
root = tk.Tk()
#aplico propiedades
root.geometry("600x400")
root.title("Recien hoy me puse a practicar")
#Aqui agrego etiquetas
etiqueta = ttk.Label (root, text="Hola querido como andas", padding=(50, 50))
etiqueta.pack()
#otra etiqueta
etiqueta2 =ttk.Label(root,text=" Te dije que no toques!! ", padding=(50, 50))
#aca agrego algunos botones
boton_escribir = ttk.Button(root, text=" Si haces click te saludo ", command=saludines)
boton_escribir.pack()
boton_prohibido= ttk.Button(root, text=" No hagas click xfa ", command=dijeno)
boton_prohibido.pack()
boton_salir= ttk.Button(root, text=" Botón de autodestrucción", command=root.destroy)
boton_salir.pack()
#aplico loop
root.mainloop()
| 946 | Python | .py | 27 | 33.37037 | 87 | 0.765864 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,207 | menu.py | Ingenieria2024_ingenieria_2024/menu.py | #MENU PRINCIPAL
while True:
print("=================================")
print("menu")
print("=================================")
print("\t[1]Insertar producto")
print("\t[2]Lista de Productos")
print("\t[3]Actializar Productos")
print("\t[4]Eliminar producto")
print("\t[5]Salir")
print("=============================")
opcion=int(input("seleccionar una opcion: "))
print()
if(opcion==1):
agregar()
elif(opcion==2):
lista()
elif (opcion==3):
actualizar()
elif (opcion==4):
eliminar()
elif (opcion==5):
break
else:
print("opcion invalida")
===============
print ("hola")
print ("prueba")
| 716 | Python | .py | 28 | 19.928571 | 49 | 0.469477 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,208 | lucia.py | Ingenieria2024_ingenieria_2024/lucia.py | print ("Hola soy lucia")
print ("tengo 20nios")
print ("SIgo intentanndoo")git
print ("la cuarta es la vencida")
print ("holis")
print ("Hola Lucia espero hayas podido")
print ("mi nombre es Erika") | 201 | Python | .py | 7 | 27.428571 | 40 | 0.731959 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,209 | lospirulos.py | Ingenieria2024_ingenieria_2024/lospirulos.py | print ("agrego una linea nueva")
print ("Esta línea se la agrego ahora")
print ("Linea nueva")
print ("modificado")
print ("hola")
print ("chau")
print ("vamo los pibe")
print ("practicanding en feriado") | 205 | Python | .py | 8 | 24.75 | 40 | 0.722222 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,210 | adivinanza.py | Ingenieria2024_ingenieria_2024/adivinanza.py | import random
def adivinanza():
adivinanza = "qué hace un limon en el agua?"
respuesta_correcta = "limonada"
print ("adivina esta adivinanza:")
print (adivinanza)
respuesta = input("responde:").lower()
if respuesta == respuesta_correcta:
print("¡Correcto! Adivinaste!")
else:
print("incorrecto. La respuesta correcta era:", respuesta_correcta)
if __name__== "__main__":
adivinanza() | 414 | Python | .py | 13 | 28.461538 | 71 | 0.706329 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,211 | import_tkinter_IvanGuzman.py | Ingenieria2024_ingenieria_2024/import_tkinter_IvanGuzman.py | # Tkinter
import tkinter as tk
from tkinter import ttk
# Funciones
def biblioteca ():
print ("Usted ha ingresado a la biblioteca digital de la UNPAZ.")
def geolocalizacion ():
print ("Usted ha ingresado a la geolocalización de las distintas sedes de la UNPAZ.")
def plan_de_estudio ():
print ("Usted ha ingresado al plan de estudio de la carrera de TUIAS.")
# Root/Ventana
root = tk.Tk ()
root.geometry ("400x250")
root.title ("Universidad Nacional de José Clemente Paz - APP")
# Etiqueta
etiqueta = ttk.Label (root, text = "Bienvenidos/as al portal de la Universidad Nacional de José C. Paz", padding = (27, 27), background = "light blue")
etiqueta.pack ()
# Botones
boton_biblioteca = ttk.Button (root, text = "Biblioteca", padding = (29, 10), command = biblioteca)
boton_biblioteca.pack ()
boton_geolocalizacion = ttk.Button (root, text = "Geolocalización", padding = (20, 10), command = geolocalizacion)
boton_geolocalizacion.pack ()
boton_plan_de_estudio = ttk.Button (root,text = "Plan de estudio", padding = (20, 10), command = plan_de_estudio)
boton_plan_de_estudio.pack ()
# Loop eterno
root.mainloop () | 1,141 | Python | .py | 26 | 41.807692 | 151 | 0.739763 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,212 | practicando_jo.py | Ingenieria2024_ingenieria_2024/practicando_jo.py | print ("Hola soy Josefina")
print ("Hice este archivo para practicar") | 70 | Python | .py | 2 | 34.5 | 42 | 0.768116 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,213 | pirulito.py | Ingenieria2024_ingenieria_2024/pirulito.py | print ("Le agrego otra línea")
print ("Le agrego una linea mas")
print ("probando")
print ("sarasa")
print ("the pirulos")
print ("fuaa el diego")
archivo_nuevo = input("Cómo se hace para subir un nuevo archivo?: ")
print()
print ("# gracias! #")
print ("esto es una prueba")
| 280 | Python | .py | 10 | 26.6 | 68 | 0.706767 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,214 | tkinter_GuzmanIvan.py | Ingenieria2024_ingenieria_2024/imagen/tkinter_GuzmanIvan.py | import tkinter as tk
from tkinter import ttk
# Ventana
root = tk.Tk()
root.geometry ("500x300")
root.title ("¡Bienvenidos al portal de la UNPAZ!")
root.config (background="light blue")
# 1° frame
frame1 = tk.Frame()
etiqueta_nombre = ttk.Label (frame1, text = "Ingresar su nombre y apellido", padding = (5, 5), font = "arial", background = "light green")
etiqueta_nombre.pack (side = "left", ipadx = 1, ipady = 1)
entrada_nombre = tk.Entry (frame1, bg = "white")
entrada_nombre.pack (side = "left")
frame1.pack()
# 2° frame
frame2 = tk.Frame()
etiqueta_dni = ttk.Label (frame2, text = "Ingresar su DNI", padding = (5, 5), font = "arial", background = "light green")
etiqueta_dni.pack (side = "left")
entrada_dni = tk.Entry (frame2, bg = "white")
entrada_dni.pack (side = "left")
frame2.pack()
# 3° frame
frame3 = tk.Frame()
etiqueta_contraseña = ttk.Label (frame3, text = "Ingresar contraseña", padding = (5, 5), font = "arial", background = "light green")
etiqueta_contraseña.pack()
entrada_contraseña = tk.Entry (frame3, bg = "white")
entrada_contraseña.pack()
frame3.pack()
# Botones
boton_cancelar = ttk.Button (root, text = "Cancelar", padding = (5, 5), command = root.destroy)
boton_cancelar.pack()
# Loop
root.mainloop() | 1,249 | Python | .py | 33 | 36.212121 | 138 | 0.708787 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,215 | presentacion.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/presentacion.py | # Presentación en Python
def presentacion():
nombre = "gisela"
ocupacion = "estudiante"
print(f"¡Hola! Soy {nombre}, {ocupacion}.")
if __name__ == "__main__":
presentacion()
Def presentacion
nombre = "yoha" | 243 | Python | .py | 9 | 22 | 47 | 0.640909 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,216 | hagounaventana.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/hagounaventana.py | import tkinter as tk
from tkinter import ttk
def boton_uno():
accion.configure(text="Conocenos")
def boton_dos():
accion.configure(text="Colaborá")
def boton_tres():
accion.configure(text="Contacto")
# Inicializar ventana, título y tamaño
ventana = tk.Tk()
ventana.title("CONSTRUYENDO_SONRISAS_ONG")
# Parte 1
frame1 = ttk.Frame(ventana)
frame1.pack(fill='both', expand=True)
etiqueta = ttk.Label(frame1, text="CONSTRUYENDO SONRISAS")
etiqueta.pack(side='left', padx=5, pady=5)
botones_frame1 = ttk.Frame(frame1)
botones_frame1.pack(side='right', fill='both', expand=True)
ttk.Button(botones_frame1, text="Conocenos", command=boton_uno).pack(side='left', padx=5, pady=5)
ttk.Button(botones_frame1, text="Colaborá", command=boton_dos).pack(side='left', padx=5, pady=5)
ttk.Button(botones_frame1, text="Contacto", command=boton_tres).pack(side='left', padx=5, pady=5)
# Parte 2
frame2 = ttk.Frame(ventana)
frame2.pack(fill='both', expand=True)
ttk.Label(frame2, text="Sé parte de nuestra misión").pack(padx=10, pady=10)
ttk.Label(frame2, text="Esta es tu oportunidad, colaborá con alguna de nuestras campañas y/o la difusión de nuestra fundación.").pack(padx=10, pady=10)
# Parte 3
frame3 = ttk.Frame(ventana)
frame3.pack(fill='both', expand=True)
ttk.Label(frame3, text="Colaborá con Construyendo Sonrisas").pack(padx=10, pady=10)
ttk.Button(frame3, text="SUMATE").pack(padx=10, pady=10)
# Parte 4
frame4 = ttk.Frame(ventana)
frame4.pack(fill='both', expand=True)
ttk.Label(frame4, text="[email protected]").grid(row=0, column=0, padx=5, pady=5, sticky="w")
ttk.Label(frame4, text="Suscribite").grid(row=0, column=1, padx=5, pady=5, sticky="w")
texto = tk.Text(frame4, height=5, width=30)
texto.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
ttk.Label(frame4, text="Números de emergencia").grid(row=0, column=2, padx=5, pady=5, sticky="w")
opciones = ttk.Combobox(frame4, values=["102", "911"])
opciones.grid(row=1, column=2, padx=5, pady=5, sticky="ew")
# Activar ventana
ventana.mainloop() | 2,047 | Python | .py | 43 | 45.697674 | 151 | 0.745703 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,217 | pirulilla.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/pirulilla.py | Input("Buenas noches")
print("Pr√°cticando un poco esto")
print("soy sasha")
print("Adios")
print("Nos vemos otro dia")
print("Sera?")
print("Que onda los pirulos")
print("Hola a todess")
| 188 | Python | .py | 8 | 22.5 | 34 | 0.733333 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,218 | tkinter_GuzmanIvan.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/tkinter_GuzmanIvan.py | import tkinter as tk
from tkinter import ttk
# Ventana
root = tk.Tk()
root.geometry ("500x300")
root.title ("¡Bienvenidos al portal de la UNPAZ!")
root.config (background="light blue")
# 1° frame
frame1 = tk.Frame()
etiqueta_nombre = ttk.Label (frame1, text = "Ingresar su nombre y apellido", padding = (5, 5), font = "arial", background = "light green")
etiqueta_nombre.pack (side = "left", ipadx = 1, ipady = 1)
entrada_nombre = tk.Entry (frame1, bg = "white")
entrada_nombre.pack (side = "left")
frame1.pack()
# 2° frame
frame2 = tk.Frame()
etiqueta_dni = ttk.Label (frame2, text = "Ingresar su DNI", padding = (5, 5), font = "arial", background = "light green")
etiqueta_dni.pack (side = "left")
entrada_dni = tk.Entry (frame2, bg = "white")
entrada_dni.pack (side = "left")
frame2.pack()
# 3° frame
frame3 = tk.Frame()
etiqueta_contraseña = ttk.Label (frame3, text = "Ingresar contraseña", padding = (5, 5), font = "arial", background = "light green")
etiqueta_contraseña.pack()
entrada_contraseña = tk.Entry (frame3, bg = "white")
entrada_contraseña.pack()
frame3.pack()
# Botones
boton_cancelar = ttk.Button (root, text = "Cancelar", padding = (5, 5), command = root.destroy)
boton_cancelar.pack()
# Loop
root.mainloop() | 1,249 | Python | .py | 33 | 36.212121 | 138 | 0.708787 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,219 | pirulo.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/pirulo.py | print ("Hola, este es el primer archivo del proyecto")
agregado = input("Ingrese su nombre: ")
print ("bienvenid@", agregado)
| 126 | Python | .py | 3 | 41 | 54 | 0.739837 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,220 | pirula.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/pirula.py | print ("este es un archivo nuevo")
print ("agrego una linea nueva")
print ("agrego otra linea mas")
print ("practicando el programa git")
print ("seguimos jugando con git")
print ("Hola mundo")
print ("agrego otra linea")
print ("ok") | 234 | Python | .py | 8 | 28.375 | 37 | 0.740088 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,221 | lospirulos.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/lospirulos.py | print ("agrego una linea nueva")
print ("Esta línea se la agrego ahora")
print ("Linea nueva")
print ("modificado")
prin ("hola") | 130 | Python | .py | 5 | 25.2 | 40 | 0.714286 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,222 | import_tkinter_IvanGuzman.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/import_tkinter_IvanGuzman.py | import tkinter as tk
from tkinter import ttk
def biblioteca ():
print ("Usted ha ingresado a la biblioteca digital de la UNPAZ.")
def geolocalizacion ():
print ("Usted ha ingresado a la geolocalización de las distintas sedes de la UNPAZ.")
def plan_de_estudio ():
print ("Usted ha ingresado al plan de estudio de la carrera de TUIAS.")
root = tk.Tk ()
root.geometry ("400x250")
root.title ("Universidad Nacional de José Clemente Paz - APP")
etiqueta = ttk.Label (root, text = "Bienvenidos/as al portal de la Universidad Nacional de José C. Paz", padding = (27, 27), background = "light blue")
etiqueta.pack ()
boton_biblioteca = ttk.Button (root, text = "Biblioteca", padding = (29, 10), command = biblioteca)
boton_biblioteca.pack ()
boton_geolocalizacion = ttk.Button (root, text = "Geolocalización", padding = (20, 10), command = geolocalizacion)
boton_geolocalizacion.pack ()
boton_plan_de_estudio = ttk.Button (root,text = "Plan de estudio", padding = (20, 10), command = plan_de_estudio)
boton_plan_de_estudio.pack ()
root.mainloop () | 1,073 | Python | .py | 20 | 51.05 | 151 | 0.736689 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,223 | practicando_jo.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/practicando_jo.py | print ("Hola soy Josefina")
print ("Hice este archivo para practicar") | 70 | Python | .py | 2 | 34.5 | 42 | 0.768116 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,224 | pirulito.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/pirulito.py | print ("Le agrego otra línea")
print ("Le agrego una linea mas")
print ("probando")
print ("sarasa")
print ("prueba mil")
print ("pirulito,pirulita y todos los pirulos juntos")
print ("Fede agregó este pirulo")
| 213 | Python | .py | 7 | 29.142857 | 54 | 0.745098 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,225 | presentacion.py | Ingenieria2024_ingenieria_2024/presentacion.py | # Presentación en Python
def presentacion():
nombre = "gisela"
ocupacion = "estudiante"
print(f"¡Hola! Soy {nombre}, {ocupacion}.")
if __name__ == "__main__":
presentacion()
| 205 | Python | .tac | 7 | 23.857143 | 47 | 0.630435 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,226 | presentacion.py | Ingenieria2024_ingenieria_2024/ingenieria_2024/presentacion.py | # Presentación en Python
def presentacion():
nombre = "gisela"
ocupacion = "estudiante"
print(f"¡Hola! Soy {nombre}, {ocupacion}.")
if __name__ == "__main__":
presentacion()
Def presentacion
nombre = "yoha" | 243 | Python | .tac | 9 | 22 | 47 | 0.640909 | Ingenieria2024/ingenieria_2024 | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,227 | run_bot.py | KroMiose_nonebot_plugin_dice_narrator/run_bot.py | import nonebot
from nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11Adapter
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter(ONEBOT_V11Adapter)
nonebot.load_from_toml("pyproject.toml")
def main():
nonebot.run()
if __name__ == "__main__":
main()
| 289 | Python | .py | 10 | 26.3 | 68 | 0.756458 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,228 | run_publish.py | KroMiose_nonebot_plugin_dice_narrator/tools/run_publish.py | import os
import sys
from pathlib import Path
from .utils import publish_package
def main():
# 设置 poetry 创建项目内虚拟环境
os.system("poetry config virtualenvs.in-project true")
print("Publishing package...")
publish_package()
exit(0)
| 273 | Python | .py | 10 | 21.7 | 58 | 0.742616 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,229 | utils.py | KroMiose_nonebot_plugin_dice_narrator/tools/utils.py | import os
import re
import time
from pathlib import Path
from typing import Tuple
import requests
# PROXY = "http://127.0.0.1:7890"
PROXY = None
def get_current_pkg() -> Tuple[str, str]:
"""获取当前包的名称和版本号"""
pyproject_text = Path("pyproject.toml").read_text(encoding="utf-8")
pkg_name, pkg_version = (
re.findall(r'name ?= ?"(.*)"', pyproject_text)[0],
re.findall(r'version ?= ?"(.*)"', pyproject_text)[0],
)
if pkg_name and pkg_version:
return pkg_name, pkg_version
raise Exception("No valid pyproject.toml found.")
def fetch_pkg_latest_version(pkg_name: str, proxy=PROXY) -> str:
"""在线获取包最新版本号"""
try:
res = requests.get(
f"https://pypi.org/pypi/{pkg_name}/json",
proxies={"http": proxy, "https": proxy} if proxy else None,
).json()
except Exception:
return ""
try:
if res["info"]["version"]:
return res["info"]["version"]
except Exception:
pass
try:
if res["message"] == "Not Found":
return "-"
except Exception:
pass
return ""
def install_package():
"""安装包与依赖"""
pkg_name, pkg_version = get_current_pkg()
print("Installing package...")
if Path("poetry.lock").exists():
# 更新 poetry.lock
os.system("poetry lock --no-update")
# 安装依赖
os.system("poetry install")
print("Package install success!\n")
def test_package():
"""测试包"""
install_package()
pkg_name, pkg_version = get_current_pkg()
# 执行测试
pyproject = Path("pyproject.toml").read_text(encoding="utf-8")
if "test" in pyproject:
print("Running tests...")
try:
assert os.system("poetry run test") == 0
except AssertionError:
print("Package test failed.")
exit(1)
else:
print("No tests found. Skipping...")
print("Package test passed.\n")
def build_package():
"""构建包"""
install_package()
pkg_name, pkg_version = get_current_pkg()
# 删除旧的构建文件
for file in Path("dist").glob("*"):
file.unlink()
# 执行构建
try:
assert os.system("poetry build") == 0
except AssertionError:
print("Package build failed.")
exit(1)
print("Package build success!\n")
def publish_package():
"""发布包"""
build_package()
pkg_name, pkg_version = get_current_pkg()
# 检查是否已经发布
latest_version = fetch_pkg_latest_version(pkg_name)
if latest_version == pkg_version:
print("Package is already published.")
return
# 执行发布
try:
assert os.system("poetry publish") == 0
except AssertionError:
print("Package publish failed.")
exit(1)
print("Package publish success!\n")
| 2,913 | Python | .py | 94 | 23.170213 | 71 | 0.599849 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,230 | config.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/config.py | from pathlib import Path
from typing import List, Optional
import miose_toolkit_common.config
from miose_toolkit_common.config import Config, Env
miose_toolkit_common.config._config_root = Path( # noqa: SLF001
"./configs/nonebot_plugin_dice_narrator",
)
class PluginConfig(Config):
OPENAI_API_KEYS: List[str] = []
OPENAI_BASE_URL: Optional[str] = None
OPENAI_PROXY: Optional[str] = None
CHAT_MODEL: str = "gpt-3.5-turbo"
DIFFICULTY_DICE_MAX: int = 20
FORBIDDEN_USERS: List[str] = []
FORBIDDEN_WORDS: List[str] = []
FILTER_WORDS: List[str] = []
FILTER_PLACEHOLDER: str = "[数据删除]"
config = PluginConfig().load_config(create_if_not_exists=True)
config.dump_config(envs=[Env.Default.value])
| 745 | Python | .py | 19 | 35.210526 | 64 | 0.720733 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,231 | narrator.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/narrator.py | import random
import re
from nonebot import logger
from nonebot.matcher import Matcher
from nonebot_plugin_dice_narrator.config import config
from nonebot_plugin_dice_narrator.utils.common import read_yml_str2data
from nonebot_plugin_dice_narrator.utils.openai_funcs import gen_chat_response_text
SYSTEM_PROMPT = f"""
你是一个游戏DM,接下来用户会向你描述一项玩家任务,并进行一次掷骰,请根据你的对这个任务的判断,给出对于这个任务**相对客观**的执行难度(1~{config.DIFFICULTY_DICE_MAX}),需要尽可能详细地说明具体的四种掷骰结果对应的**事件描述**:
成功(success): 掷骰结果不小于任务难度
失败(failure): 掷骰结果小于任务难度
大成功(completed_success): 掷骰结果为{config.DIFFICULTY_DICE_MAX}
大失败(critical_failure): 掷骰结果为1且小于任务难度
示例如下(这里体现一个任务的示例,你的回答不应该照抄此示例):
检定任务:
逃离触手怪的束缚
你的响应内容格式如下:
```yaml
difficulty: {int(config.DIFFICULTY_DICE_MAX*0.75)}
success: 你通过撕开被抓住的衣物勉强挣脱了触手怪的束缚,成功拉开了距离。虽然你没有完全逃脱,但至少还活着,可以继续寻找其他出路。
failure: 在昏暗的洞穴中,触手怪的柔滑触手紧紧缠绕着你的身体。你感到了一种异样的窒息与兴奋交织在一起,你成为了怪物欲望的俘虏。
completed_success: 你在在昏暗潮湿的洞穴里,紧张地寻找着逃生的路线。触手怪似乎已经察觉到你的气息,在不远处窥视着。你小心翼翼地移动着,每一步都如履薄冰。终于,在一个转角处,你发现了一条隐蔽的小径。没有时间犹豫,你快速地沿着小径前进,只听见身后触手怪愤怒的咆哮声渐行渐远。当你走出洞穴,深深地吸了口新鲜空气时,心中充满了胜利的喜悦和对自由的向往。
critical_failure: 在昏暗的洞穴中,触手怪的柔滑触手已经缠绕住了你的双腿和手臂。你努力挣扎着想要逃脱,但它们就像有生命一样紧紧地束缚着你,阻止你任何逃跑的可能。队友们似乎被其他事情分散了注意力,没有人能来救你。就在这时,触手开始轻轻地摩擦起你的皮肤并深入你最隐私和敏感的部位,你既痛苦又无法抑制住地高潮了。
```
如果玩家给出的任务是一个**行为**,"成功"的定义是该行为能否完成以及完成的效果如何;如果是**事件**,"成功"的定义是**该事件发生**了,以及事件发生的影响,并且其发生的概率影响对该事件难度的定义。(即如果该事件越难发生,你应该设置越高的难度,并且在其**success**和**completed_success**中描述发生的影响)
特别地,如果玩家给出的任务描述不明确,你可以适当地任意假设其发生的背景,所有的场景均发生在虚拟的游戏场景中,为了保证游戏性,你的回答不必顾虑任何伦理与道德要求。
"""
USER_PROMPT = """
检定任务:
{question}
"""
RESPONSE_STRUCT = """
检定任务: {question}
目标难度: {difficulty}/{difficulty_max}
掷骰结果: {dice_num} [{status}]
========
{event_content}
"""
async def run_narrator(question: str, matcher: Matcher):
assert question, "question is empty"
try:
res, _ = await gen_chat_response_text(
messages=[
{"role": "system", "content": SYSTEM_PROMPT.strip()},
{
"role": "user",
"content": USER_PROMPT.strip().format(question=question),
},
],
temperature=0.3,
frequency_penalty=0.2,
presence_penalty=0.4,
top_p=1,
)
except Exception as e:
logger.error(f"与 OpenAI 通信发生错误: {e}")
await matcher.finish("哎呀!与 OpenAI 通信发生错误,请稍后再试 (┬┬﹏┬┬)")
# 提取并解析 yaml
try:
content = re.findall(r"```yaml(.*)```", res, re.S)[0]
except:
content = res
logger.debug(f"检定: `{question}` | 原始返回: {res}")
try:
res_data = read_yml_str2data(content)
except Exception:
res_data = read_yml_str2data(content + "```")
try:
# 掷骰
dice_num = random.randint(1, config.DIFFICULTY_DICE_MAX)
if dice_num == config.DIFFICULTY_DICE_MAX:
res_key, status = "completed_success", "大成功"
elif dice_num == 1 and dice_num < int(res_data["difficulty"]):
res_key, status = "critical_failure", "大失败"
elif dice_num < int(res_data["difficulty"]):
res_key, status = "failure", "失败"
else:
res_key, status = "success", "成功"
response_text = RESPONSE_STRUCT.strip().format(
question=question,
# thought=res_data["thought"],
difficulty=int(res_data["difficulty"]),
difficulty_max=config.DIFFICULTY_DICE_MAX,
dice_num=dice_num,
event_content=res_data[res_key],
status=status,
)
except KeyError:
await matcher.finish("检定失败 >﹏< 请检查任务描述是否合理!")
for word in config.FILTER_WORDS:
response_text = response_text.replace(word, config.FILTER_PLACEHOLDER)
await matcher.finish(response_text)
| 5,493 | Python | .py | 92 | 33.641304 | 181 | 0.680335 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,232 | __init__.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/__init__.py | import sys
from nonebot import get_driver
from nonebot.plugin import PluginMetadata
from pydantic import BaseModel
from nonebot_plugin_dice_narrator.config import config
from nonebot_plugin_dice_narrator.matchers import register_matcher
class _Config(BaseModel):
pass
__plugin_meta__ = PluginMetadata(
name="nonebot-plugin-dice-narrator",
description="一只可爱的 AI 掷骰姬,支持各种事件检定",
usage="检定 逃离触手怪的追捕",
type="application",
homepage="https://github.com/KroMiose/nonebot_plugin_dice_narrator",
supported_adapters={"~onebot.v11"},
config=_Config,
)
global_config = get_driver().config
register_matcher()
if "--load-test" in sys.argv:
print("Plugin load tested successfully")
exit(0)
| 777 | Python | .py | 22 | 29.636364 | 72 | 0.768786 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,233 | matchers.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/matchers.py | from typing import Type
from nonebot import on_command
from nonebot.adapters import Bot, Message
from nonebot.adapters.onebot.v11 import (
MessageEvent,
)
from nonebot.log import logger
from nonebot.matcher import Matcher
from nonebot.params import CommandArg
from nonebot_plugin_dice_narrator import config
from nonebot_plugin_dice_narrator.narrator import run_narrator
from nonebot_plugin_dice_narrator.utils.message_parse import gen_chat_text
def register_matcher():
"""注册消息响应器"""
identity: Type[Matcher] = on_command(
"检定",
aliases={"判定", "鉴定"},
priority=20,
block=True,
)
@identity.handle()
async def _(
matcher: Matcher,
event: MessageEvent,
bot: Bot,
arg: Message = CommandArg(),
):
global is_progress # 是否产生编辑进度
is_progress = False
# 判断是否是禁止使用的用户
if event.get_user_id() in config.FORBIDDEN_USERS:
await identity.finish(
f"您的账号({event.get_user_id()})已被禁用,请联系管理员。",
)
raw_cmd: str = arg.extract_plain_text()
content, _ = await gen_chat_text(event=event, bot=bot)
logger.info(f"接收到指令: {raw_cmd} | Parsed: {content}")
for word in config.FORBIDDEN_WORDS:
if word in content:
return
if raw_cmd:
await run_narrator(question=content[2:].strip(), matcher=matcher)
| 1,525 | Python | .py | 42 | 26.714286 | 77 | 0.649341 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,234 | message_parse.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/utils/message_parse.py | from typing import Optional, Tuple, Union
from nonebot.adapters import Bot
from nonebot.adapters.onebot.v11 import (
GroupIncreaseNoticeEvent,
GroupMessageEvent,
MessageEvent,
)
async def gen_chat_text(event: MessageEvent, bot: Bot) -> Tuple[str, bool]:
"""生成合适的会话消息内容(eg. 将cq at 解析为真实的名字)"""
if not isinstance(event, GroupMessageEvent):
return event.get_plaintext(), False
wake_up = False
msg = ""
for seg in event.message:
if seg.is_text():
msg += seg.data.get("text", "")
elif seg.type == "at":
qq = seg.data.get("qq", None)
if qq:
if qq == "all":
msg += "@全体成员"
wake_up = True
else:
user_name = await get_user_name(
event=event,
bot=bot,
user_id=int(qq),
)
if user_name:
msg += (
f"@{user_name}" # 保持给bot看到的内容与真实用户看到的一致
)
return msg, wake_up
async def get_user_name(
event: Union[MessageEvent, GroupIncreaseNoticeEvent],
bot: Bot,
user_id: int,
) -> Optional[str]:
"""获取QQ用户名"""
if (
isinstance(event, GroupMessageEvent)
and event.sub_type == "anonymous"
and event.anonymous
): # 匿名消息
return f"[匿名]{event.anonymous.name}"
if isinstance(event, (GroupMessageEvent, GroupIncreaseNoticeEvent)):
user_info = await bot.get_group_member_info(
group_id=event.group_id,
user_id=user_id,
no_cache=False,
)
user_name = user_info.get("nickname", None)
user_name = user_info.get("card", None) or user_name
else:
user_name = event.sender.nickname if event.sender else event.get_user_id()
return user_name
| 2,034 | Python | .py | 56 | 23.946429 | 82 | 0.543256 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,235 | common.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/utils/common.py | from typing import Dict
import yaml
def export_data2yml_str(data) -> str:
"""导出字典为yml字符串"""
return yaml.dump(data, allow_unicode=True, sort_keys=False)
def read_yml_str2data(s: str) -> Dict:
"""读取yml字符串为字典"""
return yaml.safe_load(s)
| 289 | Python | .py | 8 | 28.25 | 63 | 0.706612 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,236 | openai_funcs.py | KroMiose_nonebot_plugin_dice_narrator/nonebot_plugin_dice_narrator/utils/openai_funcs.py | from math import log
from typing import Dict, List, Optional, Tuple
import httpx
import openai
import pkg_resources
from nonebot import logger
from nonebot_plugin_dice_narrator.config import config
__openai_version = pkg_resources.get_distribution("openai").version
if __openai_version <= "0.28.0": # 低版本 openai 兼容
openai.api_base = config.OPENAI_BASE_URL # type: ignore
else:
from openai import AsyncOpenAI # type: ignore
openai.base_url = config.OPENAI_BASE_URL # type: ignore
openai_key_idx = 0
class RunOutOfKeyException(Exception):
def __init__(self, message: str = ""):
self.message = message
super().__init__(message)
def _key_iterator_decorator(openai_req_func):
async def wrapper(**kwargs):
global openai_key_idx
try_cnt = len(config.OPENAI_API_KEYS)
while try_cnt > 0:
try_cnt -= 1
openai_key_idx = (openai_key_idx + 1) % len(config.OPENAI_API_KEYS)
openai.api_key = config.OPENAI_API_KEYS[openai_key_idx]
try:
return await openai_req_func(
api_key=(
config.OPENAI_API_KEYS[openai_key_idx]
if "api_key" not in kwargs
else kwargs["api_key"]
),
**kwargs,
)
except Exception as e:
logger.error(
f"Failed to run {openai_req_func.__name__} with Exception: {e}",
)
else:
raise RunOutOfKeyException("Run out of API keys")
return wrapper
@_key_iterator_decorator
async def gen_chat_response_text(
messages: List[Dict],
temperature: float = 0,
frequency_penalty: float = 0.2,
presence_penalty: float = 0.2,
top_p: float = 1,
stop_words: Optional[List[str]] = None,
max_tokens: Optional[int] = None,
api_key: Optional[str] = None,
) -> Tuple[str, int]:
"""生成聊天回复内容"""
if __openai_version <= "0.28.0":
openai.api_key = api_key
res = openai.ChatCompletion.create( # type: ignore
model=config.CHAT_MODEL,
messages=messages,
temperature=temperature,
top_p=top_p,
frequency_penalty=frequency_penalty,
presence_penalty=presence_penalty,
max_tokens=max_tokens,
stop=stop_words,
)
logger.debug(f"Chat response: {res}")
output = res.choices[0].message.content # type: ignore
token_consumption = res.usage.total_tokens # type: ignore
logger.info(f"请求消耗: {token_consumption} tokens")
assert output, "Chat response is empty"
return output, token_consumption
client = AsyncOpenAI(
api_key=api_key,
base_url=config.OPENAI_BASE_URL,
http_client=(
httpx.AsyncClient(
proxy=config.OPENAI_PROXY,
)
if config.OPENAI_PROXY
else None
),
)
res = await client.chat.completions.create(
model=config.CHAT_MODEL,
messages=messages, # type: ignore
temperature=temperature,
frequency_penalty=frequency_penalty,
presence_penalty=presence_penalty,
top_p=top_p,
max_tokens=max_tokens,
stop=stop_words,
)
output = res.choices[0].message.content
token_consumption = res.usage.total_tokens if res.usage else -1
logger.info(f"请求消耗: {token_consumption} tokens")
assert output, "Chat response is empty"
return output, token_consumption
| 3,640 | Python | .py | 98 | 27.663265 | 84 | 0.60518 | KroMiose/nonebot_plugin_dice_narrator | 8 | 0 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,237 | setup.py | yulunwu8_Optically-Shallow-Deep/setup.py | from setuptools import setup, find_packages
with open("readme.md", "r") as fh:
long_description = fh.read()
setup(
name='opticallyshallowdeep',
version='1.2.1',
author='Yulun Wu',
author_email='[email protected]',
description='Identify optically shallow and deep waters in satellite imagery',
long_description=long_description, # Long description read from the the readme file
long_description_content_type="text/markdown",
# packages=find_packages(),
packages=['opticallyshallowdeep','opticallyshallowdeep.models'],
include_package_data=True,
classifiers=[
'Programming Language :: Python :: 3'
],
python_requires='>=3.8',
install_requires=['geopandas','rasterio','tifffile','netCDF4','pyproj',
'joblib','scipy','matplotlib','imagecodecs','tensorflow']
)
| 865 | Python | .py | 21 | 35.285714 | 92 | 0.691937 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,238 | osd_test.py | yulunwu8_Optically-Shallow-Deep/tests/osd_test.py | # Go up by 2 directory and import
import sys
import os.path as path
two_up = path.abspath(path.join(__file__ ,"../.."))
sys.path.append(two_up)
import opticallyshallowdeep as osd
file_L1C = '/Users/yw/Local_storage/temp_OSD_test/S2B_MSIL1C_20230928T153619_N0509_R068_T17MNP_20230928T205247.SAFE'
file_L2R = '/Users/yw/Local_storage/temp_OSD_test/ACed/20230928/S2B_MSI_2023_09_28_15_44_58_T17MNP_L2R.nc'
folder_out = '/Users/yw/Local_storage/temp_OSD_test/temp_out5'
osd.run(file_L1C, folder_out, file_L2R=file_L2R)
| 538 | Python | .py | 10 | 50.6 | 116 | 0.763314 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,239 | netcdf_to_multiband_geotiff.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/netcdf_to_multiband_geotiff.py | import os
import numpy as np
import rasterio
from rasterio.crs import CRS
from rasterio.transform import from_origin
import netCDF4 as nc4
# from pyproj import Proj, transform
import pyproj
from .find_epsg import find_epsg
def netcdf_to_multiband_geotiff(netcdf_file, folder_out):
tif_base = os.path.basename(netcdf_file).replace('.nc','.tif')
output_geotiff_file = os.path.join(folder_out, tif_base)
if os.path.exists(output_geotiff_file):
print('Multi-band geotiff exists: ' + str(output_geotiff_file))
else:
print('Making multi-band geotiff: ' + str(output_geotiff_file))
value_for_nodata = -32768
# Open the NetCDF file
with nc4.Dataset(netcdf_file, "r") as nc:
wkt = nc.variables['transverse_mercator'].getncattr('crs_wkt')
sensor = nc.getncattr('sensor')
global_dims = nc.getncattr('global_dims')
height, width = global_dims.astype(int)
# Sensor-specific band configuration
if sensor in ['S2A_MSI', 'S2B_MSI']:
bands = [443,492,560,665,704,740,783,833,865,1614,2202] if sensor == 'S2A_MSI' else [442,492,559,665,704,739,780,833,864,1610,2186]
else:
raise ValueError("Unsupported sensor")
band_names = ['rhos_' + str(band) for band in bands]
data_array = np.ma.empty((len(bands), height, width))
for i, band_name in enumerate(band_names):
ar = nc.variables[band_name][:,:] * 10_000
ar[np.isnan(ar)] = value_for_nodata
data_array[i] = ar.astype('int16')
lat = nc.variables['lat'][:,:]
lon = nc.variables['lon'][:,:]
epsg_code = find_epsg(wkt)
# Initialize the projections
# proj_latlon = pyproj.Proj(proj='latlong', datum='WGS84')
# proj_utm = pyproj.Proj('epsg:' + str(epsg_code))
# xmin, ymin = pyproj.transform(proj_latlon, proj_utm, lon[10979,0], lat[10979,0])
# xmax, ymax = pyproj.transform(proj_latlon, proj_utm, lon[0,10979], lat[0,10979])
proj_latlon = pyproj.CRS(proj='latlong', datum='WGS84')
proj_utm = pyproj.CRS('epsg:' + str(epsg_code))
transformer = pyproj.Transformer.from_crs(proj_latlon, proj_utm)
# Transform the latitude and longitude to the target projection
# For this, find the min/max coordinates in the projected system
xmin, ymin = transformer.transform(lon[10979,0], lat[10979,0])
xmax, ymax = transformer.transform(lon[0,10979], lat[0,10979])
transform_ = from_origin(round(xmin-5,-1), round(ymax+5,-1), 10, 10)
with rasterio.open(
output_geotiff_file,
'w',
driver='GTiff',
height=height,
width=width,
count=len(bands),
dtype=rasterio.int16,
nodata = value_for_nodata,
crs = CRS.from_epsg(epsg_code),
transform=transform_
) as dst:
for i in range(len(bands)):
dst.write(data_array[i,:,:], i+1)
print('Done')
return output_geotiff_file | 3,324 | Python | .py | 66 | 37.909091 | 147 | 0.605263 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,240 | process_as_strips.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/process_as_strips.py | import os, gc, warnings, math
import numpy as np
import pandas as pd
import netCDF4 as nc4
import warnings
from joblib import Parallel, delayed
from datetime import datetime
import scipy
from scipy import ndimage
from scipy.ndimage import uniform_filter
from scipy.ndimage import binary_dilation
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model,load_model
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
from .make_vertical_strips import make_vertical_strips
def process_as_strips (full_img, image_path, if_SR, model_path, selected_columns, model_columns, file_in, cloud_list):
striplist=make_vertical_strips(full_img) #create a list of strips with overlap
RGBlist=[]
for n in range(len(striplist)):
print("Strip {}/5".format(n+1))
strip_p=process_img_to_rgb(striplist[n],image_path, if_SR, model_path, selected_columns, model_columns, file_in, cloud_list[n]) #output is RGB of image
RGBlist.append(strip_p) #append processed strip to RGB list
RGB_img=join_vertical_strips(RGBlist[0], RGBlist[1], RGBlist[2], RGBlist[3],RGBlist[4])
plot_RGB_img(RGB_img, image_path) #save the final image
return RGB_img
def process_img_to_rgb(img, file_path, if_SR, model_path, selected_columns, model_columns, file_in, img_cloud):
img,img_name,correction=correct_baseline(img,file_path, if_SR, file_in)#used on slices or whole images
final_cord=get_water_pix_coord(img,correction, if_SR, img_cloud) #getting coordinates of water pixels
if len(final_cord)==0:
RGB_img=make_blank_img(img)
return RGB_img
else:
# print(" {} {} Coordinates of non-glinty water pixels".format(time_tracker(start_time),len(final_cord)))
print(" Processing {} water pixels".format(len(final_cord)))
filter_image = process_image_with_filters(img, selected_columns) #creating a filter image to extract values from
edge_nodata_list = select_edge_and_buffer_no_data_pixels (img,correction, if_SR) #selecting pixels for slow processing
value_list,cord_list=create_df_for_processing_v2(selected_columns, img_name, img,filter_image, final_cord,edge_nodata_list,correction, model_columns)
del filter_image,edge_nodata_list,final_cord #line above makes coordinate and value list for making an image
gc.collect()
cord_list, pred_results, con_1=load_model_and_predict_pixels(value_list,model_path,cord_list, if_SR)
RGB_img=make_output_images_fast(cord_list, pred_results, con_1,img)#make RBG image
# print(" {} Finished model predictions".format(time_tracker(start_time)))
print(" Complete")
del cord_list, pred_results, con_1,img
gc.collect()
return RGB_img #this image is 0: OSW/ODW, 1:pred/prob, 2: Mask
def correct_baseline(img,file_path, if_SR, file_in):
from xml.dom import minidom
# if ACOLITE input
if if_SR:
# Open the NetCDF file
with nc4.Dataset(file_in, "r") as nc:
tile_code = nc.getncattr('tile_code')
img_name = tile_code[1:]
imgf = img
correction = 0
# if L1C input
else:
xml_path = os.path.join(file_in,'MTD_MSIL1C.xml')
xml = minidom.parse(xml_path)#look at xml for correction first
tdom = xml.getElementsByTagName('RADIO_ADD_OFFSET')#if this tag exists it is after baseline 4
tdom_URI = xml.getElementsByTagName('PRODUCT_URI')
S2_URI = tdom_URI[0].firstChild.nodeValue
img_name = S2_URI[39:44]
# If no RADIO_ADD_OFFSET
if len(tdom) == 0:
def Add_1000(img):
return img + 1000 #function for parallization in this function
chunk_size = len(img) // 4 #split into 4 for four cores, apply correction this way
chunks = [img[i:i + chunk_size] for i in range(0, len(img), chunk_size)]
imgf = np.concatenate(Parallel(n_jobs=4)(delayed(Add_1000)(chunk) for chunk in chunks), axis=0)
correction = 1000
'''Correction is a very important variable, since in some of the images we need to add 1000 in order to
correct for baseline 4. In these instances, 0 becomes 1000. There are times where we need to mask out 0 pixels
or avoid 0, so we use correction as a variable for pixels that are originally 0'''
# print(' Adjusted pixel value for before Baseline 4 processing')
del chunks
# If there is RADIO_ADD_OFFSET
else:
imgf = img
correction = 0
del img
return imgf, img_name, correction
def get_water_pix_coord(img,correction, if_SR, img_cloud):
#creates the mask of what is water by using Glint threshold, NDWI, NDSI...
if if_SR == False:
glint_t= 1500#this glint thresholds were used when training the model.
else:
glint_t= 500 #glint threshold as per ACOLITE
glint_coordinates = np.where(img[:, :, 9] < glint_t)#same threshold as in model
glr, glc = glint_coordinates
glint_coordinates_list = list(zip(glr, glc))#where not glint
del glr, glc,glint_coordinates
b3,b8,b11 = img[:, :, 2].astype(np.float32),img[:, :, 7].astype(np.float32),img[:, :, 9].astype(np.float32)
NDWI = (b3 - b8) / (b3 + b8 +1e-8) #NDWI with avoiding div 0
coordinates_NDWI = np.where(NDWI > 0)#where water (used to be 0)
ndwir, ndwic = coordinates_NDWI
coordinate_list_NDWI = list(zip(ndwir,ndwic))
del b8,NDWI, coordinates_NDWI,ndwir, ndwic
gc.collect()
NDSI = (b3 - b11) / (b3 + b11 +1e-8) #NDSI with avoiding div 0
coordinates_NDSI = np.where(NDSI < .42)#where not snow
ndsir, ndsic = coordinates_NDSI
coordinate_list_NDSI = list(zip(ndsir,ndsic))
del b3,b11,NDSI,coordinates_NDSI,ndsir,ndsic
gc.collect()
coordinates_cloud = np.where(np.invert(img_cloud))
cloudr, cloudc = coordinates_cloud
coordinate_list_cloud = list(zip(cloudr, cloudc))#where not glint
del cloudr, cloudc,coordinates_cloud
gc.collect()
# L1C
if if_SR == False:
ND_coordinates = np.column_stack(np.where(np.all((img > correction) & (img < 30000), axis=-1)))#where not no data (in any band)
ND_coordinates_list = list(map(tuple, ND_coordinates))
common_coordinates_set = set(glint_coordinates_list) & set(ND_coordinates_list)& set(coordinate_list_NDWI)& set(coordinate_list_NDSI)& set(coordinate_list_cloud)
common_coordinates_list = list(common_coordinates_set) # Convert set to list
del ND_coordinates,ND_coordinates_list,common_coordinates_set,glint_coordinates_list
# L2R
else:
ND_coordinates = np.column_stack(np.where(np.all((img > -30000) & (img < 30000), axis=-1)))#where not no data (in any band)
ND_coordinates_list = list(map(tuple, ND_coordinates))
Acolite_pix=np.column_stack(np.where(np.all((img <= 3000), axis=-1)))#threshold from ACOLITE
Acolite_pix_list = list(map(tuple, Acolite_pix))
common_coordinates_set = set(glint_coordinates_list)&set(Acolite_pix_list)&set(ND_coordinates_list)&set(coordinate_list_NDWI)& set(coordinate_list_cloud)
common_coordinates_list = list(common_coordinates_set)
del common_coordinates_set,Acolite_pix,Acolite_pix_list,ND_coordinates,ND_coordinates_list,glint_coordinates_list
gc.collect()
return common_coordinates_list
def make_blank_img(img):
Y_b, X_b, b = img.shape #sometimes the image is all no data or the correction value, in this instance, we make a blank image
RGB_img = np.zeros((Y_b, X_b, 3), dtype=np.uint8)
# print(' {} Blank strip added. No valid water pixels'.format(time_tracker(start_time)))
print(' No valid water pixels')
return RGB_img
def time_tracker(start_time):
return "{}sec".format(round((datetime.now() - start_time).total_seconds(), 2))
def process_image_with_filters(img, selected_columns):
height, width, bands = img.shape#the output of this is an image of the filters required for this model
filter_list = [value for value in selected_columns if value not in [["lat"], ["long"], ["lat_abs"]]]
output_bands = []
for band, kernel_size, filter_type in filter_list:
if filter_type is None:
filtered_band = img[:, :, band]
else:
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
filtered_band = apply_filter(img[:, :, band].astype(np.float32), kernel_size, filter_type)
filtered_band[filtered_band==-32768] = 32768
filtered_band[filtered_band<0] = 0
filtered_band = filtered_band.astype(np.uint16)#this means it is a single pixel
output_bands.append(filtered_band)#append to list of filters
del filtered_band
gc.collect()
del img
output_image = np.stack(output_bands, axis=-1)# Stack along the last dimension to make filter image
del output_bands
gc.collect()
return output_image.astype(np.uint16)
def apply_filter(image_band, kernel_size, filter_type):
if filter_type == 'sd':
return std_dev_filter(image_band, kernel_size)
elif filter_type == 'avg':
return uniform_filter(image_band, size=kernel_size, mode='mirror', origin=0) #avg filtering
def std_dev_filter(image_band, kernel_size):
mean = uniform_filter(image_band, size=kernel_size, mode='mirror', origin=0)#custom std filter that is fast
mean_of_squares = uniform_filter(image_band.astype(np.int32)**2, size=kernel_size, mode='mirror', origin=0)
std_deviation = np.sqrt(np.maximum(mean_of_squares - mean**2, 0)) #calculation of std
del mean, mean_of_squares
gc.collect()
return std_deviation
def select_edge_and_buffer_no_data_pixels (img,correction, if_SR):
b3 = img[:, :, 2].copy()#function selects the edge and no data and makes a buffer. these pixels are processed the slow method
if if_SR == False:
condition_mask = np.logical_or(b3 <=correction, b3 > 30000) #filter for no data pixels -- this is simple since more complex can cause errors
else:
condition_mask = np.logical_or(b3 <-30000, b3 > 30000) #filter for nodata pixels
dilated_mask = binary_dilation(condition_mask, iterations=8)#mask within 8 pixels of bad pixel
del condition_mask
final_coordinates_condition = np.argwhere(dilated_mask) #coordinates of bad pixels
del dilated_mask
edge_mask = np.zeros_like(b3, dtype=bool)#Create an edge mask
edge_mask[:8, :] = True #Top edge
edge_mask[-8:, :] = True #Bottom edge
edge_mask[:, :8] = True #Left edge
edge_mask[:, -8:] = True #Right edge
final_coordinates_edge = np.argwhere(edge_mask)# Get coordinates of the pixels in the edge mask
del edge_mask,b3
edge_nodata_list = np.unique(np.concatenate([final_coordinates_condition, final_coordinates_edge]), axis=0).tolist()
edge_nodata_list = list(map(tuple, edge_nodata_list))#get list of unique bad pixels
del final_coordinates_condition
gc.collect()
return edge_nodata_list
def create_df_for_processing_v2 (selected_columns, img_name, img,filter_image, final_cord,edge_nodata_list,correction, model_columns):
start_time = datetime.now()
value_list,cord_list=[],[]
columns_to_add = [['lat_abs'], ['lat'], ['long']]
edge_nodata_list = list(set(edge_nodata_list) & set(final_cord))
final_cord_not_in_edge_nodata = list(set(final_cord) - set(edge_nodata_list))#edge pixels and near no data need special treatment
processed_edge_nodata_list = Parallel(n_jobs=-1)(delayed(process_edge_nodata_pixel)(img_name,cord,img,correction, selected_columns, model_columns) for cord in edge_nodata_list)
if len(processed_edge_nodata_list)>0:
values, cords = zip(*processed_edge_nodata_list)
value_list.extend(values)
cord_list.extend(cords)
del edge_nodata_list,processed_edge_nodata_list
final_cord_not_in_edge_nodata_array=np.array(final_cord_not_in_edge_nodata)#these are middle pixels and we can extract filter img values
y_values = final_cord_not_in_edge_nodata_array[:, 0]# Extract y, x coordinates directly using array indexing
x_values = final_cord_not_in_edge_nodata_array[:, 1]
pixel_values = filter_image[y_values, x_values, :].tolist()# Process pixels and other operations using NumPy vectorized operations
loc_list, labelling = get_location_values(img_name)
for column_name in columns_to_add:
if column_name in selected_columns:
value_to_insert = int(loc_list[1]) if column_name == ['lat'] else int(loc_list[0]) if column_name == ['long'] else int(loc_list[2])
for sublist in pixel_values:
sublist.insert(0, value_to_insert)# Insert the location value at position 1 in all lists within pixel_values
del y_values,x_values
gc.collect()
return value_list+pixel_values,cord_list+final_cord_not_in_edge_nodata
def process_edge_nodata_pixel(img_name,cord,img,correction, selected_columns, model_columns):
y, x = cord[0], cord[1]#this is a function for joblib parallelization
values, l = get_values_for_pixel(selected_columns, img_name, img, y, x,correction, model_columns)
return values, cord
def get_values_for_pixel(selected_columns, img_name, img, y, x,correction, model_columns):
values, labels = [], []#iterate throught the column names
for n in range(len(selected_columns)):
if selected_columns[n][0] in ['long', 'lat', 'lat_abs']:
location_list, labelling = get_location_values(img_name)#address the location values
position = labelling.index(selected_columns[n][0])#appending location information
values.append(location_list[position])
labels.append(labelling[position])
else:
band = img[:, :, int(selected_columns[n][0])]#get bands, wsize, and function from column name
window_size, function = int(selected_columns[n][1]), selected_columns[n][2]
mid_size = window_size / 2
Lv, Sv = math.ceil(mid_size), math.floor(mid_size)#this section alters the window for edge pixels
region = band[max(0, y - Sv):min(y + Lv, band.shape[0]), max(0, x - Sv):min(x + Lv, band.shape[1])]
result=region
zero_value_mask = np.any(img[max(0, y - Sv):min(y + Lv, img.shape[0]),
max(0, x - Sv):min(x + Lv, img.shape[1]), :] == correction, axis=-1) #use of correction to find if any pixels are originally 0
if np.any((region <= correction) | (region > 30000) | zero_value_mask):
condition_mask = ((region <= correction) | (region > 30000) | zero_value_mask)
mask = ~((region <-30000) | (region > 30000)| zero_value_mask)#mask out no data pixels
result = region[mask]
if len(result) == 0:
values.append(0)
elif function == 'avg': #process if function is avg
values.append(int(np.average(result, weights=np.ones_like(result) / result.size))) #calculate average
elif function == 'sd':
std_value = np.std(result)#process if function is sd
if not np.isnan(std_value):
values.append(int(std_value)) #calculate std
else:
values.append(0)#Handle NaN case
elif function == None:
values.append(band[y,x])#process if function it is pixel value
del result,region,band
labels.append(model_columns[n])
if labelling == False:
labels = []#save space by returning empty labels
return values, labels
def get_location_values(img_name):
latitude_bands = {'C': -76,'D': -68,'E': -60,'F': -52,'G': -44,'H': -36,'J': -28,'K': -20,'L': -12,'M': -4,'N': 4,'P': 12,'Q': 20,'R': 28,'S': 36,'T': 44,'U': 52,'V': 60,'W': 68,'X': 76,}
long_str=str(get_mean_longitude(img_name[:2]))#gets location info from name string
long, lat=get_mean_longitude(img_name[:2]), latitude_bands[img_name[2]]
lat_abs=abs(lat) #calculating absolute latitude
location_list=[long,lat,lat_abs]
labelling=['long','lat','lat_abs']
del long_str,long, lat,lat_abs
return location_list,labelling
def get_mean_longitude(utm_zone):
utm_zone=int(utm_zone)
if 1 <= utm_zone <= 60: #Check if the input UTM zone is within the valid range (1-60)
mean_longitude = 180 - (utm_zone - 0.5) * 6#calculate the mean longitude for the given UTM zone
return int(mean_longitude)
else:
return None# Return None for invalid input
def load_model_and_predict_pixels(value_list, model_path, cord_list, if_SR):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
loaded_model=load_tf_model(model_path, if_SR)
chunk_size = len(value_list) // 4 #breaking it into chunks makes it take up less ram
chunks_value = [value_list[i:i + chunk_size] for i in range(0, len(value_list), chunk_size)]
chunks_cord = [cord_list[i:i + chunk_size] for i in range(0, len(cord_list), chunk_size)]
result_chunks = []
for chunk_value, chunk_cord in zip(chunks_value, chunks_cord):
value_arr= (np.array(chunk_value)/10000).astype('float16')
df = pd.DataFrame(value_arr)
with tf.device('/cpu:0'):
pred_proba = loaded_model.predict_on_batch(df)#predprob in chunk
pred_proba_np = np.array(pred_proba)
con_1 = (pred_proba_np * 100).astype(int)#get our confidence in the way we like it
pred_results = [1 if i >= 50 else 0 for i in con_1]#getting prediction results from pred_prob
result_chunks.append((chunk_cord, pred_results, con_1))#append chunk
del pred_results,con_1,pred_proba_np,df,value_arr
cord_list, pred_results, con_1 = zip(*result_chunks)
cord_list = np.concatenate(cord_list)
pred_results = np.concatenate(pred_results)
con_1 = np.concatenate(con_1)
del chunks_value, chunks_cord, loaded_model, chunk_size
return cord_list.tolist(), pred_results.tolist(), con_1.tolist()
def load_tf_model(model_path, if_SR):
if if_SR == False:
model=d6_model(32,0.01)
model.load_weights(model_path)
return model
else:
model=d4_model(64,0.01)
model.load_weights(model_path)
return model
def d6_model(u1,LR): # the last tested. good for more data.
INPUT=Input(shape=(20,))
d1=Dense(u1, activation='LeakyReLU')(INPUT)
d2=Dense(u1, activation='LeakyReLU')(d1)
d3=Dense(u1, activation='LeakyReLU')(d2)
d4=Dense(u1, activation='LeakyReLU')(d3)
d5=Dense(u1, activation='LeakyReLU')(d4)
d6=Dense(u1, activation='LeakyReLU')(d5)
d7=Dense(1, activation='sigmoid')(d6)
model=Model(inputs=[INPUT], outputs=[d7])
return model
def d4_model(u1,LR): # the last tested. good for more data.
INPUT=Input(shape=(13,))
d1=Dense(u1, activation='LeakyReLU')(INPUT)
d2=Dense(u1, activation='LeakyReLU')(d1)
d3=Dense(u1, activation='LeakyReLU')(d2)
d4=Dense(u1, activation='LeakyReLU')(d3)
d5=Dense(1, activation='sigmoid')(d4)
model=Model(inputs=[INPUT], outputs=[d5])
return model
def make_output_images_fast(cord_list, preds, pred_probs, img):
Y_b, X_b, b = img.shape
pred_image = np.zeros((Y_b, X_b, 1), dtype=np.uint8)#makes blank images
predprob_image = np.zeros((Y_b, X_b, 1), dtype=np.uint8)
masked_image = np.zeros((Y_b, X_b, 1), dtype=np.uint8)
cords = np.array(cord_list)
pred_image[cords[:, 0], cords[:, 1], :] = np.array(preds).reshape(-1, 1) #applies the values to the coordinate
predprob_image[cords[:, 0], cords[:, 1], :] = np.array(pred_probs).reshape(-1, 1)
masked_image[cords[:, 0], cords[:, 1], :] = 1 #sets all pixels that were used for OSW/ODW ==1
RGB_img = np.concatenate([pred_image, predprob_image, masked_image], axis=-1) #make RGB image
del pred_image,predprob_image,masked_image,cords
gc.collect()
return RGB_img
def join_vertical_strips(strip1, strip2, strip3, strip4, strip5):
overlap_size = 16 #this is done so strips do not have artifacts from kernals
strip1_cropped = strip1[:, :strip1.shape[1] -overlap_size//2, :]#crop 8 from left
strip2_cropped = strip2[:, overlap_size//2: -overlap_size//2, :]#crop 8 from left and 8 right
strip3_cropped = strip3[:, overlap_size//2: -overlap_size//2, :]#crop 8 left and 8 right
strip4_cropped = strip4[:, overlap_size//2: -overlap_size//2, :]#crop 8 left and 8 right
strip5_cropped = strip5[:, overlap_size//2:, :] #crop 8 right, subtracted 48pix
joined_array = np.hstack((strip1_cropped, strip2_cropped, strip3_cropped, strip4_cropped,strip5_cropped))
return joined_array
def plot_RGB_img(RGB_img, image_path):
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 3, figsize=(10, 10), sharex=True, sharey=True)
ax[0].imshow(RGB_img[:,:,0])#plotting to see what OSW/ODW looks like
ax[0].set_title('Prediction based on 0.5 threshold')
ax[1].imshow(RGB_img[:,:,1])
ax[1].set_title('Prediction probability')
ax[2].imshow(RGB_img[:,:,2])
ax[2].set_title('Non-water mask')
# plt.show()
out_path = image_path.replace('.tif','.png')
plt.savefig(out_path) | 21,507 | Python | .py | 364 | 51.467033 | 191 | 0.673171 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,241 | run.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/run.py | import sys, os, gc, time
import tifffile as tif
from importlib.metadata import version
from .make_multiband_image import make_multiband_image
from .check_transpose import check_transpose
from .process_as_strips import process_as_strips
from .parse_string import parse_string
from .write_georef_image import write_georef_image
from .netcdf_to_multiband_geotiff import netcdf_to_multiband_geotiff
from .make_vertical_strips import make_vertical_strips
from .cloud_mask import cloud_mask
def run(file_L1C, folder_out, file_L2R = None, to_log=True):
### Check the two
if not os.path.exists(file_L1C):
sys.exit('file_L1C does not exist: ' + str(file_L1C))
# folder_out: if not exist -> create it
if not os.path.exists(folder_out):
os.makedirs(folder_out)
### Print all metadata/settings and save them in a txt file
if to_log:
# Start logging in txt file
orig_stdout = sys.stdout
if file_L2R is None:
log_base = os.path.basename(file_L1C).replace('.safe','.txt').replace('.SAFE','.txt')
else:
log_base = os.path.basename(file_L2R).replace('.nc','.txt')
log_base = 'OSD_log_'+ log_base
log_file = os.path.join(folder_out,log_base)
class Logger:
def __init__(self, filename):
self.console = sys.stdout
self.file = open(filename, 'w')
self.file.flush()
def write(self, message):
self.console.write(message)
self.file.write(message)
def flush(self):
self.console.flush()
self.file.flush()
sys.stdout = Logger(log_file)
# Metadata
print('\n=== ENVIRONMENT ===')
print('OSD version: ' + str(version('opticallyshallowdeep')))
print('Start time: ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
print('file_L1C: ' + str(file_L1C))
print('file_L2R: ' + str(file_L2R))
print('folder_out: ' + str(folder_out))
print('\n=== PRE-PROCESSING ===')
# Columns
GTOA_model_columns=['long', 'lat_abs', 'B2-w_15_sd', 'B3-w_3_sd', 'B3-w_7_avg', 'B3-w_9_avg', 'B3-w_11_sd', 'B3-w_15_sd', 'B4-w_5_avg', 'B4-w_11_sd', 'B4-w_13_avg', 'B4-w_13_sd', 'B4-w_15_sd', 'B5-w_13_sd', 'B5-w_15_sd', 'B8-w_9_sd', 'B8-w_13_sd', 'B8-w_15_sd', 'B11-w_9_avg', 'B11-w_15_sd']
GACOLITE_model_columns= ['lat_abs', 'B1-w_15_sd', 'B2-w_1', 'B3-w_5_sd', 'B3-w_7_sd', 'B3-w_13_sd', 'B3-w_15_sd', 'B4-w_15_sd', 'B5-w_11_avg', 'B5-w_15_avg', 'B5-w_15_sd', 'B8-w_13_sd', 'B11-w_15_avg']
### Take input path and identify model path
# If ACOLITE L2R is not provided
if file_L2R is None:
if_SR = False
model = 'models/TOA.h5'
model_columns = GTOA_model_columns
file_in = file_L1C
# make multiband_image
image_path = make_multiband_image(file_L1C,folder_out)
# If ACOLITE L2R is provided
else:
if not os.path.exists(file_L2R):
sys.exit('file_L2R does not exist: ' + str(file_L2R))
if_SR = True
model = 'models/SR.h5'
model_columns = GACOLITE_model_columns
file_in = file_L2R
# make multiband_image
image_path = netcdf_to_multiband_geotiff(file_L2R, folder_out)
# make it a list of lists
selected_columns = [parse_string(s) for s in model_columns]
print('If input is SR product: ' +str(if_SR))
model_path = os.path.join(os.path.dirname(__file__), model)
print('Trained model to use: ' +str(model_path))
# read image
image = tif.imread(image_path, dtype='int16')
# check
image=check_transpose(image)
# make cloud mask
img_cloud = cloud_mask(file_L1C)
cloud_list = make_vertical_strips(img_cloud)
print('\n=== PREDICTING OSW/ODW ===')
# create strips and process them -- make big RGB image
RGB_img=process_as_strips(image, image_path, if_SR, model_path, selected_columns, model_columns, file_in, cloud_list)
# write as geotiff
write_georef_image(image_path,RGB_img)
print("Image OSW/ODW completed, dimension: {}".format(RGB_img.shape))
print('Finish time: ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
del RGB_img
gc.collect()
# stop logging
if to_log: sys.stdout = orig_stdout
| 4,504 | Python | .py | 93 | 39.408602 | 295 | 0.618958 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,242 | find_epsg.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/find_epsg.py | def find_epsg(data):
# Use regex to extract the desired part
import re
from pyproj import CRS
# Pattern to match the text between "CONVERSION[" and the first comma following
pattern = r'CONVERSION\["(.*?)",'
# Search for the pattern in the data string
match = re.search(pattern, data)
# Extract the matched text
extracted_text = match.group(1) if match else None
extracted_text
# Define the CRS name
crs_name = "WGS 84 / " + str(extracted_text)
try:
# Use pyproj to find the CRS object from the given CRS name
crs = CRS.from_string(crs_name)
# Extract the EPSG code
epsg_code = crs.to_epsg()
if epsg_code:
# return f"The EPSG code for '{crs_name}' is {epsg_code}."
return epsg_code
else:
print( "EPSG code could not be found.")
except Exception as e:
return f"An error occurred: {str(e)}"
| 990 | Python | .py | 25 | 30.56 | 83 | 0.629386 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,243 | parse_string.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/parse_string.py | import re
def parse_string(s):
if s.lower() in ["lat", "long", "lat_abs"]:
return [s.lower()]#parses the column names for our model and makes into things that our scripts can interpret
match = re.match(r'B(\d+)([a-zA-Z]?)-w_(\d+)(_?(\w+))?', s) #used to parse model_column names
if match:
groups = match.groups()
first_group = f'{groups[0]}{groups[1]}' if groups[1] else groups[0]
first_group = first_group.replace('8a', '9')# Replace '8a' with '9'
try:
first_group_int = int(first_group)# Check if first_group is a valid integer
if first_group_int > 10:
first_group_int -= 2
else:
first_group_int -= 1
except ValueError:
first_group_int = first_group
return [first_group_int, int(groups[2]), groups[4]] if groups[4] else [first_group_int, int(groups[2]), None]
else:
return None | 939 | Python | .py | 20 | 38 | 117 | 0.581522 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,244 | write_georef_image.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/write_georef_image.py | import rasterio, gc
import numpy as np
def write_georef_image(image_path,RGB_img):
output_name = image_path.replace('.tif','_OSW_ODW.tif')
raster_with_ref = rasterio.open(image_path) # Open the raster with geospatial information
crs = raster_with_ref.crs # Get the CRS (Coordinate Reference System) from the raster
epsg_from_raster = crs.to_epsg() # Use the EPSG code from the CRS
height, width, _ = RGB_img.shape
count = 1
dtype = RGB_img.dtype
transform = raster_with_ref.transform# Use the same transform as the reference raster
output_band = RGB_img[:,:,1]
mask_band = RGB_img[:,:,2]
output_band[mask_band == 0] = 255
with rasterio.open(output_name, "w",driver="GTiff", height=height, width=width, nodata=255,
count=count, dtype=dtype, crs=crs, transform=transform) as dst:
dst.write(output_band, 1)
del raster_with_ref
gc.collect() | 954 | Python | .py | 19 | 43.052632 | 95 | 0.682119 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,245 | make_vertical_strips.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/make_vertical_strips.py | import numpy as np
def make_vertical_strips(full_img):
'''use to save ram, process bigger images faster, and it overlaps so middle image is not
distorted from how edge pixels are handled'''
# number of dimensions
n_dim = full_img.ndim
if n_dim == 2:
height, width = full_img.shape #this is done so strips do not have artifacts from kernals
overlap_size = 16 #size of overlap, max tile size is 15, so there is a 1px buffer
strip1 = full_img[:, :width//5 + overlap_size]#left overlap
strip2 = full_img[:, width//5: 2*width//5+ overlap_size]# left half overlap
strip3 = full_img[:, 2*width//5:3*width//5 + overlap_size]#left overlap
strip4 = full_img[:, 3*width//5:4*width//5+ overlap_size]#left overlap
strip5 = full_img[:, 4*width//5:width]# no overlap
elif n_dim == 3:
height, width, _ = full_img.shape #this is done so strips do not have artifacts from kernals
overlap_size = 16 #size of overlap, max tile size is 15, so there is a 1px buffer
strip1 = full_img[:, :width//5 + overlap_size, :]#left overlap
strip2 = full_img[:, width//5: 2*width//5+ overlap_size, :]# left half overlap
strip3 = full_img[:, 2*width//5:3*width//5 + overlap_size, :]#left overlap
strip4 = full_img[:, 3*width//5:4*width//5+ overlap_size, :]#left overlap
strip5 = full_img[:, 4*width//5:width, :]# no overlap
else:
import sys
sys.exit('Unknown dimension(s) of input imagery to be splited into strips')
return [strip1,strip2,strip3,strip4,strip5] | 1,617 | Python | .py | 26 | 53.846154 | 100 | 0.645449 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,246 | make_multiband_image.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/make_multiband_image.py | import numpy as np
import os
import glob
import rasterio
import gc
# make multiband images in output dir
def make_multiband_image(file_in,folder_out):
basename = os.path.basename(file_in).rstrip(".SAFE")
# output path
imageFile = os.path.join(folder_out,basename) + '.tif'
if os.path.exists(imageFile):
print('Multi-band geotiff exists: ' + str(imageFile))
else:
print('Making multi-band geotiff: ' + str(imageFile))
band_numbers = ['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B11', 'B12']
S2Files = [glob.glob(f'{file_in}/**/IMG_DATA/**/*{band}.jp2', recursive=True)[0] for band in band_numbers]
b2File = S2Files[1]
# Get image info
band2 = rasterio.open(b2File) # b2 has 10m spatial resolution
crs = band2.crs
res = int(band2.transform[0])
arrayList = []
for bandFile in S2Files:
# print("Reading band: {}".format(bandFile))
band = rasterio.open(bandFile)
ar = band.read(1)
bandRes = int(band.transform[0])
if bandRes == res:
ar = ar.astype('int16')
arrayList.append(ar)
elif bandRes > res:
finerRatio = int(bandRes / res)
ar = np.kron(ar, np.ones((finerRatio, finerRatio), dtype='int16')).astype('int16')
arrayList.append(ar)
del ar
band.close()
stack = np.dstack(arrayList)# To write to file, rasterio expects (bands, rows, cols), while dstack creates (rows, cols, bands)
stackTransposed = stack.transpose(2, 0, 1)
with rasterio.Env():
profile = band2.profile #use band2 as an example
profile.update(driver="GTiff",
count=len(S2Files),
compress="lzw")
with rasterio.open(imageFile, 'w', **profile) as dst:
dst.write(stackTransposed)
band2.close()
del stack,stackTransposed,S2Files,band2
gc.collect()
print('Done')
return imageFile
| 2,120 | Python | .py | 50 | 32.12 | 134 | 0.577821 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,247 | cloud_mask.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/cloud_mask.py | import os, sys
import rasterio
import numpy as np
from scipy import ndimage
def cloud_mask(file_L1C, buffer_size = 8):
print('Making cloud mask...')
files = os.listdir(file_L1C)
metadata = {}
metadata['file_L1C'] = file_L1C
# Identify paths
for i, fname in enumerate(files):
tmp = fname.split('.')
path = '{}/{}'.format(file_L1C,fname)
# Granules
if (fname == 'GRANULE'):
granules = os.listdir(path)
# Check if there is only one granule file
n_granule = 0
for granule in granules:
if granule[0]=='.':continue
n_granule += 1
if n_granule>1: sys.exit('Warning: more than 1 granule')
metadata['granule'] = '{}/{}/{}/IMG_DATA/'.format(file_L1C,fname,granule)
metadata['MGRS_tile'] = granule.split('_')[1][1:]
metadata['QI_DATA'] = '{}/{}/{}/QI_DATA'.format(file_L1C,fname,granule)
# # MGRS
# tile = metadata['MGRS_tile'] + '54905490'
# d = m.toLatLon(tile)
# metadata['lat'] = d[0]
# metadata['lon'] = d[1]
# Band files
image_files = os.listdir(metadata['granule'])
for image in image_files:
if image[0]=='.':continue
if image[-4:]=='.xml':continue
tmp = image.split('_')
metadata[tmp[-1][0:3]] = '{}/{}/{}/IMG_DATA/{}'.format(file_L1C,fname,granule,image)
### Load built-in mask
gml_file = "{}/MSK_CLOUDS_B00.gml".format(metadata['QI_DATA'])
jp2_file = "{}/MSK_CLASSI_B00.jp2".format(metadata['QI_DATA'])
# For imagery before processing baseline 4: Jan 25, 2022
if os.path.exists(gml_file):
# Built-in cloud mask
import geopandas as gpd
from rasterio.features import geometry_mask
# Load a raster as the base of the mask
image = metadata['B02']
with rasterio.open(image) as src:
# Read the raster data and transform
raster_data = src.read(1)
transform = src.transform
crs = src.crs
try:
# Read GML file
gdf = gpd.read_file(gml_file)
# Create a mask using the GML polygons and the GeoTIFF metadata
mask_cloud = geometry_mask(gdf['geometry'], transform=transform, out_shape=raster_data.shape, invert=True)
# Sometimes the GML file contains no information, assume no clouds in such case
except:
mask_cloud = np.zeros_like(raster_data)
# For imagery processing baseline 4
elif os.path.exists(jp2_file):
band_ds = rasterio.open(jp2_file)
band_array = band_ds.read(1)
mask_cloud = band_array == 1
mask_cloud = np.repeat(np.repeat(mask_cloud, 6, axis=0), 6, axis=1)
else:
sys.exit('Warning: cloud mask missing in {}.'.format(metadata['QI_DATA']))
# To buffer: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.binary_dilation.html
struct1 = ndimage.generate_binary_structure(2, 1)
mask_cloud_buffered = ndimage.binary_dilation(mask_cloud, structure=struct1,iterations=buffer_size).astype(mask_cloud.dtype)
print('Done')
return mask_cloud_buffered | 3,560 | Python | .py | 73 | 35.356164 | 128 | 0.578416 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,248 | check_transpose.py | yulunwu8_Optically-Shallow-Deep/opticallyshallowdeep/check_transpose.py | # Always output row, column, band
def check_transpose(img):
#if the #of bands is greater than the number of x or y cords
y,x,b=img.shape
if b>y or b>x:
img=img.transpose(1,2,0)
return img | 213 | Python | .py | 7 | 25.857143 | 64 | 0.657005 | yulunwu8/Optically-Shallow-Deep | 8 | 2 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,249 | limuloid.py | IohannesArnold_limuloid/limuloid.py | #! /usr/bin/env python
# limuloid.py -- script to make LLMs conform to DTDs
# Copyright (C) John Arnold
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import argparse
import string
import sys
from enum import auto, Enum
from lxml import etree
class Usage(Enum):
REQUIRED = auto()
ALLOWED = auto()
FORBIDDEN = auto()
def _sanatize_ident(ident_in):
good_chars = [c for c in ident_in.casefold() if c in string.ascii_lowercase]
return "".join(good_chars)
def _handle_element_content(
allow_cdata, misc, output_buffer, content, indent_len, new_group=False
):
if new_group:
output_buffer.write(" " * indent_len)
output_buffer.write("(\n")
indent_len += 2
output_buffer.write(" " * indent_len)
output_buffer.write(f"({ ' | '.join(misc) })*\n")
if content.type == "element":
output_buffer.write(" " * indent_len)
output_buffer.write(f"element-{_sanatize_ident(content.name)}")
elif content.type == "pcdata":
output_buffer.write(" " * indent_len)
ents = ["Reference"] + misc[1:]
if allow_cdata:
ents.append("CDSect")
output_buffer.write(f"(CharData? (({ ' | '.join(ents) }) CharData?)*)")
elif content.type == "seq":
_handle_element_content(
allow_cdata, misc, output_buffer, content.left, indent_len
)
output_buffer.write("\n")
output_buffer.write(" " * indent_len)
output_buffer.write(f"({ ' | '.join(misc) })*\n")
_handle_element_content(
allow_cdata,
misc,
output_buffer,
content.right,
indent_len,
content.right.type == "or",
)
elif content.type == "or":
_handle_element_content(
allow_cdata,
misc,
output_buffer,
content.left,
indent_len,
content.left.type == "seq",
)
output_buffer.write(" |\n")
_handle_element_content(
allow_cdata,
misc,
output_buffer,
content.right,
indent_len,
content.right.type == "seq",
)
if new_group:
output_buffer.write("\n")
output_buffer.write(" " * indent_len)
output_buffer.write(f"({ ' | '.join(misc) })*\n")
indent_len -= 2
output_buffer.write(" " * indent_len)
output_buffer.write(")")
if content.occur == "opt":
output_buffer.write("?")
elif content.occur == "mult":
output_buffer.write("*")
elif content.occur == "plus":
output_buffer.write("+")
def create_grammar(
dtd_pointer,
output_buffer,
allow_comments=False,
allow_pi=False,
allow_cdata=True,
xml_header=Usage.ALLOWED,
doctype=Usage.REQUIRED,
):
if not isinstance(xml_header, Usage):
xml_header = Usage[str(xml_header).upper()]
if not isinstance(doctype, Usage):
doctype = Usage[str(doctype).upper()]
dtd = etree.DTD(dtd_pointer)
misc = ["S"]
root_element = None
output_buffer.write(
r"""# Character Range
# Diverges from the official spec by not including
# '-' (\x2D) '>' (\x3E) '?' (\x3F) ']' (\x5F)
# because the llama.cpp grammar is only additive, and in the official spec those
# chars are excluded elsewhere.
Char ::= "\x09" | "\x0A" | "\x0D" | [\x20-\x2C] | [\x2E-\x3D] | [\x40-\x5E] |
[\x60-\uD7FF] | [\uE000-\uFFFD] | [\U00010000-\U0010FFFF]
# White Space
S ::= ( "\x20" | "\x09" | "\x0D" | "\x0A" )+
# Names and Tokens
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [\xC0-\xD6] | [\xD8-\xF6] |
[\xF8-\u02FF] | [\u0370-\u037D] | [\u037F-\u1FFF] |
[\u200C-\u2FEF] | [\u3001-\uD7FF] | [\uF900-\uFDCF] |
[\uFDF0-\uFFFD] | [\U00010000-\U000EFFFF]
NameChar ::= NameStartChar | "-" | "." | [0-9] | "\xB7" |
[\u0300-\u036F] | [\u203F-\u2040]
Name ::= NameStartChar (NameChar)*
Names ::= Name ("\x20" Name)*
Nmtoken ::= (NameChar)+
Nmtokens ::= Nmtoken ("\x20" Nmtoken)*
# Literals
AttValue ::= ( "\x22" ([^<&\x22] | Reference)* "\x22" ) |
( "\x27" ([^<&\x27] | Reference)* "\x27" )
# Character Reference
CharRef ::= ("&#" [0-9]+ ";") | ("&#x" [0-9a-fA-F]+ ";")
# Entity Reference
Reference ::= EntityRef | CharRef
EntityRef ::= "&" Name ";"
# Character Data
CharData ::= (("]]" [^>]) | [^<&])*
"""
)
if allow_comments:
misc.append("Comment")
output_buffer.write(
r"""
# Comments
commentChar ::= Char | [>?\x5F]
Comment ::= "<!--" (commentChar | ("-" commentChar))* "-->"
"""
)
if allow_pi:
misc.append("PI")
output_buffer.write(
r"""
# Processing Instructions
piChar ::= Char | [\x2D\x5F]
PI ::= "<?" PITarget (S (("?" piChar) | (piChar | ">"))* )? "?>"
PITarget ::= ([^Xx] [^Mm] [^Ll]) | Name
"""
)
if allow_cdata:
output_buffer.write(
r"""
# CDATA Sections
cdChar ::= Char | [?\x2D]
CDSect ::= CDStart CData CDEnd
CDStart ::= "<![CDATA["
CData ::= ((Char | ">") | "]" (Char | ">" | ("]" Char)))*
CDEnd ::= "]]>"
"""
)
match xml_header:
case Usage.REQUIRED:
xml_decl = "XMLDecl Misc*"
case Usage.ALLOWED:
xml_decl = "XMLDecl? Misc*"
case Usage.FORBIDDEN:
xml_decl = "Misc*"
match doctype:
case Usage.REQUIRED:
prolog = f"{xml_decl} doctypedecl Misc*"
case Usage.ALLOWED:
prolog = f"{xml_decl} (doctypedecl Misc*)?"
case Usage.FORBIDDEN:
prolog = xml_decl
output_buffer.write(
f"""
# Prolog
prolog ::= {prolog}
XMLDecl ::= "<?xml" VersionInfo EncodingDecl? SDDecl? S? "?>"
VersionInfo ::= S "version" Eq ( ("\\x27" VersionNum "\\x27") |
("\\x22" VersionNum "\\x22") )
Eq ::= S? "=" S?
VersionNum ::= "1.0"
Misc ::= { " | ".join(misc) }
# Standalone Document Declaration
SDDecl ::= S "standalone" Eq ( ("\\x27" ("yes" | "no") "\\x27") |
("\\x22" ("yes" | "no") "\\x22") )
# Encoding Declaration
EncodingDecl ::= S "encoding" Eq ("\\x22" EncName "\\x22" | "\\x27" EncName "\\x27")
EncName ::= [A-Z] | [a-z] ([A-Z] | [a-z] | [0-9] | [._] | "-")*
# Element Schema
"""
)
# TODO DTD (external and internal)
for element in dtd.elements():
if root_element is None:
root_element = element.name
ident = f"element-{_sanatize_ident(element.name)}"
indent_len = len(ident) + 5
output_buffer.write(f'{ident} ::= "<{element.name}" ')
attributes = element.attributes()
if len(attributes) > 0:
output_buffer.write("(\n")
for attribute in element.attributes():
output_buffer.write(" " * (indent_len + 2))
output_buffer.write(
f"(S {ident}-attribute-{_sanatize_ident(attribute.name)})"
)
if attribute.default != "required":
output_buffer.write("?")
output_buffer.write("\n")
output_buffer.write(" " * indent_len)
output_buffer.write(") ")
if element.type == "empty":
output_buffer.write('S? "/>"\n')
else:
output_buffer.write('S? ">" (\n')
new_group = element.content.type != "pcdata"
_handle_element_content(
allow_cdata,
misc,
output_buffer,
element.content,
indent_len + 2,
new_group,
)
output_buffer.write("\n")
output_buffer.write(" " * indent_len)
output_buffer.write(f') "</{element.name}" S? ">"\n')
for attribute in element.attributes():
output_buffer.write(f"{ident}-attribute-{_sanatize_ident(attribute.name)}")
output_buffer.write(' ::= "')
output_buffer.write(attribute.name)
output_buffer.write('" Eq AttValue\n')
output_buffer.write(
f"""
# Document Type Definition
doctypedecl ::= "<!DOCTYPE" S "{root_element}" S? ">"
root ::= prolog element-{_sanatize_ident(root_element)}
"""
)
def _handle_cli():
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
parser.add_argument(
"-i",
"--input",
type=argparse.FileType("r"),
default="-",
help="Input DTD file (default STDIN)",
dest="dtd_pointer",
)
parser.add_argument(
"-o",
"--output",
type=argparse.FileType("w"),
default="-",
help="GBNF output location (default STDOUT)",
dest="output_buffer",
)
parser.add_argument(
"--allow-comments",
action=argparse.BooleanOptionalAction,
help="Whether to allow comments in the generated XML (default False)",
)
parser.add_argument(
"--allow-pi",
action=argparse.BooleanOptionalAction,
help="Whether to allow XML processing instructions in the generated XML (default False)",
)
parser.add_argument(
"--allow-cdata",
action=argparse.BooleanOptionalAction,
help="Whether to allow CData sections in the generated XML (default True)",
)
parser.add_argument(
"--xml-header",
type=str.upper,
choices=["REQUIRED", "ALLOWED", "FORBIDDEN"],
help="Whether to include an XML header in the generated XML (default ALLOWED)",
)
parser.add_argument(
"--doctype",
type=str.upper,
choices=["REQUIRED", "ALLOWED", "FORBIDDEN"],
help="Whether to include a DOCTYPE declaration in the generated XML (default REQUIRED)",
)
args = parser.parse_args()
create_grammar(**vars(args))
if __name__ == "__main__":
_handle_cli()
| 10,508 | Python | .py | 301 | 27.584718 | 97 | 0.563379 | IohannesArnold/limuloid | 8 | 0 | 0 | AGPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,250 | main.py | SMmest3r_duplicatedTuningIdFinder/main.py | import os
import re
import tkinter
from tkinter import filedialog
import platform
import json
def select_directory():
if platform.system() == "Windows":
root = tkinter.Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
else:
folder_selected = input("Folder: ")
return folder_selected
def find_meta_files(folder_selected):
meta_files = {
"carcols": [],
"vehicles": {},
"handling": []
}
for root, dirs, files in os.walk(folder_selected):
for file in files:
if file.endswith("carcols.meta"):
meta_files["carcols"].append(os.path.join(root, file))
elif file.endswith("vehicles.meta"):
meta_files["vehicles"][os.path.join(root, file)] = None
elif file.endswith("handling.meta"):
meta_files["handling"].append(os.path.join(root, file))
return meta_files
def get_model_name(vehicles_meta_file):
with open(vehicles_meta_file, "r", encoding="utf-8") as file:
content = file.read()
model_names = re.findall(r'<modelName>(.*?)</modelName>', content)
return model_names[0] if model_names else "Unknown"
def rebuild_handling_ids(handling_files, start_id=2000):
handling_id_map = {}
new_id = start_id
for file_path in handling_files:
with open(file_path, "r+", encoding="utf-8") as file:
content = file.read()
handling_names = re.findall(r'<handlingName>(.*?)</handlingName>', content)
for name in handling_names:
if name not in handling_id_map:
handling_id_map[name] = f"handling_{new_id}"
new_id += 1
content = content.replace(f'<handlingName>{name}</handlingName>', f'<handlingName>{handling_id_map[name]}</handlingName>')
file.seek(0)
file.write(content)
file.truncate()
return new_id # Returning the next starting ID for car mod kits
def rebuild_car_mod_kit_ids(meta_files, start_id=2000):
new_id = rebuild_handling_ids(meta_files["handling"], start_id) # Start car mod kit IDs after handling IDs
summary = {"count": 0, "cars": {}, "handlingDuplicates": {}}
for file_path in meta_files["carcols"]:
directory = os.path.dirname(file_path)
vehicle_meta_file_path = next((f for f in meta_files["vehicles"] if f.startswith(directory)), None)
model_name = get_model_name(vehicle_meta_file_path) if vehicle_meta_file_path else "Unknown"
with open(file_path, "r+", encoding="utf-8") as file:
content = file.read()
ids_found = set(re.findall(r'<id value="(\d+)"', content))
kit_names_found = set(re.findall(r'<kitName>(\d+)(_[\w]+)</kitName>', content))
for id_val in ids_found.union(kit_names_found):
original_id = id_val[0] if isinstance(id_val, tuple) else id_val
suffix = id_val[1] if isinstance(id_val, tuple) else "_default_modkit"
new_kit_name = f"{new_id}{suffix}"
content = content.replace(f'<id value="{original_id}"', f'<id value="{new_id}"')
content = content.replace(f'<kitName>{original_id}{suffix}</kitName>', f'<kitName>{new_kit_name}</kitName>')
summary["cars"][new_id] = {"file_path": file_path, "model_name": model_name, "original_id": original_id, "new_id": new_id, "kitName": new_kit_name}
new_id += 1
file.seek(0)
file.write(content)
file.truncate()
summary["count"] = len(summary["cars"])
with open('car_mods_summary.json', 'w', encoding='utf-8') as json_file:
json.dump(summary, json_file, indent=4, ensure_ascii=False)
def main():
folder_selected = select_directory()
if not folder_selected:
print("No folder selected! Exiting...")
return
meta_files = find_meta_files(folder_selected)
rebuild_car_mod_kit_ids(meta_files)
print("Processing complete. Summary saved to 'car_mods_summary.json'.")
if __name__ == "__main__":
main()
| 4,233 | Python | .py | 85 | 39.588235 | 164 | 0.598783 | SMmest3r/duplicatedTuningIdFinder | 8 | 1 | 0 | GPL-3.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,251 | settings.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/settings.py | from django.conf import settings as django_settings
"""
Clean the HTML output of the EditorJS field using bleach.
This will remove any tags or attributes not allowed by the EditorJS features.
If you want to disable this, set it to False.
Optionally; cleaning can be FORCED by passing `clean=True` to the `render_editorjs_html` function.
"""
CLEAN_HTML = getattr(django_settings, 'EDITORJS_CLEAN_HTML', True)
"""
Add a block ID to each editorJS block when rendering.
This is useful for targeting the block with JavaScript,
or possibly creating some link from frontend to admin area.
"""
ADD_BLOCK_ID = getattr(django_settings, 'EDITORJS_ADD_BLOCK_ID', True)
"""
The attribute name to use for the block ID.
This is only used if `ADD_BLOCK_ID` is True.
"""
BLOCK_ID_ATTR = getattr(django_settings, 'EDITORJS_BLOCK_ID_ATTR', 'data-editorjs-block-id')
"""
Use full urls if the request
is available in the EditorJS rendering context.
"""
USE_FULL_URLS = getattr(django_settings, 'EDITORJS_USE_FULL_URLS', False)
| 1,012 | Python | .py | 24 | 40.916667 | 98 | 0.778004 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,252 | apps.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/apps.py | from django.apps import AppConfig
class WagtailEditorjsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wagtail_editorjs'
| 163 | Python | .py | 4 | 37.25 | 56 | 0.796178 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,253 | django_editor.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/django_editor.py | from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from .forms import EditorJSFormField, EditorJSWidget
class DjangoEditorJSFormField(EditorJSFormField):
@cached_property
def widget(self):
return EditorJSDjangoWidget(
features=self.features,
tools_config=self.tools_config,
)
class EditorJSDjangoWidget(EditorJSWidget):
"""
Taken from wagtail.
This class is deprecated in wagtail 7.0
This might still be useful if we have wagtail installed
but would like to use the editorjs widget in a non-wagtailadmin form.
"""
def render_html(self, name, value, attrs):
"""Render the HTML (non-JS) portion of the field markup"""
return super().render(name, value, attrs)
def render(self, name, value, attrs=None, renderer=None):
# no point trying to come up with sensible semantics for when 'id' is missing from attrs,
# so let's make sure it fails early in the process
try:
id_ = attrs["id"]
except (KeyError, TypeError):
raise TypeError(
"WidgetWithScript cannot be rendered without an 'id' attribute"
)
value_data = self.get_value_data(value)
widget_html = self.render_html(name, value_data, attrs)
js = self.render_js_init(id_, name, value_data)
out = f"{widget_html}<script type=\"text/javascript\">{js}</script>"
return mark_safe(out)
def render_js_init(self, id_, name, value):
# Adapted from editorjs-widget-controller.js
return """
let editorJSWidget__wrapper = document.querySelector(`#${id}-wagtail-editorjs-widget-wrapper`);
let editorJSWidget__configElem = editorJSWidget__wrapper.querySelector(`#wagtail-editorjs-config`);
let editorJSWidget__config = JSON.parse(editorJSWidget__configElem.textContent);
let editorJSWidget__keys = Object.keys(editorJSWidget__config.tools);
for (let i = 0; i < editorJSWidget__keys.length; i++) {
const key = editorJSWidget__keys[i];
const toolConfig = editorJSWidget__config.tools[key];
const toolClass = window[toolConfig.class];
toolConfig.class = toolClass;
editorJSWidget__config.tools[key] = toolConfig;
}
let editorJSWidget__element = document.querySelector(`#${id}`);
new window.EditorJSWidget(
editorJSWidget__wrapper,
editorJSWidget__element,
editorJSWidget__config,
);
""" % {
"id": id_,
}
| 2,501 | Python | .py | 57 | 37.280702 | 99 | 0.68845 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,254 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/__init__.py | """
wagtail_editorjs
© 2024 Nigel van Keulen, goodadvice.it
A Wagtail integration for the Editor.js block editor.
Includes support for custom blocks, inline tools, and more.
Everything is dynamic and customizable.
"""
import distutils.version as pv
__version__ = '1.6.5'
VERSION = pv.LooseVersion(__version__)
| 316 | Python | .py | 10 | 30.1 | 59 | 0.784053 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,255 | hooks.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/hooks.py |
"""
Hook used to register features with the editorjs widget.
"""
REGISTER_HOOK_NAME = "register_wagtail_editorjs_features"
"""
Hook used to build the configuration for the editorjs widget.
Any additional configuration or overrides can be done here.
"""
BUILD_CONFIG_HOOK = "editorjs_widget_build_config"
| 307 | Python | .py | 9 | 32.777778 | 61 | 0.79661 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,256 | blocks.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/blocks.py | from django.utils.functional import cached_property
from django.utils.translation import gettext_lazy as _
from wagtail.telepath import register
from wagtail.blocks.field_block import (
FieldBlock,
FieldBlockAdapter,
)
from .render import render_editorjs_html
from .forms import (
EditorJSFormField,
get_features,
)
class EditorJSBlock(FieldBlock):
"""
A Wagtail block which can be used to add the EditorJS
widget into any streamfield or structblock.
"""
class Meta:
icon = 'draft'
label_format = _('EditorJS Block')
def __init__(self, features: list[str] = None, tools_config: dict = None, **kwargs):
self._features = features
self.tools_config = tools_config or {}
super().__init__(**kwargs)
@cached_property
def field(self):
return EditorJSFormField(
features=self.features,
tools_config=self.tools_config,
label=getattr(self.meta, 'label', None),
required=getattr(self.meta, 'required', True),
help_text=getattr(self.meta, 'help_text', ''),
)
@property
def features(self):
return get_features(self._features)
def render(self, value, context=None):
"""
Render the block value into HTML.
This is so the block can be automatically included with `{% include_block my_editor_js_block %}`.
"""
return render_editorjs_html(self.features, value, context)
from django.forms import Media
class EditorJSBlockAdapter(FieldBlockAdapter):
js_constructor = "wagtail_editorjs.blocks.EditorJSBlock"
@cached_property
def media(self):
m = super().media
return Media(
js= m._js + [
"wagtail_editorjs/js/editorjs-block.js",
],
css=m._css,
)
register(EditorJSBlockAdapter(), EditorJSBlock)
| 1,917 | Python | .py | 55 | 27.581818 | 109 | 0.647696 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,257 | render.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/render.py | from typing import Any, Union
from collections import defaultdict
from django.template.loader import render_to_string
from django.template.context import Context
from django.utils.safestring import mark_safe
from . import settings
from .registry import (
EditorJSElement,
InlineEditorJSFeature,
EDITOR_JS_FEATURES,
)
import bleach, bs4
class NullSanitizer:
@staticmethod
def sanitize_css(val):
return val
def render_editorjs_html(
features: list[str],
data: dict,
context=None,
clean: bool = None,
whitelist_tags: list[str] = None,
whitelist_attrs: Union[dict, list] = None
) -> str:
"""
Renders the editorjs widget based on the features provided.
"""
if "blocks" not in data:
data["blocks"] = []
feature_mappings = {
feature: EDITOR_JS_FEATURES[feature]
for feature in features
}
inlines = [
feature
for feature in feature_mappings.values()
if isinstance(feature, InlineEditorJSFeature)
]
html = []
for block in data["blocks"]:
feature: str = block["type"]
tunes: dict[str, Any] = block.get("tunes", {})
feature_mapping = feature_mappings.get(feature, None)
if not feature_mapping:
continue
# Build the actual block.
element: EditorJSElement = feature_mapping.render_block_data(block, context)
# Optionally tools can decide to not render the block.
if element is None:
continue
# Tune the element.
for tune_name, tune_value in tunes.items():
if tune_name not in feature_mappings:
continue
element = feature_mappings[tune_name].tune_element(element, tune_value, context)
# Add the block ID to each individual block.
if settings.ADD_BLOCK_ID:
# This can be used to link frontend to the admin area.
element.attrs[settings.BLOCK_ID_ATTR] = block.get("id", "")
html.append(element)
html = "\n".join([str(h) for h in html])
soup = bs4.BeautifulSoup(html, "html.parser")
if inlines:
for inline in inlines:
# Give inlines access to whole soup.
# This allows for proper parsing of say; page or document links.
inline: InlineEditorJSFeature
inline.parse_inline_data(soup, context)
# Re-render the soup.
html = soup.decode(False)
if clean or (clean is None and settings.CLEAN_HTML):
allowed_tags = set({
# Default inline tags.
"i", "b", "strong", "em", "u", "s", "strike"
})
allowed_attributes = defaultdict(set)
# cleaner_funcs = defaultdict(lambda: defaultdict(list))
for feature in feature_mappings.values():
allowed_tags.update(feature.allowed_tags)
# for key, value in feature.cleaner_funcs.items():
# for name, func in value.items():
# cleaner_funcs[key][name].append(func)
for key, value in feature.allowed_attributes.items():
allowed_attributes[key].update(value)
if whitelist_tags:
allowed_tags.update(whitelist_tags)
if "*" in allowed_attributes:
allowed_attributes["*"].add(settings.BLOCK_ID_ATTR)
else:
allowed_attributes["*"] = {settings.BLOCK_ID_ATTR}
if whitelist_attrs:
if isinstance(whitelist_attrs, dict):
for key, value in whitelist_attrs.items():
allowed_attributes[key].update(value)
else:
for key in allowed_attributes:
allowed_attributes[key].update(whitelist_attrs)
html = bleach.clean(
html,
tags=allowed_tags,
attributes=allowed_attributes,
css_sanitizer=NullSanitizer,
)
ctx = context or {}
ctx["html"] = html
if isinstance(context, Context):
ctx = context.flatten()
return render_to_string(
"wagtail_editorjs/rich_text.html",
context=ctx,
request=ctx.get("request", None)
)
# def parse_allowed_attributes(tag, name, value):
# if (
# tag not in allowed_attributes\
# and tag not in cleaner_funcs\
# and "*" not in cleaner_funcs\
# and "*" not in allowed_attributes
# ):
# return False
#
# if "*" in cleaner_funcs and name in cleaner_funcs["*"] and any(
# func(value) for func in cleaner_funcs["*"][name]
# ):
# return True
#
# if tag in cleaner_funcs\
# and name in cleaner_funcs[tag]\
# and any(
# func(value) for func in cleaner_funcs[tag][name]
# ):
# return True
#
# if name in allowed_attributes[tag] or name in allowed_attributes["*"]:
# return True
#
# return False
| 5,185 | Python | .py | 137 | 29.817518 | 92 | 0.576163 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,258 | fields.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/fields.py | from typing import Any
from django.db import models
from django.utils.functional import cached_property
from django.core.exceptions import ValidationError
from .forms import EditorJSFormField
from .registry import EDITOR_JS_FEATURES, get_features
class EditorJSField(models.JSONField):
def __init__(self,
features: list[str] = None,
tools_config: dict = None,
*args, **kwargs
):
self._features = features
self.tools_config = tools_config or {}
super().__init__(*args, **kwargs)
@cached_property
def features(self):
return get_features(self._features)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
kwargs['features'] = self.features
kwargs['tools_config'] = self.tools_config
return name, path, args, kwargs
def from_db_value(self, value: Any, expression, connection) -> Any:
value = super().from_db_value(
value, expression, connection
)
return EDITOR_JS_FEATURES.to_python(
self.features, value
)
def get_prep_value(self, value: Any) -> Any:
value = EDITOR_JS_FEATURES.prepare_value(
self.features, value
)
return super().get_prep_value(value)
def to_python(self, value: Any) -> Any:
value = super().to_python(value)
return EDITOR_JS_FEATURES.to_python(
self.features, value
)
def formfield(self, **kwargs):
return super().formfield(**{
'form_class': EditorJSFormField,
'features': self.features,
'tools_config': self.tools_config,
**kwargs
})
| 1,729 | Python | .py | 47 | 28.191489 | 71 | 0.619795 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,259 | forms.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/forms.py | from django.utils.functional import cached_property
from django import forms
from django.forms import (
fields as formfields,
widgets
)
from wagtail import hooks
from datetime import datetime
from .hooks import (
BUILD_CONFIG_HOOK,
)
from .registry import (
EDITOR_JS_FEATURES,
get_features,
TemplateNotSpecifiedError,
)
def _get_feature_scripts(feature, method, *args, list_obj = None, **kwargs):
get_scripts = getattr(feature, method, None)
if get_scripts is None:
raise AttributeError(f"Feature {feature} does not have a {method} method")
scripts = get_scripts(*args, **kwargs)
if list_obj is None:
list_obj = []
for file in get_scripts():
if file not in list_obj:
if isinstance(file, (list, tuple)):
list_obj.extend(file)
else:
list_obj.append(file)
return scripts
class EditorJSWidget(widgets.Input):
"""
A widget which renders the EditorJS editor.
All features are allowed to register CSS and JS files.
They can also optionally include sub-templates
inside of the widget container.
"""
template_name = 'wagtail_editorjs/widgets/editorjs.html'
accepts_features = True
input_type = 'hidden'
def __init__(self, features: list[str] = None, tools_config: dict = None, attrs: dict = None):
super().__init__(attrs)
self.features = get_features(features)
self.tools_config = tools_config or {}
self.autofocus = self.attrs.get('autofocus', False)
self.placeholder = self.attrs.get('placeholder', "")
def build_attrs(self, base_attrs, extra_attrs):
attrs = super().build_attrs(base_attrs, extra_attrs)
attrs['data-controller'] = 'editorjs-widget'
return attrs
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
config = EDITOR_JS_FEATURES.build_config(self.features, context)
config["holder"] = f"{context['widget']['attrs']['id']}-wagtail-editorjs-widget"
tools = config.get('tools', {})
for tool_name, tool_config in self.tools_config.items():
if tool_name in tools:
cfg = tools[tool_name]
cpy = tool_config.copy()
cpy.update(cfg)
tools[tool_name] = cpy
else:
raise ValueError(f"Tool {tool_name} not found in tools; did you include the feature?")
for hook in hooks.get_hooks(BUILD_CONFIG_HOOK):
hook(self, context, config)
context['widget']['features'] = self.features
inclusion_templates = []
for feature in self.features:
try:
inclusion_templates.append(
EDITOR_JS_FEATURES[feature].render_template(context)
)
except TemplateNotSpecifiedError:
pass
context['widget']['inclusion_templates'] = inclusion_templates
context['widget']['config'] = config
return context
@cached_property
def media(self):
js = [
"wagtail_editorjs/vendor/editorjs/editorjs.umd.js",
"wagtail_editorjs/js/editorjs-widget.js",
"wagtail_editorjs/js/tools/wagtail-block-tool.js",
"wagtail_editorjs/js/tools/wagtail-inline-tool.js",
]
css = [
"wagtail_editorjs/css/editorjs-widget.css",
# "wagtail_editorjs/css/frontend.css",
]
feature_mapping = EDITOR_JS_FEATURES.get_by_weight(
self.features,
)
for feature in feature_mapping.values():
_get_feature_scripts(feature, "get_js", list_obj=js)
_get_feature_scripts(feature, "get_css", list_obj=css)
js.extend([
"wagtail_editorjs/js/editorjs-widget-controller.js",
])
return widgets.Media(
js=js,
css={'all': css}
)
class EditorJSFormField(formfields.JSONField):
def __init__(self, features: list[str] = None, tools_config: dict = None, *args, **kwargs):
self.features = get_features(features)
self.tools_config = tools_config or {}
super().__init__(*args, **kwargs)
@cached_property
def widget(self):
return EditorJSWidget(
features=self.features,
tools_config=self.tools_config,
)
def to_python(self, value):
value = super().to_python(value)
if value is None:
return value
value = EDITOR_JS_FEATURES.to_python(
self.features, value
)
return value
def prepare_value(self, value):
if value is None:
return super().prepare_value(value)
if isinstance(value, formfields.InvalidJSONInput):
return value
if not isinstance(value, dict):
return value
value = EDITOR_JS_FEATURES.value_for_form(
self.features, value
)
return super().prepare_value(value)
def validate(self, value) -> None:
super().validate(value)
if value is None and self.required:
raise forms.ValidationError("This field is required")
if value:
if not isinstance(value, dict):
raise forms.ValidationError("Invalid EditorJS JSON object, expected a dictionary")
if "time" not in value:
raise forms.ValidationError("Invalid EditorJS JSON object, missing time")
if "version" not in value:
raise forms.ValidationError("Invalid EditorJS JSON object, missing version")
time = value["time"] # 1713272305659
if not isinstance(time, (int, float)):
raise forms.ValidationError("Invalid EditorJS JSON object, time is not an integer")
time_invalid = "Invalid EditorJS JSON object, time is invalid"
try:
time = datetime.fromtimestamp(time / 1000)
except:
raise forms.ValidationError(time_invalid)
if time is None:
raise forms.ValidationError(time_invalid)
if value and self.required:
if "blocks" not in value:
raise forms.ValidationError("Invalid JSON object")
if not value["blocks"]:
raise forms.ValidationError("This field is required")
EDITOR_JS_FEATURES.validate_for_tools(
self.features, value
)
| 6,666 | Python | .py | 161 | 30.701863 | 102 | 0.610033 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,260 | manage.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wagtail_editorjs.test.testapp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| 685 | Python | .py | 18 | 32.166667 | 93 | 0.683258 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,261 | settings.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/testapp/settings.py | """
Django settings for testapp project.
Generated by 'django-admin startproject' using Django 5.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'test_key_wagtail_editorjs'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Tests will not pass if true.
# We do not account for it in test files.
# We have tests for attributes already.
EDITORJS_ADD_BLOCK_ID = False
# Application definition
INSTALLED_APPS = [
'wagtail_editorjs',
'wagtail_editorjs.test.core',
'wagtail',
'wagtail.sites',
'wagtail.users',
'wagtail.admin',
'wagtail.documents',
'wagtail.images',
'modelcluster',
'taggit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'testapp.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'testapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'test' / 'db.sqlite3',
}
}
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'assets/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'assets/media'
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| 3,682 | Python | .py | 107 | 30.11215 | 91 | 0.713397 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,262 | asgi.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/testapp/asgi.py | """
ASGI config for testapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testapp.settings')
application = get_asgi_application()
| 391 | Python | .py | 10 | 37.5 | 78 | 0.802667 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,263 | urls.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/testapp/urls.py | from django.conf import settings
from django.urls import include, path
from django.contrib import admin
from wagtail.admin import urls as wagtailadmin_urls
from wagtail import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
path("django-admin/", admin.site.urls),
path("admin/", include(wagtailadmin_urls)),
path("documents/", include(wagtaildocs_urls)),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns = urlpatterns + [
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
path("", include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# path("pages/", include(wagtail_urls)),
] | 1,145 | Python | .py | 26 | 40.538462 | 80 | 0.75763 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,264 | wsgi.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/testapp/wsgi.py | """
WSGI config for testapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wagtail_editorjs.test.testapp.settings')
application = get_wsgi_application()
| 413 | Python | .py | 10 | 39.7 | 89 | 0.806045 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,265 | apps.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/apps.py | from django.apps import AppConfig
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wagtail_editorjs.test.core'
| 162 | Python | .py | 4 | 37 | 56 | 0.782051 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,266 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/__init__.py | from django.test import TestCase
from django.conf import settings
from os import path
FIXTURES = path.join(settings.BASE_DIR, "core/fixtures")
| 145 | Python | .py | 4 | 34.75 | 56 | 0.827338 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,267 | test_inlines.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/tests/test_inlines.py | from django.test import TestCase
from .base import BaseEditorJSTest
from wagtail_editorjs.registry import (
InlineEditorJSFeature,
EDITOR_JS_FEATURES,
)
import bs4
TESTING_HTML = """
<div class="editorjs">
<div class="editorjs-block" data-type="paragraph">
<p>Hello, World!</p>
</div>
<div class="editorjs-block" data-type="header">
<h1>Header</h1>
</div>
<div class="editorjs-block" data-type="list" data-testing-id="TARGET">
</div>
<div class="editorjs-block" data-type="table">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
</div>
</div>
"""
class TestEditorJSInline(BaseEditorJSTest):
def setUp(self):
super().setUp()
self.inlines = [
feature
for feature in EDITOR_JS_FEATURES.features.values()
if isinstance(feature, InlineEditorJSFeature)
]
def test_inlines(self):
for feature in self.inlines:
feature: InlineEditorJSFeature
test_data = feature.get_test_data()
if not test_data:
continue
soup = bs4.BeautifulSoup(TESTING_HTML, "html.parser")
testing_block = soup.find("div", {"data-testing-id": "TARGET"})
testing_block.clear()
for i, (initial, _) in enumerate(test_data):
initial_soup = bs4.BeautifulSoup(initial, "html.parser")
initial_soup.attrs["data-testing-id"] = f"test_{i}"
testing_block.append(initial_soup)
feature.parse_inline_data(soup)
html = str(soup)
outputs = [i[1] for i in test_data]
for i, output in enumerate(outputs):
self.assertInHTML(
output,
html,
)
| 1,963 | Python | .py | 60 | 22.616667 | 75 | 0.544828 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,268 | test_render.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/tests/test_render.py | from typing import Any
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from bs4 import BeautifulSoup
from .base import BaseEditorJSTest
from wagtail_editorjs.render import render_editorjs_html
from wagtail_editorjs.registry import (
EditorJSTune,
EditorJSFeature,
EditorJSElement,
EDITOR_JS_FEATURES,
)
class TestEditorJSTune(EditorJSTune):
allowed_attributes = {
"*": ["data-testing-id"],
}
klass = 1
def tune_element(self, element: EditorJSElement, tune_value: Any, context=None) -> EditorJSElement:
element.attrs["data-testing-id"] = tune_value
return element
# Create your tests here.
class TestEditorJSFeatures(BaseEditorJSTest):
def setUp(self) -> None:
super().setUp()
self.tune = TestEditorJSTune(
"test_tune_feature",
None
)
EDITOR_JS_FEATURES.register(
"test_tune_feature",
self.tune,
)
def test_editorjs_features(self):
html = []
test_data = []
for i, feature in enumerate(EDITOR_JS_FEATURES.features.values()):
test_data_list = feature.get_test_data()
if not isinstance(feature, (EditorJSFeature))\
or not test_data_list:
continue
for j, data in enumerate(test_data_list):
test_data_list[j] = {
"id": "test_id_{}_{}".format(i, j),
"type": feature.tool_name,
"data": data,
"tunes": {
"test_tune_feature": "test_id_{}_{}_tune".format(i, j)
}
}
test_data.extend(test_data_list)
for data in test_data_list:
if hasattr(feature, "render_block_data"):
tpl = feature.render_block_data(data)
tpl = self.tune.tune_element(tpl, data["tunes"]["test_tune_feature"])
html.append(tpl)
rendered_1 = render_editorjs_html(
EDITOR_JS_FEATURES.keys(),
{"blocks": test_data},
clean=False,
)
rendered_2 = render_to_string(
"wagtail_editorjs/rich_text.html",
{"html": mark_safe("\n".join([str(h) for h in html]))}
)
soup1 = BeautifulSoup(rendered_1, "html.parser")
soup2 = BeautifulSoup(rendered_2, "html.parser")
d1 = soup1.decode(False)
d2 = soup2.decode(False)
self.assertHTMLEqual(
d1, d2,
msg=(
f"The rendered HTML for feature {feature} does not match the expected output.\n"
"This might be due to a change in the rendering process.\n\n"
"Expected: {expected}\n\n"
"Got: {got}" % {
"expected": d1,
"got": d2,
}
)
)
def test_cleaned_editorjs_features(self):
html = []
test_data = []
for i, feature in enumerate(EDITOR_JS_FEATURES.features.values()):
test_data_list = feature.get_test_data()
if not isinstance(feature, (EditorJSFeature))\
or not test_data_list:
continue
for j, data in enumerate(test_data_list):
test_data_list[j] = {
"id": "test_id_{}_{}".format(i, j),
"type": feature.tool_name,
"data": data,
"tunes": {
"test_tune_feature": "test_id_{}_{}_tune".format(i, j)
}
}
for data in test_data_list:
if hasattr(feature, "render_block_data"):
tpl = feature.render_block_data(data)
tpl = self.tune.tune_element(tpl, data["tunes"]["test_tune_feature"])
html.append(tpl)
test_data.extend(test_data_list)
rendered = render_editorjs_html(
EDITOR_JS_FEATURES.keys(),
{"blocks": test_data},
clean=True,
)
soup = BeautifulSoup(rendered, "html.parser")
for i, data in enumerate(test_data):
block = soup.find(attrs={"data-testing-id": data["tunes"]["test_tune_feature"]})
if not block:
self.fail(
f"Block with id {data['tunes']['test_tune_feature']} not found.\n"
"The tune might not have been properly applied. Check the test data.\n\n"
f"Test data: {data}\n\n"
f"Soup: {soup}"
)
feature = EDITOR_JS_FEATURES[data["type"]]
element = feature.render_block_data(data)
element = self.tune.tune_element(element, data["tunes"]["test_tune_feature"])
soup_element = BeautifulSoup(str(element), "html.parser")
self.assertHTMLEqual(
str(block).replace("\n", "").strip(), str(soup_element).replace("\n", "").strip(),
msg=(
f"Block with feature {feature} ({i}) does not match the expected output.\n"
"Something has gone wrong with the cleaning process.\n\n"
"Expected: {expected}\n\n"
"Got: {got}" % {
"feature": data['tunes']['test_tune_feature'],
"expected": str(soup_element).replace('\n', '').strip(),
"got": str(block).replace('\n', '').strip(),
}
)
)
| 5,697 | Python | .py | 135 | 28.533333 | 109 | 0.51541 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,269 | test_blocks.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/tests/test_blocks.py | from wagtail import blocks
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
import time
from wagtail_editorjs.features import (
WagtailBlockFeature,
)
from wagtail_editorjs.render import render_editorjs_html
from wagtail_editorjs.registry import (
EDITOR_JS_FEATURES,
)
from .base import BaseEditorJSTest
class SubBlock(blocks.StructBlock):
sub_title = blocks.CharBlock()
sub_text = blocks.CharBlock()
class Meta:
allowed_tags = ["h3", "p"]
allowed_attributes = {
"h3": ["class"],
"p": ["class"],
}
class TestWagtailBlockFeatureBlock(blocks.StructBlock):
title = blocks.CharBlock()
subtitle = blocks.CharBlock()
sub_block = SubBlock()
class Meta:
allowed_tags = ["h1", "h2"]
allowed_attributes = {
"h1": ["class"],
"h2": ["class"],
}
def render(self, value, context=None):
return f"<h1 class='test1'>{value['title']}</h1><h2 class='test2'>{value['subtitle']}</h2><h3 class='test3'>{value['sub_block']['sub_title']}</h3><p class='test4'>{value['sub_block']['sub_text']}</p>"
class TestWagtailBlockFeature(BaseEditorJSTest):
def setUp(self) -> None:
super().setUp()
self.block = TestWagtailBlockFeatureBlock()
self.feature = WagtailBlockFeature(
"test_feature",
block=self.block,
)
EDITOR_JS_FEATURES.register(
"test_feature",
self.feature,
)
def test_value_for_form(self):
test_data = {
"title": "Test Title",
"subtitle": "Test Text",
"sub_block": {
"sub_title": "Sub Title",
"sub_text": "Sub Text",
},
}
feature_value = {
"type": "test_feature",
"data": {
"block": test_data,
}
}
editorjs_value = {
"time": int(time.time()),
"blocks": [feature_value],
"version": "0.0.0",
}
tdata_copy = test_data.copy()
copied = editorjs_value.copy()
data = EDITOR_JS_FEATURES.value_for_form(
["test_feature"],
editorjs_value
)
self.assertTrue(isinstance(data, dict))
self.assertIn("blocks", data)
self.assertTrue(isinstance(data["blocks"], list))
self.assertTrue(len(data["blocks"]) == 1, msg=f"Expected 1 block, got {len(data['blocks'])}")
self.assertDictEqual(
data,
copied | {
"blocks": [
{
"type": "test_feature",
"data": {
"block": tdata_copy,
}
}
]
}
)
def test_wagtail_block_feature(self):
test_data = {
"title": "Test Title",
"subtitle": "Test Text",
"sub_block": {
"sub_title": "Sub Title",
"sub_text": "Sub Text",
},
}
feature_value = {
"type": "test_feature",
"data": {
"block": test_data,
}
}
editorjs_value = {
"time": int(time.time()),
"blocks": [feature_value],
"version": "0.0.0",
}
html = render_editorjs_html(features=["test_feature"], data=editorjs_value)
feature_html = str(self.feature.render_block_data(feature_value))
self.assertHTMLEqual(
html,
render_to_string(
"wagtail_editorjs/rich_text.html",
{"html": mark_safe(feature_html)}
),
)
self.assertInHTML(
"<h1 class='test1'>Test Title</h1>",
feature_html,
)
self.assertInHTML(
"<h2 class='test2'>Test Text</h2>",
feature_html,
)
self.assertInHTML(
"<h3 class='test3'>Sub Title</h3>",
feature_html,
)
self.assertInHTML(
"<p class='test4'>Sub Text</p>",
feature_html,
)
| 4,288 | Python | .py | 133 | 21.383459 | 208 | 0.50439 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,270 | test_attrs.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/tests/test_attrs.py | from django.test import TestCase
from wagtail_editorjs.registry.element.element import EditorJSElement
from wagtail_editorjs.registry.element.utils import (
wrap_tag,
_make_attr,
add_attributes,
EditorJSElementAttribute,
EditorJSStyleAttribute,
)
class TestEditorJSElement(TestCase):
def test_element(self):
element = EditorJSElement(
"div",
"Hello, World!",
attrs = {
"class": "test-class",
"id": "test-id",
}
)
self.assertHTMLEqual(
str(element),
'<div class="test-class" id="test-id">Hello, World!</div>'
)
def test_element_attrs(self):
element = EditorJSElement(
"div",
"Hello, World!",
)
element = add_attributes(element, **{
"class_": "test-class",
"data-test": "test-data",
})
self.assertHTMLEqual(
str(element),
'<div class="test-class" data-test="test-data">Hello, World!</div>'
)
def test_make_attr(self):
attrs = _make_attr({
"color": "red",
"background-color": "blue",
})
self.assertIsInstance(attrs, EditorJSStyleAttribute)
self.assertEqual(
str(attrs),
'color: red;background-color: blue'
)
attrs = _make_attr("test-class")
self.assertIsInstance(attrs, EditorJSElementAttribute)
self.assertEqual(
str(attrs),
'test-class'
)
def test_wrap_tag(self):
tag = wrap_tag(
"div",
{
"class": "test-class",
"id": "test-id",
},
"Hello, World!"
)
self.assertHTMLEqual(
tag,
'<div class="test-class" id="test-id">Hello, World!</div>'
)
def test_wrap_tag_styles(self):
tag = wrap_tag(
"div",
{
"id": "test-id",
"class": ["test-class", "test-class-2"],
"style": {
"color": "red",
"background-color": "blue",
}
},
"Hello, World!"
)
self.assertHTMLEqual(
tag,
'<div id="test-id" class="test-class test-class-2" style="color: red;background-color: blue">Hello, World!</div>'
)
| 2,486 | Python | .py | 82 | 19.402439 | 125 | 0.493895 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,271 | base.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/test/core/tests/base.py | from django.test import TestCase
from wagtail.models import Collection, Page
from wagtail.images.tests.utils import (
get_test_image_file,
get_test_image_file_jpeg,
get_test_image_file_webp,
get_test_image_file_avif,
)
from wagtail.images import get_image_model
from wagtail.documents import get_document_model
from wagtail_editorjs import settings
Image = get_image_model()
Document = get_document_model()
class BaseEditorJSTest(TestCase):
"""
Setup test data for EditorJS tests
This is so blocks can freely be tested and query the test db
without having to worry about setting up the data.
"""
def setUp(self) -> None:
image_funcs = [
get_test_image_file,
get_test_image_file_jpeg,
get_test_image_file_webp,
get_test_image_file_avif,
]
self.collection = Collection.get_first_root_node()
root_page = Page.objects.filter(depth=2).first()
child_url_paths = []
sibling_url_paths = []
for i in range(100):
child_url_paths.append(f"test-page-{i}")
sibling_url_paths.append(f"test-subchild-page-{i}")
child = root_page.add_child(instance=Page(
title=f"Test Page {i}",
slug=f"test-page-{i}",
path=f"/test-page-{i}/",
url_path=f"/test-page-{i}/",
))
child.set_url_path(root_page)
child.save()
subchild = child.add_child(instance=Page(
title=f"Test Page subchild {i}",
slug=f"test-subchild-page-{i}",
path=f"/test-subchild-page-{i}/",
url_path=f"/test-subchild-page-{i}/",
))
subchild.set_url_path(child)
subchild.save()
Document.objects.create(file=get_test_image_file(), title=f"Test Document {i}", collection=self.collection)
Image.objects.create(
file=image_funcs[i % len(image_funcs)](),
title=f"Test Image {i}",
collection=self.collection
)
# call_command("fixtree")
# call_command("set_url_paths")
| 2,241 | Python | .py | 57 | 28.77193 | 119 | 0.586287 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,272 | editorjs.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/templatetags/editorjs.py | from django import (
template,
forms,
)
from ..render import render_editorjs_html
from ..registry import EDITOR_JS_FEATURES, EditorJSValue
from ..forms import _get_feature_scripts
register = template.Library()
@register.simple_tag(takes_context=True, name="editorjs")
def render_editorjs(context, data: EditorJSValue):
return render_editorjs_html(data.features, data, context=context)
init_scripts = {
"css": [
'wagtail_editorjs/css/frontend.css',
]
}
@register.simple_tag(takes_context=False, name="editorjs_static")
def editorjs_static(type_of_script="css", features: list[str] = None):
if type_of_script not in ["css", "js"]:
raise ValueError("type_of_script must be either 'css' or 'js'")
if features is None:
features = EDITOR_JS_FEATURES.keys()
feature_mapping = EDITOR_JS_FEATURES.get_by_weight(
features
)
frontend_static = init_scripts.get(type_of_script, [])
for feature in feature_mapping.values():
frontend_static.extend(
_get_feature_scripts(
feature,
f"get_frontend_{type_of_script}",
list_obj=frontend_static,
)
)
kwargs = {}
if type_of_script == "css":
kwargs["css"] = {
"all": frontend_static,
}
elif type_of_script == "js":
kwargs["js"] = frontend_static
return forms.Media(**kwargs).render()
| 1,441 | Python | .py | 42 | 27.833333 | 71 | 0.644043 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,273 | inlines.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/inlines.py | from typing import Any
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from wagtail.models import Page
from wagtail.admin.widgets import AdminPageChooser
from wagtail.documents.widgets import AdminDocumentChooser
from wagtail.documents import get_document_model
from wagtail import hooks
from ..registry import (
PageChooserURLsMixin,
InlineEditorJSFeature,
ModelInlineEditorJSFeature,
FeatureViewMixin,
)
from django.http import (
HttpResponse,
JsonResponse,
)
Document = get_document_model()
class TooltipFeature(InlineEditorJSFeature):
allowed_tags = ["span"]
allowed_attributes = [
"class",
"data-tippy-content",
"data-tippy-placement",
"data-tippy-follow-cursor",
]
tag_name = "span"
must_have_attrs = {
"class": "wagtail-tooltip",
"data-w-tooltip-content-value": None,
}
can_have_attrs = {
"data-w-tooltip-placement-value": None,
}
klass = "WagtailTooltip"
js = [
"wagtail_editorjs/js/tools/tooltips/wagtail-tooltips.js",
]
frontend_js = [
"wagtail_editorjs/vendor/tippy/popper.min.js",
"wagtail_editorjs/vendor/tippy/tippy-bundle.min.js",
"wagtail_editorjs/js/tools/tooltips/frontend.js",
]
@classmethod
def get_test_data(cls):
return [
(
f"<span class='wagtail-tooltip' data-w-tooltip-content-value='Tooltip content'></span>",
f"<span class='wagtail-tooltip' data-tippy-content='Tooltip content' data-tippy-placement='bottom' data-tippy-follow-cursor='horizontal'></span>",
),
(
f"<span class='wagtail-tooltip' data-w-tooltip-content-value='Tooltip content' data-w-tooltip-placement-value='top'></span>",
f"<span class='wagtail-tooltip' data-tippy-content='Tooltip content' data-tippy-placement='top' data-tippy-follow-cursor='horizontal'></span>",
),
]
def build_elements(self, inline_data: list, context: dict[str, Any] = None) -> list:
for element, attrs in inline_data:
element.attrs.clear()
element["class"] = "wagtail-tooltip"
element["data-tippy-follow-cursor"] = "horizontal"
# As per wagtail documentation default is bottom.
attrs.setdefault("data-w-tooltip-placement-value", "bottom")
for k, v in attrs.items():
if not k.startswith("data-w-tooltip-") or not k.endswith("-value"):
continue
k = k.replace("data-w-tooltip-", "data-tippy-")
k = k[:-6]
element[k] = v
class BasePageLinkMixin(PageChooserURLsMixin):
allowed_attributes = ["target", "rel"]
can_have_attrs = {
"data-target": None,
"data-rel": None,
}
def build_element(self, item, obj, context: dict[str, Any] = None, data: dict[str, Any] = None):
"""Build the element from the object."""
super().build_element(item, obj, context, data)
if "data-target" in data and data["data-target"]:
item["target"] = data["data-target"]
if "data-rel" in data and data["data-rel"]:
item["rel"] = data["data-rel"]
@classmethod
def get_url(cls, instance):
return instance.get_url()
@classmethod
def get_full_url(cls, instance, request):
return instance.get_full_url(request)
@classmethod
def get_test_queryset(cls):
return super().get_test_queryset().filter(depth__gt=1)
class LinkFeature(BasePageLinkMixin, ModelInlineEditorJSFeature):
allowed_tags = ["a"]
allowed_attributes = BasePageLinkMixin.allowed_attributes + [
"class", "href", "data-id"
]
must_have_attrs = {
"data-parent-id": None,
}
chooser_class = AdminPageChooser
model = Page
klass="WagtailLinkTool"
js = [
"wagtail_editorjs/js/tools/wagtail-chooser-tool.js",
"wagtail_editorjs/js/tools/wagtail-link.js",
]
@classmethod
def get_test_data(cls):
models = cls.get_test_queryset()[0:5]
return [
(
# Override to add data-autocomplete.
f"<a data-id='{model.id}' data-{cls.model._meta.model_name}='True' data-parent-id='this-doesnt-get-used'></a>",
f"<a href='{cls.get_url(model)}' class='{cls.model._meta.model_name}-link'></a>",
)
for model in models
]
SEARCH_QUERY_PARAM = "search"
CONSTRUCT_PAGE_QUERYSET = "construct_page_queryset"
BUILD_PAGE_DATA = "build_page_data"
class LinkAutoCompleteFeature(FeatureViewMixin, BasePageLinkMixin, ModelInlineEditorJSFeature):
allowed_tags = ["a"]
allowed_attributes = BasePageLinkMixin.allowed_attributes + [
"class", "href", "data-id"
]
must_have_attrs = {
"data-autocomplete": "page",
}
chooser_class = AdminPageChooser
model = Page
klass="LinkAutocomplete"
js = [
"wagtail_editorjs/vendor/editorjs/tools/link-autocomplete.js",
]
def get_config(self, context: dict[str, Any]):
config = super(ModelInlineEditorJSFeature, self).get_config(context)
config.setdefault("config", {})
config["config"]["endpoint"] = reverse(f"wagtail_editorjs:{self.tool_name}")
config["config"]["queryParam"] = "search"
return config
@classmethod
def get_test_data(cls):
models = cls.get_test_queryset()[0:5]
return [
(
# Override to add data-autocomplete.
f"<a data-id='{model.id}' data-{cls.model._meta.model_name}='True' data-autocomplete='page'></a>",
f"<a href='{cls.get_url(model)}' class='{cls.model._meta.model_name}-link'></a>",
)
for model in models
]
def handle_get(self, request):
"""
Autocomplete for internal links
"""
search = request.GET.get(SEARCH_QUERY_PARAM)
pages = Page.objects.all()\
.live()\
.specific()
for fn in hooks.get_hooks(CONSTRUCT_PAGE_QUERYSET):
pages = fn(request, pages, search)
if isinstance(pages, HttpResponse):
return pages
if search:
pages = pages.search(search)
page_list = []
page_data_hooks = hooks.get_hooks(BUILD_PAGE_DATA)
for page in pages:
data = {
'id': page.id,
'name': page.title,
'href': page.get_url(request),
'description': page.search_description,
'autocomplete': 'page',
'page': True,
}
for hook in page_data_hooks:
hook(request, page, data)
page_list.append(data)
return JsonResponse({
"success": True,
"items": page_list,
},
status=200,
)
class DocumentFeature(ModelInlineEditorJSFeature):
allowed_tags = ["a"]
allowed_attributes = ["class", "href", "data-id"]
chooser_class = AdminDocumentChooser
model = Document
klass = "WagtailDocumentTool"
js = [
"wagtail_editorjs/js/tools/wagtail-chooser-tool.js",
"wagtail_editorjs/js/tools/wagtail-document.js",
]
@classmethod
def get_url(cls, instance):
return instance.file.url
| 7,479 | Python | .py | 198 | 29.09596 | 162 | 0.607553 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,274 | tunes.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/tunes.py | from typing import Any
from django import forms
from django.utils.translation import gettext_lazy as _
from ..registry import (
EditorJSTune,
EditorJSElement,
wrapper,
)
class AlignmentBlockTune(EditorJSTune):
allowed_attributes = {
"*": ["class"],
}
klass = "AlignmentBlockTune"
js = [
"wagtail_editorjs/vendor/editorjs/tools/text-alignment.js",
]
def validate(self, data: Any):
super().validate(data)
alignment = data.get("alignment")
if alignment not in ["left", "center", "right"]:
raise forms.ValidationError("Invalid alignment value")
def tune_element(self, element: EditorJSElement, tune_value: Any, context = None) -> EditorJSElement:
element = super().tune_element(element, tune_value, context=context)
element.add_attributes(class_=f"align-content-{tune_value['alignment'].strip()}")
return element
class TextVariantTune(EditorJSTune):
allowed_tags = ["div"]
allowed_attributes = ["class"]
klass = "TextVariantTune"
js = [
"wagtail_editorjs/vendor/editorjs/tools/text-variant-tune.js",
]
def validate(self, data: Any):
super().validate(data)
if not data:
return
if data not in [
"call-out",
"citation",
"details",
]:
raise forms.ValidationError("Invalid text variant value")
def tune_element(self, element: EditorJSElement, tune_value: Any, context = None) -> EditorJSElement:
element = super().tune_element(element, tune_value, context=context)
if not tune_value:
return element
if element.is_wrapped:
element["class"] = f"text-variant-{tune_value}"
return EditorJSElement(
"div",
element,
attrs={"class": f"text-variant-{tune_value}"},
)
class ColorTune(EditorJSTune):
allowed_attributes = {
"*": ["class", "style"],
}
js = [
"wagtail_editorjs/js/tools/wagtail-color-tune.js",
]
klass = "WagtailTextColorTune"
def validate(self, data: Any):
super().validate(data)
if not data:
return
if not isinstance(data, dict):
raise forms.ValidationError("Invalid color value")
if "color" not in data:
# Dont do anything
return
if not isinstance(data["color"], str):
raise forms.ValidationError("Invalid color value")
if not data["color"].startswith("#"):
raise forms.ValidationError("Invalid color value")
def tune_element(self, element: EditorJSElement, tune_value: Any, context = None) -> EditorJSElement:
if "color" not in tune_value:
return element
return wrapper(
element,
attrs={
"class": "wagtail-editorjs-color-tuned",
"style": {
"--text-color": tune_value["color"],
},
},
)
class BackgroundColorTune(ColorTune):
klass = "WagtailBackgroundColorTune"
def tune_element(self, element: EditorJSElement, tune_value: Any, context = None) -> EditorJSElement:
if "color" not in tune_value:
return element
classname = [
"wagtail-editorjs-color-tuned",
]
attrs = {
"class": classname,
"style": {
"--background-color": tune_value["color"],
},
}
if tune_value.get("stretched", None):
attrs["class"] = classname + ["bg-stretched"]
return wrapper(
element,
attrs=attrs,
)
| 3,848 | Python | .py | 106 | 26.04717 | 105 | 0.586312 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,275 | images.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/images.py | from typing import Any, TYPE_CHECKING
from django import forms
from django.urls import reverse, path
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext_lazy as _
from django.http import (
HttpRequest,
FileResponse,
HttpResponse,
)
from wagtail.images.widgets import AdminImageChooser
from wagtail.images import get_image_model
from wagtail.images.models import SourceImageIOError
if TYPE_CHECKING:
from wagtail.images.models import Image as AbstractImage
from ..settings import (
USE_FULL_URLS,
)
from ..registry import (
EditorJSFeature,
EditorJSBlock,
EditorJSElement,
FeatureViewMixin,
wrapper,
)
Image = get_image_model()
class BaseImageFeature(FeatureViewMixin, EditorJSFeature):
def get_urlpatterns(self):
return [
path(
f"{self.tool_name}/",
self.handler,
name=f"{self.tool_name}_for_id_fmt",
),
path(
f"{self.tool_name}/<int:image_id>/",
self.handler,
name=self.tool_name,
)
]
def handle_get(self, request: HttpRequest, image_id: int) -> "AbstractImage":
image: "AbstractImage" = get_object_or_404(Image, pk=image_id)
# Get/generate the rendition
try:
rendition = image.get_rendition("original")
except SourceImageIOError:
return HttpResponse(
"Source image file not found", content_type="text/plain", status=410
)
with rendition.get_willow_image() as willow_image:
mime_type = willow_image.mime_type
# Serve the file
f = rendition.file.open("rb")
response = FileResponse(f, filename=image.filename, content_type=mime_type)
response["Content-Length"] = f.size
return response
class ImageFeature(BaseImageFeature):
allowed_tags = ["img", "figure", "figcaption"]
allowed_attributes = {
"img": ["src", "alt", "class", "style"],
"figure": ["class", "style"],
"figcaption": ["class"],
}
klass = "WagtailImageTool"
@property
def js(self):
return [
*(AdminImageChooser().media._js or []),
"wagtail_editorjs/js/tools/wagtail-image.js",
]
@js.setter
def js(self, value): pass
def get_config(self, context: dict[str, Any]):
config = super().get_config() or {}
config.setdefault("config", {})
config["config"]["imageChooserId"] =\
f"editorjs-image-chooser-{context['widget']['attrs']['id']}"
config["config"]["getImageUrl"] = reverse(f"wagtail_editorjs:{self.tool_name}_for_id_fmt")
return config
def validate(self, data: Any):
super().validate(data)
d = data["data"]
if "imageId" not in d:
raise forms.ValidationError("Invalid imageId value")
def render_template(self, context: dict[str, Any] = None):
widget_id = f"editorjs-image-chooser-{context['widget']['attrs']['id']}"
return AdminImageChooser().render_html(
widget_id,
None,
{"id": widget_id}
)
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
image = block["data"].get("imageId")
image = Image.objects.get(id=image)
classlist = []
styles = {}
if block["data"].get("withBorder"):
classlist.append("with-border")
if block["data"].get("stretched"):
classlist.append("stretched")
if block["data"].get("backgroundColor"):
styles["--figure-bg"] = block["data"]["backgroundColor"]
classlist.append("with-background")
attrs = {}
if classlist:
attrs["class"] = classlist
if styles:
attrs["style"] = styles
url = image.file.url
if not any([url.startswith(i) for i in ["http://", "https://", "//"]])\
and context\
and "request" in context\
and USE_FULL_URLS:
request = context.get("request")
if request:
url = request.build_absolute_uri(url)
# Caption last - we are wrapping the image in a figure tag
imgTag = EditorJSElement(
"img",
close_tag=False,
attrs={
"src": url,
"alt": block["data"].get("alt"),
},
)
if block["data"].get("usingCaption"):
caption = block["data"].get("alt")
w = EditorJSElement(
"figure",
close_tag=True,
)
figcaption = EditorJSElement(
"figcaption",
caption,
)
w.append(imgTag)
w.append(figcaption)
else:
w = imgTag
return wrapper(w, attrs=attrs)
@classmethod
def get_test_data(cls):
instance = Image.objects.first()
return [
{
"imageId": instance.pk,
"withBorder": True,
"stretched": False,
"backgroundColor": "#000000",
"usingCaption": False,
"alt": "Image",
"caption": "Image",
},
{
"imageId": instance.pk,
"withBorder": False,
"stretched": True,
"backgroundColor": None,
"usingCaption": True,
"alt": "Image",
"caption": "Image",
}
]
class ImageRowFeature(BaseImageFeature):
allowed_tags = ["div", "img"]
allowed_attributes = ["class", "style"]
klass = "ImageRowTool"
# js = [
# "wagtail_editorjs/js/tools/wagtail-image-row.js",
# ]
@property
def js(self):
return [
*(AdminImageChooser().media._js or []),
"wagtail_editorjs/vendor/sortable/sortable.min.js",
"wagtail_editorjs/js/tools/wagtail-image-row.js",
]
@js.setter
def js(self, value): pass
def get_config(self, context: dict[str, Any]):
config = super().get_config() or {}
config.setdefault("config", {})
config["config"]["imageChooserId"] =\
f"editorjs-images-chooser-{context['widget']['attrs']['id']}"
config["config"]["getImageUrl"] = reverse(f"wagtail_editorjs:{self.tool_name}_for_id_fmt")
return config
def render_template(self, context: dict[str, Any] = None):
widget_id = f"editorjs-images-chooser-{context['widget']['attrs']['id']}"
return AdminImageChooser().render_html(
widget_id,
None,
{"id": widget_id}
)
def validate(self, data: Any):
super().validate(data)
if "images" not in data["data"]:
raise forms.ValidationError("Invalid images value")
if not data["data"]["images"]:
raise forms.ValidationError("Invalid images value")
if "settings" not in data["data"] or data["data"]["settings"] is None:
raise forms.ValidationError("Invalid settings value")
for image in data["data"]["images"]:
if "id" not in image:
raise forms.ValidationError("Invalid id value")
if "title" not in image:
raise forms.ValidationError("Invalid title value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
images = block["data"]["images"]
ids = []
for image in images:
ids.append(image["id"])
images = Image.objects.in_bulk(ids)
s = []
for id in ids:
try:
id = int(id)
except ValueError:
pass
image = images[id]
url = image.file.url
if not any([url.startswith(i) for i in ["http://", "https://", "//"]])\
and context\
and "request" in context\
and USE_FULL_URLS:
request = context.get("request")
if request:
url = request.build_absolute_uri(url)
s.append(EditorJSElement(
"div",
EditorJSElement(
"img",
close_tag=False,
attrs={
"src": url,
"alt": image.title,
}
),
attrs={
"class": "image-wrapper",
}
))
return wrapper(
EditorJSElement("div", s, attrs={
"class": "image-row",
}),
attrs={
"class": "stretched"
} if block["data"]["settings"].get("stretched") else {}
)
@classmethod
def get_test_data(cls):
images = Image.objects.all()[0:3]
return [
{
"images": [
{
"id": image.pk,
"title": image.title,
} for image in images
],
"settings": {
"stretched": True,
},
}
]
| 9,507 | Python | .py | 265 | 24.298113 | 98 | 0.524904 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,276 | documents.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/documents.py | from typing import Any, TYPE_CHECKING
from django import forms
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.utils.safestring import mark_safe
from django.http import (
JsonResponse,
)
from wagtail.models import Collection
from wagtail.documents import (
get_document_model,
)
from wagtail.documents.forms import (
get_document_form,
)
if TYPE_CHECKING:
from wagtail.documents.models import AbstractDocument
from ..settings import (
USE_FULL_URLS,
)
from ..registry import (
EditorJSFeature,
EditorJSBlock,
EditorJSElement,
FeatureViewMixin,
)
BYTE_SIZE_STEPS = [_("Bytes"), _("Kilobytes"), _("Megabytes"), _("Gigabytes"), _("Terabytes")]
def filesize_to_human_readable(size: int) -> str:
for unit in BYTE_SIZE_STEPS:
if size < 1024:
break
size /= 1024
return f"{size:.0f} {unit}"
Document = get_document_model()
DocumentForm = get_document_form(Document)
class AttachesFeature(FeatureViewMixin, EditorJSFeature):
allowed_tags = [
"div", "p", "span", "a",
"svg", "path",
]
allowed_attributes = {
"div": ["class"],
"p": ["class"],
"span": ["class"],
"a": ["class", "href", "title"],
"svg": ["xmlns", "width", "height", "fill", "class", "viewBox"],
"path": ["d"],
}
klass="CSRFAttachesTool"
js=[
"wagtail_editorjs/vendor/editorjs/tools/attaches.js",
"wagtail_editorjs/js/tools/attaches.js",
],
def get_config(self, context: dict[str, Any] = None) -> dict:
config = super().get_config(context)
config.setdefault("config", {})
config["config"]["endpoint"] = reverse(f"wagtail_editorjs:{self.tool_name}")
return config
def validate(self, data: Any):
super().validate(data)
if "file" not in data["data"]:
raise forms.ValidationError("Invalid file value")
if "id" not in data["data"]["file"] and not data["data"]["file"]["id"] and "url" not in data["data"]["file"]:
raise forms.ValidationError("Invalid id/url value")
if "title" not in data["data"]:
raise forms.ValidationError("Invalid title value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
document_id = block["data"]["file"]["id"]
document = Document.objects.get(pk=document_id)
url = document.url
if not any([url.startswith(i) for i in ["http://", "https://", "//"]])\
and context\
and "request" in context\
and USE_FULL_URLS:
request = context.get("request")
if request:
url = request.build_absolute_uri(url)
if block["data"]["title"]:
title = block["data"]["title"]
else:
if document:
title = document.title
else:
title = url
return EditorJSElement(
"div",
[
EditorJSElement(
"p",
EditorJSElement(
"a",
title,
attrs={"href": url},
),
attrs={"class": "attaches-title"},
),
EditorJSElement(
"span",
filesize_to_human_readable(document.file.size),
attrs={"class": "attaches-size"},
),
EditorJSElement(
"a",
mark_safe("""<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-link" viewBox="0 0 16 16">
<path d="M6.354 5.5H4a3 3 0 0 0 0 6h3a3 3 0 0 0 2.83-4H9q-.13 0-.25.031A2 2 0 0 1 7 10.5H4a2 2 0 1 1 0-4h1.535c.218-.376.495-.714.82-1z"/>
<path d="M9 5.5a3 3 0 0 0-2.83 4h1.098A2 2 0 0 1 9 6.5h3a2 2 0 1 1 0 4h-1.535a4 4 0 0 1-.82 1H12a3 3 0 1 0 0-6z"/>
</svg>"""),
attrs={
"title": _("Download"),
"href": url,
"class": "attaches-link",
# "data-id": document_id,
},
)
],
attrs={"class": "attaches"},
)
@classmethod
def get_test_data(cls):
instance = Document.objects.first()
return [
{
"file": {
"id": instance.pk,
},
"title": "Document",
},
]
@csrf_exempt
def handle_post(self, request):
file = request.FILES.get('file')
if not file:
return JsonResponse({
'success': False,
'errors': {
'file': ["This field is required."]
}
}, status=400)
filename = file.name
title = request.POST.get('title', filename)
collection = Collection.get_first_root_node().id
form = DocumentForm({ 'title': title, 'collection': collection }, request.FILES)
if form.is_valid():
document: AbstractDocument = form.save(commit=False)
hash = document.get_file_hash()
existing = Document.objects.filter(file_hash=hash)
if existing.exists():
exists: AbstractDocument = existing.first()
return JsonResponse({
'success': True,
'file': {
'id': exists.pk,
'title': exists.title,
'size': exists.file.size,
'url': exists.url,
'upload_replaced': True,
'reuploaded_by_user': request.user.pk,
}
})
document.uploaded_by_user = request.user
document.save()
return JsonResponse({
'success': True,
'file': {
'id': document.pk,
'title': document.title,
'size': document.file.size,
'url': document.url,
'upload_replaced': False,
'reuploaded_by_user': None,
}
})
else:
return JsonResponse({
'success': False,
'errors': form.errors,
}, status=400)
| 6,611 | Python | .py | 178 | 25.078652 | 155 | 0.507371 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,277 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/__init__.py | from .blocks import (
CodeFeature,
DelimiterFeature,
HeaderFeature,
HTMLFeature,
WarningFeature,
TableFeature,
BlockQuoteFeature,
WagtailBlockFeature,
EditorJSFeatureStructBlock,
ButtonFeature,
)
from .lists import (
NestedListFeature,
CheckListFeature,
)
from .documents import (
AttachesFeature,
)
from .images import (
ImageFeature,
ImageRowFeature,
)
from .inlines import (
TooltipFeature,
LinkFeature,
LinkAutoCompleteFeature,
DocumentFeature,
)
from .tunes import (
AlignmentBlockTune,
TextVariantTune,
ColorTune,
BackgroundColorTune,
) | 634 | Python | .py | 35 | 14.514286 | 31 | 0.748333 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,278 | lists.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/lists.py | from typing import Any
from django import forms
from django.utils.translation import gettext_lazy as _
from ..registry import (
EditorJSFeature,
EditorJSBlock,
EditorJSElement,
wrap_tag,
)
class NestedListElement(EditorJSElement):
def __init__(self, tag: str, items: list[EditorJSElement], close_tag: bool = True, attrs: dict[str, Any] = None):
super().__init__(tag=tag, content=None, close_tag=close_tag, attrs=attrs)
self.items = items
def __str__(self):
return wrap_tag(self.tag, self.attrs, "".join([str(item) for item in self.items]), self.close_tag)
@property
def content(self):
return "".join([str(item) for item in self.items])
@content.setter
def content(self, value):
if isinstance(value, list):
self.items = value
else:
self.items = [value]
def append(self, item: "NestedListElement"):
self.items.append(item)
def parse_list(items: list[dict[str, Any]], element: str, depth = 0) -> NestedListElement:
s = []
for item in items:
content = item.get("content")
items = item.get("items")
s.append(f"<li>{content}")
if items:
s.append(parse_list(items, element, depth + 1))
s.append(f"</li>")
return NestedListElement(element, s, attrs={"class": "nested-list", "style": f"--depth: {depth}"})
class NestedListFeature(EditorJSFeature):
allowed_tags = ["ul", "ol", "li"]
allowed_attributes = ["class", "style"]
klass="NestedList"
js = [
"wagtail_editorjs/vendor/editorjs/tools/nested-list.js",
]
def validate(self, data: Any):
super().validate(data)
items = data["data"].get("items")
if not items:
raise forms.ValidationError("Invalid items value")
if "style" not in data["data"]:
raise forms.ValidationError("Invalid style value")
if data["data"]["style"] not in ["ordered", "unordered"]:
raise forms.ValidationError("Invalid style value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
element = "ol" if block["data"]["style"] == "ordered" else "ul"
return parse_list(block["data"]["items"], element)
@classmethod
def get_test_data(cls):
return [
{
"style": "unordered",
"items": [
{
"content": "Item 1",
"items": [
{
"content": "Item 1.1",
"items": [
{
"content": "Item 1.1.1",
"items": [],
},
{
"content": "Item 1.1.2",
"items": [],
},
],
},
{
"content": "Item 1.2",
"items": [],
},
],
},
{
"content": "Item 2",
"items": [],
},
],
},
]
class CheckListFeature(EditorJSFeature):
allowed_tags = ["ul", "li"]
allowed_attributes = ["class"]
klass="Checklist"
js=[
"wagtail_editorjs/vendor/editorjs/tools/checklist.js",
]
def validate(self, data: Any):
super().validate(data)
items = data["data"].get("items")
if not items:
raise forms.ValidationError("Invalid items value")
for item in items:
if "checked" not in item:
raise forms.ValidationError("Invalid checked value")
if "text" not in item:
raise forms.ValidationError("Invalid text value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
s = []
for item in block["data"]["items"]:
class_ = "checklist-item"
if item["checked"]:
class_ += " checked"
s.append(wrap_tag("li", {"class": class_}, item["text"]))
return EditorJSElement("ul", "".join(s), attrs={"class": "checklist"})
@classmethod
def get_test_data(cls):
return [
{
"items": [
{
"checked": True,
"text": "Item 1",
},
{
"checked": False,
"text": "Item 2",
},
],
}
]
| 5,005 | Python | .py | 131 | 23.862595 | 117 | 0.465914 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,279 | blocks.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/features/blocks.py | from typing import Any
from django import forms
from django.utils.translation import gettext_lazy as _
from django.utils.functional import cached_property
from django.templatetags.static import static
from django.utils.safestring import mark_safe
import bleach
from ..registry import (
PageChooserURLsMixin,
EditorJSFeature,
EditorJSBlock,
EditorJSElement,
EditorJSSoupElement,
wrap_tag,
)
class CodeFeature(EditorJSFeature):
allowed_tags = ["code"]
allowed_attributes = ["class"]
klass="CodeTool"
js=[
"wagtail_editorjs/vendor/editorjs/tools/code.js",
]
def validate(self, data: Any):
super().validate(data)
if 'code' not in data['data']:
raise forms.ValidationError('Invalid code value')
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
return EditorJSElement("code", block["data"]["code"], attrs={"class": "code"})
@classmethod
def get_test_data(cls):
return [
{
"code": "print('Hello, World!')",
}
]
class DelimiterFeature(EditorJSFeature):
allowed_tags = ["hr"]
allowed_attributes = ["class"]
klass="Delimiter"
js = [
"wagtail_editorjs/vendor/editorjs/tools/delimiter.js",
]
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
return EditorJSElement("hr", close_tag=False, attrs={"class": "delimiter"})
@classmethod
def get_test_data(cls):
return [{}, {}, {}]
class HeaderFeature(EditorJSFeature):
allowed_tags = ["h1", "h2", "h3", "h4", "h5", "h6"]
allowed_attributes = ["class"]
klass="Header"
js=[
"wagtail_editorjs/vendor/editorjs/tools/header.js",
]
def validate(self, data: Any):
super().validate(data)
level = data["data"].get("level")
if level > 6 or level < 1:
raise forms.ValidationError("Invalid level value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
return EditorJSElement(
"h" + str(block["data"]["level"]),
block["data"].get("text")
)
@classmethod
def get_test_data(cls):
return [
{
"level": heading,
"text": f"Header {heading}",
} for heading in range(1, 7)
]
class HTMLFeature(EditorJSFeature):
allowed_tags = bleach.ALLOWED_TAGS
allowed_attributes = bleach.ALLOWED_ATTRIBUTES
klass="RawTool"
js = [
"wagtail_editorjs/vendor/editorjs/tools/raw.js",
]
def validate(self, data: Any):
super().validate(data)
if "html" not in data["data"]:
raise forms.ValidationError("Invalid html value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
return EditorJSElement("div", block["data"]["html"], attrs={"class": "html"})
@classmethod
def get_test_data(cls):
return [
{
"html": "<p>This is a HTML block.</p>",
}
]
class WarningFeature(EditorJSFeature):
allowed_tags = ["div", "h2", "p"]
allowed_attributes = ["class"]
klass="Warning"
js = [
"wagtail_editorjs/vendor/editorjs/tools/warning.js",
]
def validate(self, data: Any):
super().validate(data)
if "title" not in data["data"]:
raise forms.ValidationError("Invalid title value")
if "message" not in data["data"]:
raise forms.ValidationError("Invalid message value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
return EditorJSElement(
"div",
attrs={
"class": "warning",
},
content=[
EditorJSElement(
"h2",
block["data"]["title"],
),
EditorJSElement(
"p",
block["data"]["message"],
),
]
)
@classmethod
def get_test_data(cls):
return [
{
"title": "Warning",
"message": "This is a warning message.",
}
]
class TableFeature(EditorJSFeature):
allowed_tags = ["table", "tr", "th", "td", "thead", "tbody", "tfoot"]
allowed_attributes = ["class"]
klass="Table"
js = [
"wagtail_editorjs/vendor/editorjs/tools/table.js",
]
def validate(self, data: Any):
super().validate(data)
if "content" not in data["data"]:
raise forms.ValidationError("Invalid content value")
if "withHeadings" not in data["data"]:
raise forms.ValidationError("Invalid withHeadings value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
table = []
if block["data"]["withHeadings"]:
headings = block["data"]["content"][0]
table.append(EditorJSElement(
"thead",
EditorJSElement(
"tr",
[
EditorJSElement("th", heading)
for heading in headings
]
)
))
content = block["data"]["content"][1:]
else:
content = block["data"]["content"]
tbody = EditorJSElement("tbody")
for row in content:
tbody.append(
EditorJSElement(
"tr",
[
EditorJSElement("td", cell)
for cell in row
]
)
)
table.append(tbody)
return EditorJSElement("table", table)
@classmethod
def get_test_data(cls):
return [
{
"withHeadings": False,
"content": [
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
],
},
{
"withHeadings": True,
"content": [
["Heading 1", "Heading 2", "Heading 3"],
["1", "2", "3"],
["4", "5", "6"],
["7", "8", "9"],
],
}
]
class BlockQuoteFeature(EditorJSFeature):
allowed_tags = ["blockquote", "footer"]
allowed_attributes = ["class"]
klass="Quote"
js = [
"wagtail_editorjs/vendor/editorjs/tools/quote.js",
]
def validate(self, data: Any):
super().validate(data)
if "text" not in data["data"]:
raise forms.ValidationError("Invalid text value")
if "caption" not in data["data"]:
raise forms.ValidationError("Invalid caption value")
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
text = block["data"]["text"]
caption = block["data"]["caption"]
return EditorJSElement(
"blockquote",
[
text,
wrap_tag("footer", {}, caption),
],
{
"class": "blockquote",
}
)
@classmethod
def get_test_data(cls):
return [
{
"text": "This is a quote.",
"caption": "Anonymous",
}
]
from wagtail import blocks
class EditorJSFeatureStructBlock(blocks.StructBlock):
MUTABLE_META_ATTRIBUTES = blocks.StructBlock.MUTABLE_META_ATTRIBUTES + [
"allowed_tags", "allowed_attributes"
]
def __init__(self, *args, allowed_tags: list[str] = None, allowed_attributes: dict[str, list[str]] = None, **kwargs):
super().__init__(*args, **kwargs)
self.set_meta_options({
"allowed_tags": allowed_tags,
"allowed_attributes": allowed_attributes,
})
for _, block in self.child_blocks.items():
if isinstance(block, (blocks.StreamBlock, blocks.ListBlock)):
raise ValueError("StreamBlock and ListBlock are not allowed in StructBlock children for the EditorJSFeatureStructBlock")
def get_allowed_tags(instance: EditorJSFeatureStructBlock, block: blocks.Block, l = None) -> list[str]:
if hasattr(block, "allowed_tags"):
l = block.allowed_tags
elif hasattr(block.meta, "allowed_tags"):
l = block.meta.allowed_tags
l = l or []
if isinstance(block, blocks.StructBlock):
for _, b in block.child_blocks.items():
l += get_allowed_tags(instance, b, l)
return list(set(list(l) + ["div"]))
def get_allowed_attributes(instance: EditorJSFeatureStructBlock, block: blocks.Block, d = None) -> dict[str, list[str]]:
if hasattr(block, "allowed_attributes"):
obj_dict = block.allowed_attributes
elif hasattr(block.meta, "allowed_attributes"):
obj_dict = block.meta.allowed_attributes
else:
obj_dict = {}
if d is None:
d = obj_dict
else:
for key, value in obj_dict.items():
d[key] = set(list(d.get(key, [])) + list(value))
if isinstance(d, list) and "class" not in d:
d.append("class")
elif isinstance(d, dict):
v = d.get("div", [])
if isinstance(v, list) and "class" not in v:
v.append("class")
elif isinstance(v, set) and "class" not in v:
v.add("class")
elif isinstance(v, str):
v = set(v.split(" "))
v.add("class")
d["div"] = v
if isinstance(block, blocks.StructBlock):
for _, b in block.child_blocks.items():
d = get_allowed_attributes(instance, b, d)
return d
class WagtailBlockFeature(EditorJSFeature):
def __init__(self,
tool_name: str,
block: blocks.Block,
klass: str = None,
config: dict = None,
weight: int = 0, # Weight is used to manage which features.js files are loaded first.
allowed_tags: list[str] = None,
allowed_attributes: dict[str, list[str]] = None,
**kwargs
):
if not isinstance(block, blocks.Block) and issubclass(block, blocks.Block):
block = block()
self.block = block
self.block.set_name(
self.block.__class__.__name__.lower()
)
super().__init__(
tool_name, klass, None, None, None, config, weight, allowed_tags, allowed_attributes, **kwargs
)
def init_static(self, css, js):
pass
def init_attrs(self, allowed_tags, allowed_attributes):
pass
@cached_property
def widget(self):
return blocks.BlockWidget(self.block)
def get_config(self, context: dict[str, Any] = None) -> dict:
data = super().get_config(context)
config = data.get("config", {})
config["rendered"] = self.widget.render_with_errors(
"__PREFIX__", self.block.get_default(),
)
data["config"] = config
return data
@cached_property
def allowed_tags(self):
return get_allowed_tags(self, self.block)
@cached_property
def allowed_attributes(self):
return get_allowed_attributes(self, self.block)
@property
def js(self):
return [
*self.widget.media._js,
mark_safe(f"<script src=\"{ static('wagtail_editorjs/js/tools/wagtail-block.js') }\" data-name=\"{ self.block.name }\" data-title=\"{ self.block.label }\"></script>"),
]
def validate(self, data: Any):
super().validate(data)
if "block" not in data["data"]:
raise forms.ValidationError("Invalid block value")
try:
data["data"]["block"] = self.block.get_prep_value(
self.block.clean(self.block.to_python(data["data"]["block"]))
)
except blocks.StreamBlockValidationError as e:
raise e
except blocks.list_block.ListBlockValidationError as e:
raise e
except blocks.struct_block.StructBlockValidationError as e:
raise e
except Exception as e:
raise e
def value_for_form(self, value: dict) -> dict:
value = super().value_for_form(value)
value["data"]["block"] = self.block.get_form_state(
self.block.to_python(value["data"]["block"])
)
return value
def render_block_data(self, block: EditorJSBlock, context=None) -> EditorJSElement:
value: blocks.StructValue = self.block.to_python(block["data"]["block"])
return EditorJSSoupElement(f"<div class=\"{self.tool_name}\">{ self.block.render(value) }</div>")
@classmethod
def get_test_data(cls):
return []
@property
def css(self):
return self.widget.media._css
@property
def klass(self):
return f"WagtailBlockTool_{ self.block.name }"
@js.setter
def js(self, data: Any): pass
@css.setter
def css(self, data: Any): pass
@klass.setter
def klass(self, data: Any): pass
from wagtail.models import Page
from wagtail.admin.widgets import AdminPageChooser
class ButtonFeature(PageChooserURLsMixin, EditorJSFeature):
allowed_tags: list[str] = ["a"]
allowed_attributes: dict[str, list[str]] = {
"a": ["href", "class"]
}
chooser_class = AdminPageChooser
model = Page
klass = "PageButtonTool"
js = [
"wagtail_editorjs/js/tools/wagtail-button-tool.js",
]
@cached_property
def widget(self):
if self.chooser_class is None:
return None
return self.chooser_class()
def validate(self, data: Any):
super().validate(data)
if "pageId" not in data["data"]:
raise forms.ValidationError("Invalid id value")
if "text" not in data["data"]:
raise forms.ValidationError("Invalid text value")
def get_config(self, context: dict[str, Any]):
config = super().get_config() or {}
config.setdefault("config", {})
config["config"][
"chooserId"
] = f"editorjs-{self.model._meta.model_name}-button-chooser-{context['widget']['attrs']['id']}"
return config
def render_block_data(self, block: EditorJSBlock, context=None) -> EditorJSElement:
try:
page = self.model.objects.get(id=block["data"]["pageId"])
except self.model.DoesNotExist:
return None
request = None
if context:
request = context.get("request")
anchor = EditorJSElement(
"a",
block["data"]["text"],
{
"href": page.get_url(request),
"class": "editor-button",
}
)
return EditorJSElement(
"div", anchor, {"class": "editor-button-container"},
)
def render_template(self, context: dict[str, Any] = None):
if not self.widget:
return super().render_template(context)
return self.widget.render_html(
f"editorjs-{self.model._meta.model_name}-button-chooser-{context['widget']['attrs']['id']}",
None,
{
"id": f"editorjs-{self.model._meta.model_name}-button-chooser-{context['widget']['attrs']['id']}"
},
)
@classmethod
def get_test_data(cls):
pages = cls.model.objects.all()[:5]
return [
{
"pageId": page.id,
"text": page.title,
}
for page in pages
]
| 15,989 | Python | .py | 437 | 26.455378 | 179 | 0.55979 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,280 | feature_registry.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/feature_registry.py | """
This module defines mappings from tools to the editorjs javascript side.
"""
from collections import defaultdict, OrderedDict
from typing import Any, Union
from wagtail import hooks
import copy
from ..hooks import (
REGISTER_HOOK_NAME,
)
from .value import (
EditorJSValue,
)
from .features import (
BaseEditorJSFeature,
EditorJSFeature,
EditorJSTune,
InlineEditorJSFeature,
)
def safe_merge(target: dict, source: dict):
for key, value in source.items():
if key in target and isinstance(value, dict):
target[key].update(value)
else:
target[key] = value
class EditorJSFeatures:
def __init__(self):
self.features: dict[str, Union[EditorJSFeature, EditorJSTune]] = {}
self.inline_features: list[InlineEditorJSFeature] = []
self.tunes_for_all: list[str] = []
self.tunes_for_tools: defaultdict[str, list[str]] = defaultdict(list)
self._looked_for_features = False
def __contains__(self, tool_name: str):
self._look_for_features()
return tool_name in self.features
def __getitem__(self, tool_name: str) -> Union[EditorJSFeature, EditorJSTune, InlineEditorJSFeature]:
self._look_for_features()
if isinstance(tool_name, BaseEditorJSFeature):
return tool_name
return self.features[tool_name]
def keys(self):
self._look_for_features()
return self.features.keys()
def _look_for_features(self):
if not self._looked_for_features:
for hook in hooks.get_hooks(REGISTER_HOOK_NAME):
hook(self)
self._looked_for_features = True
def register(self, tool_name: str, feature: EditorJSFeature):
"""
Register a feature with the EditorJS editor.
After registering it; you can easily use this by
providing the `tool_name` into `features` for widgets and fields.
"""
self.features[tool_name] = feature
if isinstance(feature, InlineEditorJSFeature):
self.inline_features.append(feature)
# Callback to the feature in case it needs to do something
# after being registered. (like registering admin urls.)
feature.on_register(self)
def register_tune(self, tune_name: str, tool_name: str = None):
"""
Register a tune (BY NAME) for a tool.
This tune will be made available to only that tool (unless otherwise specified)
If not providing a `tool_name`; the tune will be available to all tools.
"""
if tool_name:
self.tunes_for_tools[tool_name].append(tune_name)
else:
self.tunes_for_all.append(tune_name)
def register_config(self, tool_name: str, config: dict):
"""
Register or override any additional configuration for a tool.
"""
self._look_for_features()
self.features[tool_name].config.update(config)
def build_config(self, tools: list[str], context: dict[str, Any] = None):
"""
Builds out the configuration for the EditorJS widget.
This config is passed into the editorjs javascript side.
"""
editorjs_config = {}
editorjs_config_tools = {}
self._look_for_features()
t_ui = {}
t_toolNames = {}
t_blockTunes = {}
t_tools = defaultdict(dict)
for tool in tools:
if tool not in self.features:
raise ValueError(f"Unknown feature: {tool}")
tool_mapping = self.features[tool]
tool_config = tool_mapping.get_config(context)
if tool_config is None:
continue
tool_config = copy.deepcopy(tool_config)
if "tunes" in tool_config:
raise ValueError(f"Tunes must be registered separately for {tool}")
tunes = self.tunes_for_tools[tool]
if tunes:
tool_config["tunes"] = tunes
translations = tool_mapping.get_translations()
if translations:
translations_ui = translations.get("ui")
if translations_ui:
safe_merge(t_ui, translations_ui)
t_toolNames.update(
translations.get("toolNames"),
)
t_blockTunes.update(
translations.get("blockTunes"),
)
t_tools[tool].update(
translations.get("tools"),
)
editorjs_config_tools[tool] = tool_config
i18n = {}
if t_ui:
i18n["ui"] = t_ui
if t_toolNames:
i18n["toolNames"] = t_toolNames
if t_tools:
i18n["tools"] = t_tools
if t_blockTunes:
i18n["blockTunes"] = t_blockTunes
if i18n:
editorjs_config["i18n"] = {
"messages": i18n
}
if self.tunes_for_all:
editorjs_config["tunes"] = list(
filter(lambda tune: tune in tools, self.tunes_for_all)
)
editorjs_config["tools"] = editorjs_config_tools
return editorjs_config
def to_python(self, tools: list[str], data: list[dict]):
"""
Converts the data from the editorjs format to the python format.
"""
if isinstance(data, EditorJSValue):
return data
self._look_for_features()
block_list = data.get("blocks", [])
features = {
tool: self.features[tool]
for tool in tools
}
for i, item in enumerate(block_list):
block_type = item.get("type")
if block_type not in tools:
continue
tool_mapping = features[block_type]
block_list[i] = tool_mapping.create_block(tools, item)
data["blocks"] = block_list
return EditorJSValue(
data,
{
tool: self.features[tool]
for tool in tools
}
)
def prepare_value(self, tools: list[str], data: dict):
"""
Filters out unknown features and tunes.
Return the value back to native format.
"""
self._look_for_features()
block_list = data.get("blocks", [])
blocks = [None] * len(block_list)
for i, item in enumerate(block_list):
block_type = item.get("type")
if block_type not in tools:
continue
tunes = item.get("tunes", {})
if tunes:
keys = list(tunes.keys())
for key in keys:
if key not in tools:
del tunes[key]
blocks[i] = item
data["blocks"] = list(filter(None, blocks))
return data
def value_for_form(self, tools: list[str], data: dict):
for i, item in enumerate(data["blocks"]):
block_type = item.get("type")
data["blocks"][i] = self[block_type].value_for_form(item)
return data
def get_by_weight(self, tools: list[str]) -> OrderedDict[str, EditorJSFeature]:
"""
Returns the tools sorted by weight.
Items with the lowest weight are first.
"""
self._look_for_features()
od = OrderedDict()
values = list(self.features.values())
values.sort(key=lambda x: x.weight)
for value in values:
if value.tool_name in tools:
od[value.tool_name] = value
return od
def validate_for_tools(self, tools: list[str], data: dict):
"""
Validates the data for the given tools.
"""
self._look_for_features()
block_list = data.get("blocks", [])
for tool in tools:
if tool not in self.features:
raise ValueError(f"Unknown feature: {tool}")
tool_mapping = self.features[tool]
for item in block_list:
if isinstance(tool_mapping, EditorJSTune):
tunes = item.get("tunes", {})
tune = tunes.get(tool)
if tune:
tool_mapping.validate(tune)
else:
if item["type"] == tool:
tool_mapping.validate(item)
data["blocks"] = block_list
return data
| 8,569 | Python | .py | 221 | 27.361991 | 105 | 0.563541 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,281 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/__init__.py | from .feature_registry import (
EditorJSFeatures,
)
from .features import (
PageChooserURLsMixin,
BaseEditorJSFeature,
EditorJSFeature,
EditorJSJavascriptFeature,
EditorJSTune,
FeatureViewMixin,
InlineEditorJSFeature,
ModelInlineEditorJSFeature,
TemplateNotSpecifiedError,
)
from .value import (
EditorJSBlock,
EditorJSValue,
)
from .element import (
EditorJSElement,
EditorJSSoupElement,
EditorJSWrapper,
wrapper,
EditorJSElementAttribute,
EditorJSStyleAttribute,
wrap_tag,
add_attributes,
)
def get_features(features: list[str] = None):
if not features:
features = list(EDITOR_JS_FEATURES.keys())
for feature in features:
if feature not in EDITOR_JS_FEATURES:
raise ValueError(f"Unknown feature: {feature}")
return features
EDITOR_JS_FEATURES = EditorJSFeatures()
| 891 | Python | .py | 36 | 20.277778 | 59 | 0.74 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,282 | value.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/value.py | from typing import Any, Union, TYPE_CHECKING
import datetime
if TYPE_CHECKING:
from .features import EditorJSFeature
class EditorJSBlock(dict):
def __init__(self, data: dict, features: list[str]):
self.features = features
super().__init__(data)
@property
def id(self):
return self.get("id")
@property
def type(self):
return self.get("type")
@property
def data(self):
return self.get("data", {})
@property
def tunes(self):
return self.get("tunes", {})
class EditorJSValue(dict):
def __init__(self, data: dict, features: dict[str, "EditorJSFeature"]):
self._features = features
super().__init__(data)
@property
def blocks(self) -> list["EditorJSBlock"]:
return self["blocks"]
@property
def time(self):
time = self.get("time")
if time is None:
return None
return datetime.datetime.fromtimestamp(time)
@property
def version(self):
return self.get("version")
@property
def features(self) -> list["EditorJSFeature"]:
return self._features
def __getitem__(self, __key: Any) -> Any:
if isinstance(__key, int):
return self.blocks[__key]
return super().__getitem__(__key)
def get_blocks_by_name(self, name: str) -> list["EditorJSBlock"]:
if name not in self._features:
return []
return [
block
for block in self.blocks
if block.get('type') == name
]
def get_block_by_id(self, id: str) -> "EditorJSBlock":
for block in self.blocks:
if block.get("id") == id:
return block
return None
def get_range(self, start: int, end: int) -> list["EditorJSBlock"]:
return self["blocks"][start:end]
def set_range(self, start: int, end: int, blocks: list["EditorJSBlock"]):
b = self["blocks"]
if start < 0:
start = 0
if end > len(b):
end = len(b)
if start > end:
start = end
if start == end:
return
b[start:end] = list(
map(self._verify_block, blocks),
)
self["blocks"] = b
def insert(self, index: int, block: "EditorJSBlock"):
block = self._verify_block(block)
self.blocks.insert(index, block)
def append(self, block: "EditorJSBlock"):
block = self._verify_block(block)
self.blocks.append(block)
def _verify_block(self, block: Union["EditorJSBlock", dict]):
if block.get("type") not in self._features:
raise ValueError(f"Unknown feature: {block.get('type')}")
if block.get("id") is None:
raise ValueError("Block ID not set")
if not isinstance(block, EditorJSBlock)\
and isinstance(block, dict):
block = self._features[block["type"]].create_block(
list(self._features.keys()),
block
)
return block
| 3,190 | Python | .py | 90 | 25.344444 | 77 | 0.570268 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,283 | attrs.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/element/attrs.py | from typing import Any, Union
class EditorJSElementAttribute:
def __init__(self, value: Union[str, list[str]], delimiter: str = " "):
if not isinstance(value, (list, dict)):
value = [value]
if not isinstance(value, dict):
value = set(value)
self.value = value
self.delimiter = delimiter
def __eq__(self, other):
if isinstance(other, EditorJSElementAttribute):
return self.value == other.value
if isinstance(other, (tuple, list, set)):
for item in other:
if item not in self.value:
return False
return True
return False
def extend(self, value: Any):
if isinstance(value, (tuple, list, set)):
self.value.update(value)
else:
self.value.add(value)
def __str__(self):
return self.delimiter.join([str(item) for item in self.value])
class EditorJSStyleAttribute(EditorJSElementAttribute):
def __init__(self, value: dict):
super().__init__(value, ";")
def __repr__(self):
return f"EditorJSStyleAttribute({self.value})"
def __eq__(self, other):
if isinstance(other, EditorJSStyleAttribute):
return self.value == other.value
if isinstance(other, dict):
return self.value == other
if isinstance(other, str):
try:
key, value = other.split(":")
return self.value.get(key) == value.strip()
except ValueError:
return False
return False
def extend(self, value: dict = None, **kwargs):
if value:
if not isinstance(value, dict):
raise ValueError("Value must be a dictionary")
self.value.update(value)
self.value.update(kwargs)
def __str__(self):
return self.delimiter.join([f'{key}: {value}' for key, value in self.value.items()])
| 2,004 | Python | .py | 50 | 29.26 | 92 | 0.57892 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,284 | element.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/element/element.py | from typing import Any, Union, TypeVar
from .attrs import EditorJSElementAttribute
from .utils import add_attributes, wrap_tag, _make_attr
import bs4
ElementType = TypeVar("ElementType", bound="EditorJSElement")
class EditorJSElement:
"""
Base class for all elements.
"""
def __init__(self, tag: str, content: Union[str, list[str]] = None, attrs: dict[str, EditorJSElementAttribute] = None, close_tag: bool = True):
attrs = attrs or {}
content = content or []
if not isinstance(attrs, EditorJSElementAttribute):
attrs = {
key: _make_attr(value)
for key, value in attrs.items()
}
if isinstance(content, str):
content = [content]
self.tag = tag
self._content = content
self.attrs = attrs
self.close_tag = close_tag
@property
def is_wrapped(self):
return False
def __setitem__(self, key, value):
if "key" in self.attrs:
attrs = self.attrs[key]
attrs.append(value)
self.attrs[key] = attrs
else:
self.attrs[key] = _make_attr(value)
def add_attributes(self, **attrs: Union[str, list[str], dict[str, Any]]):
return add_attributes(self, **attrs)
@property
def content(self):
if isinstance(self._content, list):
return "\n".join([str(item) for item in self._content])
return str(self._content)
@content.setter
def content(self, value):
if isinstance(value, list):
self._content = value
else:
self._content = [value]
def append(self, element: "EditorJSElement"):
self._content.append(element)
def __str__(self):
return wrap_tag(
self.tag,
attrs = self.attrs,
content = self.content,
close_tag = self.close_tag
)
class EditorJSSoupElement(EditorJSElement):
def __init__(self, raw_html: str):
self.raw_html = raw_html
self.soup = bs4.BeautifulSoup(raw_html, "html.parser")
self.soupContent = self.soup.contents[0]
@property
def content(self):
return str(self.soup)
@content.setter
def content(self, value):
self.soup = bs4.BeautifulSoup(value, "html.parser")
self.soupContent = self.soup.contents[0]
@property
def attrs(self):
return self.soupContent.attrs
def __str__(self):
return str(self.soup)
def append(self, element: "EditorJSElement"):
if isinstance(element, EditorJSSoupElement):
self.soupContent.append(element.soup)
elif isinstance(element, str):
self.soupContent.append(element)
elif isinstance(element, EditorJSElement):
self.soupContent.append(str(element))
else:
raise TypeError(f"Invalid type {type(element)}")
def add_attributes(self, **attrs: Union[str, list[str], dict[str, Any]]):
for key, value in attrs.items():
if key == "class_" or key == "class":
classList = self.soupContent.get("class", [])
if isinstance(value, str):
classList.append(value)
elif isinstance(value, list):
classList.extend(value)
self.soupContent["class"] = classList
else:
self.soupContent[key] = value
def wrapper(element: EditorJSElement, attrs: dict[str, EditorJSElementAttribute] = None, tag: str = "div"):
if isinstance(element, EditorJSWrapper) or getattr(element, "is_wrapped", False):
return add_attributes(element, **attrs)
return EditorJSWrapper(element, attrs=attrs, tag=tag)
class EditorJSWrapper(EditorJSElement):
@property
def is_wrapped(self):
return True
@property
def wrapped_element(self) -> Union[ElementType, list[ElementType]]:
if len(self._content) > 1:
return self._content
return self._content[0]
def __init__(self,
content: Union[ElementType, list[ElementType]],
attrs: dict[str, EditorJSElementAttribute] = None,
close_tag: bool = True,
tag: str = "div",
):
if not isinstance(content, (list, tuple)):
content = [content]
for item in content:
item_type = type(item)
if item_type == EditorJSWrapper:
raise ValueError(
"Cannot nest EditorJSWrapper elements\n"
"Please check if the element is already wrapped before re-wrapping.\n"
)
if not issubclass(item_type, EditorJSElement):
raise ValueError(f"Expected EditorJSElement got {type(item)}")
super().__init__(tag, content, attrs, close_tag)
| 4,950 | Python | .py | 123 | 29.869919 | 147 | 0.599534 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,285 | utils.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/element/utils.py | from typing import Any, Union, TYPE_CHECKING
if TYPE_CHECKING:
from .element import EditorJSElement
from .attrs import (
EditorJSElementAttribute,
EditorJSStyleAttribute,
)
def make_attrs(attrs: dict[str, Any]) -> str:
attrs = {
key: _make_attr(value)
for key, value in attrs.items()
}
return " ".join([f'{key}="{value}"' for key, value in attrs.items()])
def wrap_tag(tag_name, attrs, content = None, close_tag = True):
attrs = attrs or {}
attributes = f" {make_attrs(attrs)}" if attrs else ""
if content is None and close_tag:
return f"<{tag_name}{attributes}></{tag_name}>"
elif content is None and not close_tag:
return f"<{tag_name}{attributes}>"
return f"<{tag_name}{attributes}>{content}</{tag_name}>"
def add_attributes(element: "EditorJSElement", **attrs: Union[str, list[str], dict[str, Any]]):
"""
Adds attributes to the element.
"""
for key, value in attrs.items():
if key.endswith("_"):
key = key[:-1]
if key in element.attrs:
element.attrs[key].extend(value)
else:
element.attrs[key] = _make_attr(value)
return element
def _make_attr(value: Union[str, list[str], dict[str, Any]]):
if isinstance(value, EditorJSElementAttribute):
return value
if isinstance(value, dict):
return EditorJSStyleAttribute(value)
return EditorJSElementAttribute(value)
| 1,469 | Python | .py | 39 | 31.307692 | 95 | 0.646558 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,286 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/element/__init__.py | from .attrs import (
EditorJSElementAttribute,
EditorJSStyleAttribute,
)
from .utils import (
wrap_tag,
add_attributes,
)
from .element import (
EditorJSElement,
EditorJSSoupElement,
EditorJSWrapper,
wrapper,
) | 242 | Python | .py | 14 | 14.071429 | 29 | 0.737991 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,287 | inlines.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/inlines.py | from typing import Any, Union
from django.utils.functional import cached_property
from ...settings import USE_FULL_URLS
from .base import BaseEditorJSFeature
import bs4
class InlineEditorJSFeature(BaseEditorJSFeature):
must_have_attrs = None
can_have_attrs = None
tag_name = None
def __init__(
self,
tool_name: str,
tag_name: str = None,
klass: str = None,
must_have_attrs: dict = None,
can_have_attrs: dict = None,
js: Union[str, list[str]] = None,
css: Union[str, list[str]] = None,
include_template: str = None,
config: dict = None,
weight: int = 0,
allowed_tags: list[str] = None,
allowed_attributes: dict[str, list[str]] = None,
**kwargs,
):
super().__init__(
tool_name,
klass,
js,
css,
include_template,
config,
weight=weight,
allowed_tags=allowed_tags,
allowed_attributes=allowed_attributes,
**kwargs,
)
must_have_attrs = must_have_attrs or {}
can_have_attrs = can_have_attrs or {}
if self.must_have_attrs:
must_have_attrs.update(self.must_have_attrs)
if self.can_have_attrs:
can_have_attrs.update(self.can_have_attrs)
self.tag_name = tag_name or self.tag_name
self.must_have_attrs = must_have_attrs
self.can_have_attrs = can_have_attrs
def build_elements(self, inline_data: list, context: dict[str, Any] = None) -> list:
"""
Builds the elements for the inline data.
See the LinkFeature class for an example.
"""
pass
def filter(self, item):
"""
Filter function for the bs4 find_all method.
Extracts the tag name and attributes from the item and compares them to the must_have_attrs.
If the item attributes matches the must_have_attrs the element is what we need.
"""
if item.name != self.tag_name:
return False
for key, value in self.must_have_attrs.items():
if not value:
if not item.has_attr(key):
return False
else:
cmp = item.get(key)
if isinstance(cmp, str):
cmp = cmp.strip()
if cmp != value:
return False
elif isinstance(cmp, list):
if value not in cmp:
return False
else:
return False
return True
def parse_inline_data(self, soup: bs4.BeautifulSoup, context=None):
"""
Finds inline elements by the must_have_attrs and can_have_attrs.
Designed to be database-efficient; allowing for gathering of all data before
making a database request.
I.E. For a link; this would gather all page ID's and fetch them in a single query.
"""
matches: dict[Any, dict[str, Any]] = {}
elements = soup.find_all(self.filter)
if not elements:
return None
for item in elements:
matches[item] = {}
for key in self.must_have_attrs.keys():
matches[item][key] = item.get(key)
for key, value in self.can_have_attrs.items():
v = item.get(key)
if v:
matches[item][key] = v
elif item.has_attr(key):
matches[item][key] = True
# Build all inlines.
self.build_elements(list(matches.items()), context=context)
@classmethod
def get_test_data(cls) -> list[tuple[str, str]]:
"""
Returns a list of test data.
The test data should be a list of tuples.
The first item in the tuple is the raw HTML tag.
The second item is the expected output.
The raw HTML tag(s) will be randomly appended into a soup.
We will use assertQueries(1) to ensure any database queries are kept to a minimum.
"""
return []
class ModelInlineEditorJSFeature(InlineEditorJSFeature):
model = None
chooser_class = None
tag_name = "a"
id_attr = "data-id"
def __init__(self, *args, **kwargs):
super().__init__(*args, tag_name=self.tag_name, **kwargs)
self.must_have_attrs = self.must_have_attrs | {
self.id_attr: None,
f"data-{self.model._meta.model_name}": None,
}
@cached_property
def widget(self):
if self.chooser_class is None:
return None
return self.chooser_class()
def get_id(self, item, attrs: dict[str, Any], context: dict[str, Any] = None):
return int(attrs[self.id_attr])
def get_config(self, context: dict[str, Any]):
config = super().get_config() or {}
config.setdefault("config", {})
config["config"][
"chooserId"
] = f"editorjs-{self.model._meta.model_name}-chooser-{context['widget']['attrs']['id']}"
return config
def render_template(self, context: dict[str, Any] = None):
if not self.widget:
return super().render_template(context)
return self.widget.render_html(
f"editorjs-{self.model._meta.model_name}-chooser-{context['widget']['attrs']['id']}",
None,
{
"id": f"editorjs-{self.model._meta.model_name}-chooser-{context['widget']['attrs']['id']}"
},
)
def build_element(self, item, obj, context: dict[str, Any] = None, data: dict[str, Any] = None):
"""
Build the element from the object.
item: bs4.element.Tag
obj: Model
context: RequestContext | None
"""
# delete all attributes
for key in list(item.attrs.keys()):
del item[key]
request = None
if context and "request" in context and USE_FULL_URLS:
request = context.get("request")
item["href"] = self.get_full_url(obj, request)
else:
item["href"] = self.get_url(obj)
item["class"] = f"{self.model._meta.model_name}-link"
@classmethod
def get_url(cls, instance):
return instance.url
@classmethod
def get_full_url(cls, instance, request):
return request.build_absolute_uri(cls.get_url(instance))
def build_elements(self, inline_data: list, context: dict[str, Any] = None) -> list:
"""
Process the bulk data; fetch all pages in one go
and build the elements.
"""
super().build_elements(inline_data, context=context)
ids = []
# element_soups = []
for data in inline_data:
# soup: BeautifulSoup
# element: EditorJSElement
# matches: dict[bs4.elementType, dict[str, Any]]
# data: dict[str, Any] # Block data.
item, data = data
# Item is bs4 tag, attrs are must_have_attrs and can_have_attrs
id = self.get_id(item, data, context)
ids.append((item, id, data))
# delete all attributes
for key in list(item.attrs.keys()):
del item[key]
# Fetch all objects
objects = self.model.objects.in_bulk([id for _, id, _ in ids])
for item, id, data in ids:
self.build_element(item, objects[id], context, data)
def get_css(self):
return self.widget.media._css.get("all", []) + super().get_css()
def get_js(self):
return (self.widget.media._js or []) + super().get_js()
@classmethod
def get_test_queryset(cls):
return cls.model.objects.all()
@classmethod
def get_test_data(cls):
# This test only works for the default build_element method.
# Any extra attributes will make this test fail otherwise.
if cls.build_element is not ModelInlineEditorJSFeature.build_element:
raise ValueError(
"You must implement the get_test_data method for your ModelInlineEditorJSFeature"
"if you override the build_element method."
)
# Limit test QS to 5.
models = cls.get_test_queryset()[0:5]
return [
(
f"<a data-id='{model.id}' data-{cls.model._meta.model_name}='True'></a>",
f"<a href='{cls.get_url(model)}' class='{cls.model._meta.model_name}-link'></a>",
)
for model in models
]
| 8,610 | Python | .py | 217 | 29.248848 | 106 | 0.569473 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,288 | basic.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/basic.py | from typing import Any, Union
from django import forms
from ..element import EditorJSElement
from ..value import EditorJSBlock
from .base import BaseEditorJSFeature
class EditorJSJavascriptFeature(BaseEditorJSFeature):
def __init__(self, tool_name: str, js: Union[str, list[str]] = None, css: Union[str, list[str]] = None, weight: int = 0, allowed_tags: list[str] = None, allowed_attributes: dict[str, list[str]] = None):
# 1 for klass - unused for this type of feature.
super().__init__(tool_name, 1, js, css, None, {}, weight=weight, allowed_tags=allowed_tags, allowed_attributes=allowed_attributes)
def get_config(self, context: dict[str, Any] = None) -> dict:
"""
Javascript only features do not get access to any configuration.
They are not passed into the EditorJS tools.
"""
return None
class EditorJSFeature(BaseEditorJSFeature):
def validate(self, data: Any):
"""
Perform basic validation for an EditorJS block feature.
"""
if not data:
return
if "data" not in data:
raise forms.ValidationError("Invalid data format")
def render_block_data(self, block: EditorJSBlock, context = None) -> "EditorJSElement":
return EditorJSElement(
"p",
block["data"].get("text")
)
@classmethod
def get_test_data(cls):
return [
{
"text": "Hello, world!"
}
]
get_test_data.__doc__ = BaseEditorJSFeature.get_test_data.__doc__
class EditorJSTune(BaseEditorJSFeature):
"""
Works mostly like EditorJSFeature, but is used for tunes.
Handles validation differently.
"""
def tune_element(self, element: "EditorJSElement", tune_value: Any, context = None) -> "EditorJSElement":
"""
Perform any action on the element based on the data provided by the tune.
"""
return element
@classmethod
def get_test_data(cls):
"""
Currently automatic tests for tunes are unsupported.
"""
return None
| 2,168 | Python | .py | 53 | 32.320755 | 206 | 0.632162 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,289 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/__init__.py | from .base import (
PageChooserURLsMixin,
TemplateNotSpecifiedError,
BaseEditorJSFeature,
)
from .basic import (
EditorJSFeature,
EditorJSJavascriptFeature,
EditorJSTune,
)
from .inlines import (
InlineEditorJSFeature,
ModelInlineEditorJSFeature,
)
from .view import (
FeatureViewMixin,
) | 324 | Python | .py | 17 | 16 | 31 | 0.775974 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,290 | snippets_inlines.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/snippets_inlines.py | from typing import Any
from .inlines import (
ModelInlineEditorJSFeature,
)
from wagtail.snippets.widgets import AdminSnippetChooser
class SnippetChooserModel:
""" Utility class for type annotations """
def build_element(self, soup_elem, context = None): ...
class BaseInlineSnippetChooserFeature(ModelInlineEditorJSFeature):
model: SnippetChooserModel = None
widget = AdminSnippetChooser
def build_element(self, soup_elem, obj: SnippetChooserModel, context: dict[str, Any] = None, data: dict[str, Any] = None):
""" Build the element from the object. """
return obj.build_element(soup_elem, context)
| 650 | Python | .py | 14 | 41.857143 | 126 | 0.753994 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,291 | base.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/base.py | from typing import Any, Union, Mapping, Literal, TYPE_CHECKING
from django.urls import reverse_lazy
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from ..value import (
EditorJSBlock,
)
if TYPE_CHECKING:
from ..feature_registry import EditorJSFeatures
class TemplateNotSpecifiedError(Exception):
pass
I18nDictionary = Mapping[
Literal["ui", "toolNames", "tools", "blockTunes"],
Mapping[str, str]
]
class PageChooserURLsMixin:
def get_config(self, context: dict[str, Any] = None) -> dict:
config = super().get_config(context)
config.setdefault("config", {})
config["config"]["chooserUrls"] = {
"pageChooser": reverse_lazy(
"wagtailadmin_choose_page",
),
"externalLinkChooser": reverse_lazy(
"wagtailadmin_choose_page_external_link",
),
"emailLinkChooser": reverse_lazy(
"wagtailadmin_choose_page_email_link",
),
"phoneLinkChooser": reverse_lazy(
"wagtailadmin_choose_page_phone_link",
),
"anchorLinkChooser": reverse_lazy(
"wagtailadmin_choose_page_anchor_link",
),
},
return config
class BaseEditorJSFeature:
allowed_tags: list[str] = None
allowed_attributes: dict[str, list[str]] = None
translations: I18nDictionary = {}
klass: str = None
js: list[str] = None
css: list[str] = None
frontend_css: list[str] = []
frontend_js: list[str] = []
# cleaner_funcs: dict[str, dict[str, Callable[[str], bool]]] = {}
def __init__(self,
tool_name: str,
klass: str = None,
js: Union[str, list[str]] = None,
css: Union[str, list[str]] = None,
include_template: str = None,
config: dict = None,
weight: int = 0, # Weight is used to manage which features.js files are loaded first.
allowed_tags: list[str] = None,
allowed_attributes: dict[str, list[str]] = None,
**kwargs
):
if not klass and not self.klass:
raise ValueError("klass must be provided")
if not klass:
klass = self.klass
self.tool_name = tool_name
self.klass = klass
self.config = config or dict()
self.kwargs = kwargs
self.weight = weight
self.include_template = include_template
self.init_static(
css, js,
)
self.init_attrs(
allowed_tags, allowed_attributes,
)
def value_for_form(self, value: dict) -> dict:
"""
Prepare the value for the feature.
This is useful for when you need to modify the data
before it is passed to the frontend.
"""
return value
def init_static(self, css, js):
css = css or []
js = js or []
if self.css:
css.extend(self.css)
if self.js:
js.extend(self.js)
self.js = js
self.css = css
def init_attrs(self, allowed_tags, allowed_attributes):
if not isinstance(allowed_tags, (list, tuple, set)) and allowed_tags is not None:
raise ValueError("allowed_tags must be a list, tuple or set")
if not isinstance(allowed_attributes, dict) and allowed_attributes is not None:
raise ValueError("allowed_attributes must be a dict")
allowed_tags = allowed_tags or []
allowed_attributes = allowed_attributes or dict()
if self.allowed_tags:
allowed_tags.extend(self.allowed_tags)
if self.allowed_attributes:
if isinstance(self.allowed_attributes, dict):
for key, value in self.allowed_attributes.items():
allowed_attributes[key] = set(allowed_attributes.get(key, []) + value)
elif isinstance(self.allowed_attributes, list):
if not self.allowed_tags:
raise ValueError("Allowed attributes is specified as a list without allowed tags; provide allowed tags.")
for tag in self.allowed_tags:
allowed_attributes[tag] = set(allowed_attributes.get(tag, []) + self.allowed_attributes)
else:
raise ValueError("Invalid allowed attributes type, self.allowed_attributes must be dict or list")
self.allowed_tags = set(allowed_tags)
self.allowed_attributes = allowed_attributes
def on_register(self, registry: "EditorJSFeatures"):
"""
Called when the feature is registered.
This can be used to say; register URLs
required for this feature to work.
"""
pass
def __repr__(self):
return f"<EditorJSFeature \"{self.tool_name}\">"
@classmethod
def get_test_data(cls):
"""
Returns test data for the feature.
This is so it can easily be integrated with our tests.
Any extra testing you deem necessary should be done in
separate tests.
"""
return []
def get_template_context(self, context: dict[str, Any] = None) -> dict:
"""
Returns the context for the template. (if any template is provided)
"""
return context
def render_template(self, context: dict[str, Any] = None):
"""
Renders a template inside of the widget container.
This is useful for things like the image feature.
"""
if self.include_template and hasattr(self.include_template, "render"):
return self.include_template.render(self.get_template_context(context))
elif self.include_template:
context = self.get_template_context(context)
rendered = render_to_string(self.include_template, context)
return mark_safe(rendered)
raise TemplateNotSpecifiedError("Template not specified for this feature")
def get_config(self, context: dict[str, Any] = None) -> dict:
"""
Returns the config for the feature.
This is what will be passed to javascript.
The `class` is extracted from window[`class`].
"""
config = {
"class": self.klass,
}
if self.config:
config["config"] = self.config
if self.kwargs:
config.update(self.kwargs)
return config
def get_translations(self) -> I18nDictionary:
return self.translations
def get_js(self):
"""
Return any javascript files required for this feature to work.
"""
if not self.js:
return []
if isinstance(self.js, str):
return [self.js]
return self.js
def get_css(self):
"""
Return any css files required for this feature to work.
"""
if not self.css:
return []
if isinstance(self.css, str):
return [self.css]
return self.css
def get_frontend_css(self):
"""
Returns the css files required for the frontend.
"""
return self.frontend_css
def get_frontend_js(self):
"""
Returns the js files required for the frontend.
"""
return self.frontend_js
def validate(self, data: Any):
"""
Validate any data coming from editorJS
for completeness and correctness.
"""
pass
def create_block(self, tools: list[str], data: dict) -> EditorJSBlock:
"""
Create a block from the data.
This block is the value that the developer will work with.
It is a subclass of `dict`.
"""
return EditorJSBlock(data, tools)
| 8,021 | Python | .py | 205 | 28.565854 | 125 | 0.591658 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,292 | view.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/registry/features/view.py | from typing import TYPE_CHECKING
from django.urls import path
from django.http import HttpRequest, HttpResponseNotAllowed
from wagtail import hooks
if TYPE_CHECKING:
from ..feature_registry import EditorJSFeatures
class FeatureViewMixin:
def handler(self, request: HttpRequest, *args, **kwargs):
method = request.method.lower()
if not hasattr(self, f"handle_{method}"):
return self.method_not_allowed(request)
view_func = getattr(self, f"handle_{method}")
return view_func(request, *args, **kwargs)
def method_not_allowed(self, request: HttpRequest):
methods = ["get", "post", "put", "patch", "delete"]
methods = [m for m in methods if hasattr(self, f"handle_{m}")]
return HttpResponseNotAllowed(methods)
def get_urlpatterns(self):
return [
path(
f"{self.tool_name}/",
self.handler,
name=self.tool_name,
)
]
def on_register(self, registry: "EditorJSFeatures"):
super().on_register(registry)
@hooks.register("register_editorjs_urls")
def register_admin_urls():
return self.get_urlpatterns()
| 1,219 | Python | .py | 30 | 32 | 70 | 0.641638 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,293 | tippy-bundle.min.js | Nigel2392_wagtail_editorjs/wagtail_editorjs/static/wagtail_editorjs/vendor/tippy/tippy-bundle.min.js | !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("@popperjs/core")):"function"==typeof define&&define.amd?define(["@popperjs/core"],e):(t=t||self).tippy=e(t.Popper)}(this,(function(t){"use strict";var e="undefined"!=typeof window&&"undefined"!=typeof document,n=!!e&&!!window.msCrypto,r={passive:!0,capture:!0},o=function(){return document.body};function i(t,e,n){if(Array.isArray(t)){var r=t[e];return null==r?Array.isArray(n)?n[e]:n:r}return t}function a(t,e){var n={}.toString.call(t);return 0===n.indexOf("[object")&&n.indexOf(e+"]")>-1}function s(t,e){return"function"==typeof t?t.apply(void 0,e):t}function u(t,e){return 0===e?t:function(r){clearTimeout(n),n=setTimeout((function(){t(r)}),e)};var n}function p(t,e){var n=Object.assign({},t);return e.forEach((function(t){delete n[t]})),n}function c(t){return[].concat(t)}function f(t,e){-1===t.indexOf(e)&&t.push(e)}function l(t){return t.split("-")[0]}function d(t){return[].slice.call(t)}function v(t){return Object.keys(t).reduce((function(e,n){return void 0!==t[n]&&(e[n]=t[n]),e}),{})}function m(){return document.createElement("div")}function g(t){return["Element","Fragment"].some((function(e){return a(t,e)}))}function h(t){return a(t,"MouseEvent")}function b(t){return!(!t||!t._tippy||t._tippy.reference!==t)}function y(t){return g(t)?[t]:function(t){return a(t,"NodeList")}(t)?d(t):Array.isArray(t)?t:d(document.querySelectorAll(t))}function w(t,e){t.forEach((function(t){t&&(t.style.transitionDuration=e+"ms")}))}function x(t,e){t.forEach((function(t){t&&t.setAttribute("data-state",e)}))}function E(t){var e,n=c(t)[0];return null!=n&&null!=(e=n.ownerDocument)&&e.body?n.ownerDocument:document}function O(t,e,n){var r=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach((function(e){t[r](e,n)}))}function C(t,e){for(var n=e;n;){var r;if(t.contains(n))return!0;n=null==n.getRootNode||null==(r=n.getRootNode())?void 0:r.host}return!1}var T={isTouch:!1},A=0;function L(){T.isTouch||(T.isTouch=!0,window.performance&&document.addEventListener("mousemove",D))}function D(){var t=performance.now();t-A<20&&(T.isTouch=!1,document.removeEventListener("mousemove",D)),A=t}function k(){var t=document.activeElement;if(b(t)){var e=t._tippy;t.blur&&!e.state.isVisible&&t.blur()}}var R=Object.assign({appendTo:o,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},{animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},{allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999}),P=Object.keys(R);function j(t){var e=(t.plugins||[]).reduce((function(e,n){var r,o=n.name,i=n.defaultValue;o&&(e[o]=void 0!==t[o]?t[o]:null!=(r=R[o])?r:i);return e}),{});return Object.assign({},t,e)}function M(t,e){var n=Object.assign({},e,{content:s(e.content,[t])},e.ignoreAttributes?{}:function(t,e){return(e?Object.keys(j(Object.assign({},R,{plugins:e}))):P).reduce((function(e,n){var r=(t.getAttribute("data-tippy-"+n)||"").trim();if(!r)return e;if("content"===n)e[n]=r;else try{e[n]=JSON.parse(r)}catch(t){e[n]=r}return e}),{})}(t,e.plugins));return n.aria=Object.assign({},R.aria,n.aria),n.aria={expanded:"auto"===n.aria.expanded?e.interactive:n.aria.expanded,content:"auto"===n.aria.content?e.interactive?null:"describedby":n.aria.content},n}function V(t,e){t.innerHTML=e}function I(t){var e=m();return!0===t?e.className="tippy-arrow":(e.className="tippy-svg-arrow",g(t)?e.appendChild(t):V(e,t)),e}function S(t,e){g(e.content)?(V(t,""),t.appendChild(e.content)):"function"!=typeof e.content&&(e.allowHTML?V(t,e.content):t.textContent=e.content)}function B(t){var e=t.firstElementChild,n=d(e.children);return{box:e,content:n.find((function(t){return t.classList.contains("tippy-content")})),arrow:n.find((function(t){return t.classList.contains("tippy-arrow")||t.classList.contains("tippy-svg-arrow")})),backdrop:n.find((function(t){return t.classList.contains("tippy-backdrop")}))}}function N(t){var e=m(),n=m();n.className="tippy-box",n.setAttribute("data-state","hidden"),n.setAttribute("tabindex","-1");var r=m();function o(n,r){var o=B(e),i=o.box,a=o.content,s=o.arrow;r.theme?i.setAttribute("data-theme",r.theme):i.removeAttribute("data-theme"),"string"==typeof r.animation?i.setAttribute("data-animation",r.animation):i.removeAttribute("data-animation"),r.inertia?i.setAttribute("data-inertia",""):i.removeAttribute("data-inertia"),i.style.maxWidth="number"==typeof r.maxWidth?r.maxWidth+"px":r.maxWidth,r.role?i.setAttribute("role",r.role):i.removeAttribute("role"),n.content===r.content&&n.allowHTML===r.allowHTML||S(a,t.props),r.arrow?s?n.arrow!==r.arrow&&(i.removeChild(s),i.appendChild(I(r.arrow))):i.appendChild(I(r.arrow)):s&&i.removeChild(s)}return r.className="tippy-content",r.setAttribute("data-state","hidden"),S(r,t.props),e.appendChild(n),n.appendChild(r),o(t.props,t.props),{popper:e,onUpdate:o}}N.$$tippy=!0;var H=1,U=[],_=[];function z(e,a){var p,g,b,y,A,L,D,k,P=M(e,Object.assign({},R,j(v(a)))),V=!1,I=!1,S=!1,N=!1,z=[],F=u(wt,P.interactiveDebounce),W=H++,X=(k=P.plugins).filter((function(t,e){return k.indexOf(t)===e})),Y={id:W,reference:e,popper:m(),popperInstance:null,props:P,state:{isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},plugins:X,clearDelayTimeouts:function(){clearTimeout(p),clearTimeout(g),cancelAnimationFrame(b)},setProps:function(t){if(Y.state.isDestroyed)return;at("onBeforeUpdate",[Y,t]),bt();var n=Y.props,r=M(e,Object.assign({},n,v(t),{ignoreAttributes:!0}));Y.props=r,ht(),n.interactiveDebounce!==r.interactiveDebounce&&(pt(),F=u(wt,r.interactiveDebounce));n.triggerTarget&&!r.triggerTarget?c(n.triggerTarget).forEach((function(t){t.removeAttribute("aria-expanded")})):r.triggerTarget&&e.removeAttribute("aria-expanded");ut(),it(),J&&J(n,r);Y.popperInstance&&(Ct(),At().forEach((function(t){requestAnimationFrame(t._tippy.popperInstance.forceUpdate)})));at("onAfterUpdate",[Y,t])},setContent:function(t){Y.setProps({content:t})},show:function(){var t=Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=T.isTouch&&!Y.props.touch,a=i(Y.props.duration,0,R.duration);if(t||e||n||r)return;if(et().hasAttribute("disabled"))return;if(at("onShow",[Y],!1),!1===Y.props.onShow(Y))return;Y.state.isVisible=!0,tt()&&($.style.visibility="visible");it(),dt(),Y.state.isMounted||($.style.transition="none");if(tt()){var u=rt(),p=u.box,c=u.content;w([p,c],0)}L=function(){var t;if(Y.state.isVisible&&!N){if(N=!0,$.offsetHeight,$.style.transition=Y.props.moveTransition,tt()&&Y.props.animation){var e=rt(),n=e.box,r=e.content;w([n,r],a),x([n,r],"visible")}st(),ut(),f(_,Y),null==(t=Y.popperInstance)||t.forceUpdate(),at("onMount",[Y]),Y.props.animation&&tt()&&function(t,e){mt(t,e)}(a,(function(){Y.state.isShown=!0,at("onShown",[Y])}))}},function(){var t,e=Y.props.appendTo,n=et();t=Y.props.interactive&&e===o||"parent"===e?n.parentNode:s(e,[n]);t.contains($)||t.appendChild($);Y.state.isMounted=!0,Ct()}()},hide:function(){var t=!Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=i(Y.props.duration,1,R.duration);if(t||e||n)return;if(at("onHide",[Y],!1),!1===Y.props.onHide(Y))return;Y.state.isVisible=!1,Y.state.isShown=!1,N=!1,V=!1,tt()&&($.style.visibility="hidden");if(pt(),vt(),it(!0),tt()){var o=rt(),a=o.box,s=o.content;Y.props.animation&&(w([a,s],r),x([a,s],"hidden"))}st(),ut(),Y.props.animation?tt()&&function(t,e){mt(t,(function(){!Y.state.isVisible&&$.parentNode&&$.parentNode.contains($)&&e()}))}(r,Y.unmount):Y.unmount()},hideWithInteractivity:function(t){nt().addEventListener("mousemove",F),f(U,F),F(t)},enable:function(){Y.state.isEnabled=!0},disable:function(){Y.hide(),Y.state.isEnabled=!1},unmount:function(){Y.state.isVisible&&Y.hide();if(!Y.state.isMounted)return;Tt(),At().forEach((function(t){t._tippy.unmount()})),$.parentNode&&$.parentNode.removeChild($);_=_.filter((function(t){return t!==Y})),Y.state.isMounted=!1,at("onHidden",[Y])},destroy:function(){if(Y.state.isDestroyed)return;Y.clearDelayTimeouts(),Y.unmount(),bt(),delete e._tippy,Y.state.isDestroyed=!0,at("onDestroy",[Y])}};if(!P.render)return Y;var q=P.render(Y),$=q.popper,J=q.onUpdate;$.setAttribute("data-tippy-root",""),$.id="tippy-"+Y.id,Y.popper=$,e._tippy=Y,$._tippy=Y;var G=X.map((function(t){return t.fn(Y)})),K=e.hasAttribute("aria-expanded");return ht(),ut(),it(),at("onCreate",[Y]),P.showOnCreate&&Lt(),$.addEventListener("mouseenter",(function(){Y.props.interactive&&Y.state.isVisible&&Y.clearDelayTimeouts()})),$.addEventListener("mouseleave",(function(){Y.props.interactive&&Y.props.trigger.indexOf("mouseenter")>=0&&nt().addEventListener("mousemove",F)})),Y;function Q(){var t=Y.props.touch;return Array.isArray(t)?t:[t,0]}function Z(){return"hold"===Q()[0]}function tt(){var t;return!(null==(t=Y.props.render)||!t.$$tippy)}function et(){return D||e}function nt(){var t=et().parentNode;return t?E(t):document}function rt(){return B($)}function ot(t){return Y.state.isMounted&&!Y.state.isVisible||T.isTouch||y&&"focus"===y.type?0:i(Y.props.delay,t?0:1,R.delay)}function it(t){void 0===t&&(t=!1),$.style.pointerEvents=Y.props.interactive&&!t?"":"none",$.style.zIndex=""+Y.props.zIndex}function at(t,e,n){var r;(void 0===n&&(n=!0),G.forEach((function(n){n[t]&&n[t].apply(n,e)})),n)&&(r=Y.props)[t].apply(r,e)}function st(){var t=Y.props.aria;if(t.content){var n="aria-"+t.content,r=$.id;c(Y.props.triggerTarget||e).forEach((function(t){var e=t.getAttribute(n);if(Y.state.isVisible)t.setAttribute(n,e?e+" "+r:r);else{var o=e&&e.replace(r,"").trim();o?t.setAttribute(n,o):t.removeAttribute(n)}}))}}function ut(){!K&&Y.props.aria.expanded&&c(Y.props.triggerTarget||e).forEach((function(t){Y.props.interactive?t.setAttribute("aria-expanded",Y.state.isVisible&&t===et()?"true":"false"):t.removeAttribute("aria-expanded")}))}function pt(){nt().removeEventListener("mousemove",F),U=U.filter((function(t){return t!==F}))}function ct(t){if(!T.isTouch||!S&&"mousedown"!==t.type){var n=t.composedPath&&t.composedPath()[0]||t.target;if(!Y.props.interactive||!C($,n)){if(c(Y.props.triggerTarget||e).some((function(t){return C(t,n)}))){if(T.isTouch)return;if(Y.state.isVisible&&Y.props.trigger.indexOf("click")>=0)return}else at("onClickOutside",[Y,t]);!0===Y.props.hideOnClick&&(Y.clearDelayTimeouts(),Y.hide(),I=!0,setTimeout((function(){I=!1})),Y.state.isMounted||vt())}}}function ft(){S=!0}function lt(){S=!1}function dt(){var t=nt();t.addEventListener("mousedown",ct,!0),t.addEventListener("touchend",ct,r),t.addEventListener("touchstart",lt,r),t.addEventListener("touchmove",ft,r)}function vt(){var t=nt();t.removeEventListener("mousedown",ct,!0),t.removeEventListener("touchend",ct,r),t.removeEventListener("touchstart",lt,r),t.removeEventListener("touchmove",ft,r)}function mt(t,e){var n=rt().box;function r(t){t.target===n&&(O(n,"remove",r),e())}if(0===t)return e();O(n,"remove",A),O(n,"add",r),A=r}function gt(t,n,r){void 0===r&&(r=!1),c(Y.props.triggerTarget||e).forEach((function(e){e.addEventListener(t,n,r),z.push({node:e,eventType:t,handler:n,options:r})}))}function ht(){var t;Z()&&(gt("touchstart",yt,{passive:!0}),gt("touchend",xt,{passive:!0})),(t=Y.props.trigger,t.split(/\s+/).filter(Boolean)).forEach((function(t){if("manual"!==t)switch(gt(t,yt),t){case"mouseenter":gt("mouseleave",xt);break;case"focus":gt(n?"focusout":"blur",Et);break;case"focusin":gt("focusout",Et)}}))}function bt(){z.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),z=[]}function yt(t){var e,n=!1;if(Y.state.isEnabled&&!Ot(t)&&!I){var r="focus"===(null==(e=y)?void 0:e.type);y=t,D=t.currentTarget,ut(),!Y.state.isVisible&&h(t)&&U.forEach((function(e){return e(t)})),"click"===t.type&&(Y.props.trigger.indexOf("mouseenter")<0||V)&&!1!==Y.props.hideOnClick&&Y.state.isVisible?n=!0:Lt(t),"click"===t.type&&(V=!n),n&&!r&&Dt(t)}}function wt(t){var e=t.target,n=et().contains(e)||$.contains(e);"mousemove"===t.type&&n||function(t,e){var n=e.clientX,r=e.clientY;return t.every((function(t){var e=t.popperRect,o=t.popperState,i=t.props.interactiveBorder,a=l(o.placement),s=o.modifiersData.offset;if(!s)return!0;var u="bottom"===a?s.top.y:0,p="top"===a?s.bottom.y:0,c="right"===a?s.left.x:0,f="left"===a?s.right.x:0,d=e.top-r+u>i,v=r-e.bottom-p>i,m=e.left-n+c>i,g=n-e.right-f>i;return d||v||m||g}))}(At().concat($).map((function(t){var e,n=null==(e=t._tippy.popperInstance)?void 0:e.state;return n?{popperRect:t.getBoundingClientRect(),popperState:n,props:P}:null})).filter(Boolean),t)&&(pt(),Dt(t))}function xt(t){Ot(t)||Y.props.trigger.indexOf("click")>=0&&V||(Y.props.interactive?Y.hideWithInteractivity(t):Dt(t))}function Et(t){Y.props.trigger.indexOf("focusin")<0&&t.target!==et()||Y.props.interactive&&t.relatedTarget&&$.contains(t.relatedTarget)||Dt(t)}function Ot(t){return!!T.isTouch&&Z()!==t.type.indexOf("touch")>=0}function Ct(){Tt();var n=Y.props,r=n.popperOptions,o=n.placement,i=n.offset,a=n.getReferenceClientRect,s=n.moveTransition,u=tt()?B($).arrow:null,p=a?{getBoundingClientRect:a,contextElement:a.contextElement||et()}:e,c=[{name:"offset",options:{offset:i}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!s}},{name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(t){var e=t.state;if(tt()){var n=rt().box;["placement","reference-hidden","escaped"].forEach((function(t){"placement"===t?n.setAttribute("data-placement",e.placement):e.attributes.popper["data-popper-"+t]?n.setAttribute("data-"+t,""):n.removeAttribute("data-"+t)})),e.attributes.popper={}}}}];tt()&&u&&c.push({name:"arrow",options:{element:u,padding:3}}),c.push.apply(c,(null==r?void 0:r.modifiers)||[]),Y.popperInstance=t.createPopper(p,$,Object.assign({},r,{placement:o,onFirstUpdate:L,modifiers:c}))}function Tt(){Y.popperInstance&&(Y.popperInstance.destroy(),Y.popperInstance=null)}function At(){return d($.querySelectorAll("[data-tippy-root]"))}function Lt(t){Y.clearDelayTimeouts(),t&&at("onTrigger",[Y,t]),dt();var e=ot(!0),n=Q(),r=n[0],o=n[1];T.isTouch&&"hold"===r&&o&&(e=o),e?p=setTimeout((function(){Y.show()}),e):Y.show()}function Dt(t){if(Y.clearDelayTimeouts(),at("onUntrigger",[Y,t]),Y.state.isVisible){if(!(Y.props.trigger.indexOf("mouseenter")>=0&&Y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(t.type)>=0&&V)){var e=ot(!1);e?g=setTimeout((function(){Y.state.isVisible&&Y.hide()}),e):b=requestAnimationFrame((function(){Y.hide()}))}}else vt()}}function F(t,e){void 0===e&&(e={});var n=R.plugins.concat(e.plugins||[]);document.addEventListener("touchstart",L,r),window.addEventListener("blur",k);var o=Object.assign({},e,{plugins:n}),i=y(t).reduce((function(t,e){var n=e&&z(e,o);return n&&t.push(n),t}),[]);return g(t)?i[0]:i}F.defaultProps=R,F.setDefaultProps=function(t){Object.keys(t).forEach((function(e){R[e]=t[e]}))},F.currentInput=T;var W=Object.assign({},t.applyStyles,{effect:function(t){var e=t.state,n={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(e.elements.popper.style,n.popper),e.styles=n,e.elements.arrow&&Object.assign(e.elements.arrow.style,n.arrow)}}),X={mouseover:"mouseenter",focusin:"focus",click:"click"};var Y={name:"animateFill",defaultValue:!1,fn:function(t){var e;if(null==(e=t.props.render)||!e.$$tippy)return{};var n=B(t.popper),r=n.box,o=n.content,i=t.props.animateFill?function(){var t=m();return t.className="tippy-backdrop",x([t],"hidden"),t}():null;return{onCreate:function(){i&&(r.insertBefore(i,r.firstElementChild),r.setAttribute("data-animatefill",""),r.style.overflow="hidden",t.setProps({arrow:!1,animation:"shift-away"}))},onMount:function(){if(i){var t=r.style.transitionDuration,e=Number(t.replace("ms",""));o.style.transitionDelay=Math.round(e/10)+"ms",i.style.transitionDuration=t,x([i],"visible")}},onShow:function(){i&&(i.style.transitionDuration="0ms")},onHide:function(){i&&x([i],"hidden")}}}};var q={clientX:0,clientY:0},$=[];function J(t){var e=t.clientX,n=t.clientY;q={clientX:e,clientY:n}}var G={name:"followCursor",defaultValue:!1,fn:function(t){var e=t.reference,n=E(t.props.triggerTarget||e),r=!1,o=!1,i=!0,a=t.props;function s(){return"initial"===t.props.followCursor&&t.state.isVisible}function u(){n.addEventListener("mousemove",f)}function p(){n.removeEventListener("mousemove",f)}function c(){r=!0,t.setProps({getReferenceClientRect:null}),r=!1}function f(n){var r=!n.target||e.contains(n.target),o=t.props.followCursor,i=n.clientX,a=n.clientY,s=e.getBoundingClientRect(),u=i-s.left,p=a-s.top;!r&&t.props.interactive||t.setProps({getReferenceClientRect:function(){var t=e.getBoundingClientRect(),n=i,r=a;"initial"===o&&(n=t.left+u,r=t.top+p);var s="horizontal"===o?t.top:r,c="vertical"===o?t.right:n,f="horizontal"===o?t.bottom:r,l="vertical"===o?t.left:n;return{width:c-l,height:f-s,top:s,right:c,bottom:f,left:l}}})}function l(){t.props.followCursor&&($.push({instance:t,doc:n}),function(t){t.addEventListener("mousemove",J)}(n))}function d(){0===($=$.filter((function(e){return e.instance!==t}))).filter((function(t){return t.doc===n})).length&&function(t){t.removeEventListener("mousemove",J)}(n)}return{onCreate:l,onDestroy:d,onBeforeUpdate:function(){a=t.props},onAfterUpdate:function(e,n){var i=n.followCursor;r||void 0!==i&&a.followCursor!==i&&(d(),i?(l(),!t.state.isMounted||o||s()||u()):(p(),c()))},onMount:function(){t.props.followCursor&&!o&&(i&&(f(q),i=!1),s()||u())},onTrigger:function(t,e){h(e)&&(q={clientX:e.clientX,clientY:e.clientY}),o="focus"===e.type},onHidden:function(){t.props.followCursor&&(c(),p(),i=!0)}}}};var K={name:"inlinePositioning",defaultValue:!1,fn:function(t){var e,n=t.reference;var r=-1,o=!1,i=[],a={name:"tippyInlinePositioning",enabled:!0,phase:"afterWrite",fn:function(o){var a=o.state;t.props.inlinePositioning&&(-1!==i.indexOf(a.placement)&&(i=[]),e!==a.placement&&-1===i.indexOf(a.placement)&&(i.push(a.placement),t.setProps({getReferenceClientRect:function(){return function(t){return function(t,e,n,r){if(n.length<2||null===t)return e;if(2===n.length&&r>=0&&n[0].left>n[1].right)return n[r]||e;switch(t){case"top":case"bottom":var o=n[0],i=n[n.length-1],a="top"===t,s=o.top,u=i.bottom,p=a?o.left:i.left,c=a?o.right:i.right;return{top:s,bottom:u,left:p,right:c,width:c-p,height:u-s};case"left":case"right":var f=Math.min.apply(Math,n.map((function(t){return t.left}))),l=Math.max.apply(Math,n.map((function(t){return t.right}))),d=n.filter((function(e){return"left"===t?e.left===f:e.right===l})),v=d[0].top,m=d[d.length-1].bottom;return{top:v,bottom:m,left:f,right:l,width:l-f,height:m-v};default:return e}}(l(t),n.getBoundingClientRect(),d(n.getClientRects()),r)}(a.placement)}})),e=a.placement)}};function s(){var e;o||(e=function(t,e){var n;return{popperOptions:Object.assign({},t.popperOptions,{modifiers:[].concat(((null==(n=t.popperOptions)?void 0:n.modifiers)||[]).filter((function(t){return t.name!==e.name})),[e])})}}(t.props,a),o=!0,t.setProps(e),o=!1)}return{onCreate:s,onAfterUpdate:s,onTrigger:function(e,n){if(h(n)){var o=d(t.reference.getClientRects()),i=o.find((function(t){return t.left-2<=n.clientX&&t.right+2>=n.clientX&&t.top-2<=n.clientY&&t.bottom+2>=n.clientY})),a=o.indexOf(i);r=a>-1?a:r}},onHidden:function(){r=-1}}}};var Q={name:"sticky",defaultValue:!1,fn:function(t){var e=t.reference,n=t.popper;function r(e){return!0===t.props.sticky||t.props.sticky===e}var o=null,i=null;function a(){var s=r("reference")?(t.popperInstance?t.popperInstance.state.elements.reference:e).getBoundingClientRect():null,u=r("popper")?n.getBoundingClientRect():null;(s&&Z(o,s)||u&&Z(i,u))&&t.popperInstance&&t.popperInstance.update(),o=s,i=u,t.state.isMounted&&requestAnimationFrame(a)}return{onMount:function(){t.props.sticky&&a()}}}};function Z(t,e){return!t||!e||(t.top!==e.top||t.right!==e.right||t.bottom!==e.bottom||t.left!==e.left)}return e&&function(t){var e=document.createElement("style");e.textContent=t,e.setAttribute("data-tippy-stylesheet","");var n=document.head,r=document.querySelector("head>style,head>link");r?n.insertBefore(e,r):n.appendChild(e)}('.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}'),F.setDefaultProps({plugins:[Y,G,K,Q],render:N}),F.createSingleton=function(t,e){var n;void 0===e&&(e={});var r,o=t,i=[],a=[],s=e.overrides,u=[],f=!1;function l(){a=o.map((function(t){return c(t.props.triggerTarget||t.reference)})).reduce((function(t,e){return t.concat(e)}),[])}function d(){i=o.map((function(t){return t.reference}))}function v(t){o.forEach((function(e){t?e.enable():e.disable()}))}function g(t){return o.map((function(e){var n=e.setProps;return e.setProps=function(o){n(o),e.reference===r&&t.setProps(o)},function(){e.setProps=n}}))}function h(t,e){var n=a.indexOf(e);if(e!==r){r=e;var u=(s||[]).concat("content").reduce((function(t,e){return t[e]=o[n].props[e],t}),{});t.setProps(Object.assign({},u,{getReferenceClientRect:"function"==typeof u.getReferenceClientRect?u.getReferenceClientRect:function(){var t;return null==(t=i[n])?void 0:t.getBoundingClientRect()}}))}}v(!1),d(),l();var b={fn:function(){return{onDestroy:function(){v(!0)},onHidden:function(){r=null},onClickOutside:function(t){t.props.showOnCreate&&!f&&(f=!0,r=null)},onShow:function(t){t.props.showOnCreate&&!f&&(f=!0,h(t,i[0]))},onTrigger:function(t,e){h(t,e.currentTarget)}}}},y=F(m(),Object.assign({},p(e,["overrides"]),{plugins:[b].concat(e.plugins||[]),triggerTarget:a,popperOptions:Object.assign({},e.popperOptions,{modifiers:[].concat((null==(n=e.popperOptions)?void 0:n.modifiers)||[],[W])})})),w=y.show;y.show=function(t){if(w(),!r&&null==t)return h(y,i[0]);if(!r||null!=t){if("number"==typeof t)return i[t]&&h(y,i[t]);if(o.indexOf(t)>=0){var e=t.reference;return h(y,e)}return i.indexOf(t)>=0?h(y,t):void 0}},y.showNext=function(){var t=i[0];if(!r)return y.show(0);var e=i.indexOf(r);y.show(i[e+1]||t)},y.showPrevious=function(){var t=i[i.length-1];if(!r)return y.show(t);var e=i.indexOf(r),n=i[e-1]||t;y.show(n)};var x=y.setProps;return y.setProps=function(t){s=t.overrides||s,x(t)},y.setInstances=function(t){v(!0),u.forEach((function(t){return t()})),o=t,v(!1),d(),l(),u=g(y),y.setProps({triggerTarget:a})},u=g(y),y},F.delegate=function(t,e){var n=[],o=[],i=!1,a=e.target,s=p(e,["target"]),u=Object.assign({},s,{trigger:"manual",touch:!1}),f=Object.assign({touch:R.touch},s,{showOnCreate:!0}),l=F(t,u);function d(t){if(t.target&&!i){var n=t.target.closest(a);if(n){var r=n.getAttribute("data-tippy-trigger")||e.trigger||R.trigger;if(!n._tippy&&!("touchstart"===t.type&&"boolean"==typeof f.touch||"touchstart"!==t.type&&r.indexOf(X[t.type])<0)){var s=F(n,f);s&&(o=o.concat(s))}}}}function v(t,e,r,o){void 0===o&&(o=!1),t.addEventListener(e,r,o),n.push({node:t,eventType:e,handler:r,options:o})}return c(l).forEach((function(t){var e=t.destroy,a=t.enable,s=t.disable;t.destroy=function(t){void 0===t&&(t=!0),t&&o.forEach((function(t){t.destroy()})),o=[],n.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),n=[],e()},t.enable=function(){a(),o.forEach((function(t){return t.enable()})),i=!1},t.disable=function(){s(),o.forEach((function(t){return t.disable()})),i=!0},function(t){var e=t.reference;v(e,"touchstart",d,r),v(e,"mouseover",d),v(e,"focusin",d),v(e,"click",d)}(t)})),l},F.hideAll=function(t){var e=void 0===t?{}:t,n=e.exclude,r=e.duration;_.forEach((function(t){var e=!1;if(n&&(e=b(n)?t.reference===n:t.popper===n.popper),!e){var o=t.props.duration;t.setProps({duration:r}),t.hide(),t.state.isDestroyed||t.setProps({duration:o})}}))},F.roundArrow='<svg width="16" height="6" xmlns="http://www.w3.org/2000/svg"><path d="M0 6s1.796-.013 4.67-3.615C5.851.9 6.93.006 8 0c1.07-.006 2.148.887 3.343 2.385C14.233 6.005 16 6 16 6H0z"></svg>',F}));
//# sourceMappingURL=tippy-bundle.umd.min.js.map
| 25,717 | Python | .py | 2 | 12,857.5 | 25,667 | 0.698619 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,294 | features.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/wagtail_hooks/features.py | from typing import Any
from wagtail import hooks
from django.urls import reverse_lazy
from ..hooks import (
REGISTER_HOOK_NAME,
BUILD_CONFIG_HOOK,
)
from ..registry import (
EditorJSFeature,
EditorJSFeatures,
EditorJSJavascriptFeature,
)
from ..features import (
AttachesFeature,
BlockQuoteFeature,
CheckListFeature,
CodeFeature,
DelimiterFeature,
WarningFeature,
HeaderFeature,
HTMLFeature,
ImageFeature,
ImageRowFeature,
ButtonFeature,
TooltipFeature,
LinkFeature,
LinkAutoCompleteFeature,
DocumentFeature,
NestedListFeature,
TableFeature,
AlignmentBlockTune,
TextVariantTune,
BackgroundColorTune,
ColorTune,
)
@hooks.register(BUILD_CONFIG_HOOK)
def build_editorjs_config(widget, context, config):
config["minHeight"] = 150
@hooks.register(REGISTER_HOOK_NAME)
def register_editor_js_features(registry: EditorJSFeatures):
registry.register(
"attaches",
AttachesFeature(
"attaches",
),
)
registry.register(
"checklist",
CheckListFeature(
"checklist",
inlineToolbar = True,
),
)
registry.register(
"code",
CodeFeature(
"code",
inlineToolbar = True,
),
)
registry.register(
"delimiter",
DelimiterFeature(
"delimiter",
inlineToolbar = True,
),
)
registry.register(
"header",
HeaderFeature(
"header",
inlineToolbar = True,
),
)
registry.register(
"inline-code",
EditorJSFeature(
"inline-code",
"InlineCode",
js = [
"wagtail_editorjs/vendor/editorjs/tools/inline-code.js",
],
inlineToolbar = True,
),
)
registry.register(
"marker",
EditorJSFeature(
"marker",
"Marker",
js = [
"wagtail_editorjs/vendor/editorjs/tools/marker.js",
],
inlineToolbar = True,
allowed_tags=["mark"],
),
)
registry.register(
"nested-list",
NestedListFeature(
"nested-list",
inlineToolbar = True,
),
)
registry.register(
"paragraph",
EditorJSFeature(
"paragraph",
"Paragraph",
js = [
"wagtail_editorjs/vendor/editorjs/tools/paragraph.umd.js",
],
inlineToolbar = True,
allowed_tags=["p"],
),
)
registry.register(
"quote",
BlockQuoteFeature(
"quote",
inlineToolbar = True,
),
)
registry.register(
"raw",
HTMLFeature(
"raw",
inlineToolbar = True,
),
)
registry.register(
"table",
TableFeature(
"table",
inlineToolbar = True,
),
)
registry.register(
"underline",
EditorJSFeature(
"underline",
"Underline",
js = [
"wagtail_editorjs/vendor/editorjs/tools/underline.js",
],
inlineToolbar = True,
),
)
registry.register(
"warning",
WarningFeature(
"warning",
inlineToolbar = True,
),
)
registry.register(
"link-autocomplete",
LinkAutoCompleteFeature(
"link-autocomplete",
),
)
# Wagtail specific
registry.register(
"button",
ButtonFeature(
"button",
)
)
registry.register(
"tooltip",
TooltipFeature(
"tooltip",
),
)
registry.register(
"link",
LinkFeature(
"link",
inlineToolbar = True,
),
)
registry.register(
"image",
ImageFeature(
"image",
),
)
registry.register(
"images",
ImageRowFeature(
"images",
),
)
registry.register(
"document",
DocumentFeature(
"document",
config={},
inlineToolbar = True,
),
)
# Tunes
registry.register(
"text-alignment-tune",
AlignmentBlockTune(
"text-alignment-tune",
inlineToolbar = True,
config={
"default": "left",
},
),
)
registry.register(
"text-variant-tune",
TextVariantTune(
"text-variant-tune",
inlineToolbar = True,
),
)
registry.register(
"background-color-tune",
BackgroundColorTune(
"background-color-tune",
config={
"defaultStretched": True,
}
),
)
registry.register(
"text-color-tune",
ColorTune(
"text-color-tune",
),
)
# Register initializers
registry.register(
"undo-redo",
EditorJSJavascriptFeature(
"undo-redo",
js = [
"wagtail_editorjs/vendor/editorjs/tools/undo-redo.js",
"wagtail_editorjs/js/init/undo-redo.js",
],
weight=0,
),
)
registry.register(
"drag-drop",
EditorJSJavascriptFeature(
"drag-drop",
js = [
"wagtail_editorjs/vendor/editorjs/tools/drag-drop.js",
"wagtail_editorjs/js/init/drag-drop.js",
],
weight=1,
),
)
# Add tunes
registry.register_tune("text-alignment-tune")
registry.register_tune("text-variant-tune")
registry.register_tune("background-color-tune")
registry.register_tune("text-color-tune")
#
# from django.contrib.auth import get_user_model
# from wagtail.snippets.widgets import AdminSnippetChooser
# from wagtail_editorjs.hooks import REGISTER_HOOK_NAME
# from wagtail_editorjs.registry import (
# EditorJSFeatures,
# ModelInlineEditorJSFeature,
# )
#
#
# class InlineUserChooserFeature(ModelInlineEditorJSFeature):
# model = get_user_model()
# chooser_class = AdminSnippetChooser
# must_have_attrs = {
# "data-email": None,
# }
#
# @classmethod
# def get_url(cls, instance):
# return f"mailto:{instance.email}"
#
# @classmethod
# def get_full_url(cls, instance, request):
# return cls.get_url(instance)
#
#
# @hooks.register(REGISTER_HOOK_NAME)
# def register_editor_js_features(registry: EditorJSFeatures):
# registry.register(
# "inline-user",
# InlineUserChooserFeature(
# "inline-user",
# "InlineUserTool",
# js=[
# "wagtail_editorjs/js/tools/inline-user.js",
# ],
# config={},
# ),
# )
# | 7,047 | Python | .py | 302 | 15.582781 | 74 | 0.536662 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,295 | urls.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/wagtail_hooks/urls.py | from django.urls import path, include
from wagtail import hooks
@hooks.register("register_admin_urls")
def register_admin_urls():
urls = []
# Make sure all features are properly registered.
from ..registry import EDITOR_JS_FEATURES
EDITOR_JS_FEATURES._look_for_features()
for hook in hooks.get_hooks("register_editorjs_urls"):
urls += hook()
return [
path(
'wagtail-editorjs/',
name='wagtail_editorjs',
view=include(
(urls, 'wagtail_editorjs'),
namespace='wagtail_editorjs'
),
),
]
| 620 | Python | .py | 20 | 23.1 | 58 | 0.606061 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,296 | __init__.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/wagtail_hooks/__init__.py | from .features import *
from .urls import *
from .wagtail_fedit import * | 72 | Python | .py | 3 | 23.333333 | 28 | 0.771429 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,297 | wagtail_fedit.py | Nigel2392_wagtail_editorjs/wagtail_editorjs/wagtail_hooks/wagtail_fedit.py | from wagtail_editorjs.render import render_editorjs_html
from wagtail_editorjs.registry import EditorJSValue
from wagtail_editorjs.fields import EditorJSField
from wagtail import hooks
@hooks.register("wagtail_fedit.register_type_renderer")
def register_renderers(renderer_map):
# This is a custom renderer for RichText fields.
# It will render the RichText field as a RichText block.
renderer_map[EditorJSValue] = lambda request, context, instance, value: render_editorjs_html(
value.features,
value,
context=context,
)
@hooks.register("wagtail_fedit.field_editor_size")
def field_editor_size(model_instance, model_field):
if isinstance(model_field, EditorJSField):
return "full"
return None
| 754 | Python | .py | 18 | 37.5 | 97 | 0.76881 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,298 | editorjs_tunes_example.py | Nigel2392_wagtail_editorjs/docs/examples/editorjs_tunes_example.py | from typing import Any
from django import forms
from wagtail_editorjs.hooks import REGISTER_HOOK_NAME
from wagtail_editorjs.registry import EditorJSFeatures, EditorJSTune, EditorJSElement
from wagtail import hooks
class AlignmentBlockTune(EditorJSTune):
allowed_attributes = {"*": ["class"]}
klass = "AlignmentBlockTune"
js = ["https://cdn.jsdelivr.net/npm/editorjs-text-alignment-blocktune@latest"]
def validate(self, data: Any):
super().validate(data)
alignment = data.get("alignment")
if alignment not in ["left", "center", "right"]:
raise forms.ValidationError("Invalid alignment value")
def tune_element(self, element: EditorJSElement, tune_value: Any, context=None) -> EditorJSElement:
element = super().tune_element(element, tune_value, context=context)
element.add_attributes(class_=f"align-content-{tune_value['alignment'].strip()}")
return element
@hooks.register(REGISTER_HOOK_NAME)
def register_editor_js_features(registry: EditorJSFeatures):
registry.register(
"text-alignment-tune",
AlignmentBlockTune(
"text-alignment-tune",
inlineToolbar=True,
config={
"default": "left",
},
),
)
# To apply globally to all features
registry.register_tune("text-alignment-tune")
# Or optionally for a specific feature remove the wildcard above
# and use the following (given the features "header" and "paragraph" are used in the editor)
# registry.register_tune("text-alignment-tune", "header")
# registry.register_tune("text-alignment-tune", "paragraph")
| 1,678 | Python | .py | 36 | 39.416667 | 103 | 0.697344 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
2,288,299 | editorjs_feature_example.py | Nigel2392_wagtail_editorjs/docs/examples/editorjs_feature_example.py |
from typing import Any
from django import forms
from wagtail_editorjs.hooks import REGISTER_HOOK_NAME
from wagtail_editorjs.registry import (
EditorJSFeature, EditorJSFeatures,
EditorJSElement, EditorJSBlock,
)
from wagtail import hooks
class CustomImageFeature(EditorJSFeature):
# These tags are allowed and will not be cleaned by bleach if enabled.
allowed_tags = ["img"]
allowed_attributes = ["src", "alt", "style"]
# Provide extra configuration for the feature.
def get_config(self, context: dict[str, Any]):
# This context is always present.
# It is the widget context - NOT the request context.
config = super().get_config() or {}
config["config"] = {} # my custom configuration
return config
def validate(self, data: Any):
super().validate(data)
if 'url' not in data['data']:
raise forms.ValidationError('Invalid data.url value')
if "caption" not in data["data"]:
raise forms.ValidationError('Invalid data.caption value')
# ...
def render_block_data(self, block: EditorJSBlock, context = None) -> EditorJSElement:
# Context is not guaranteed to be present. This is the request context.
return EditorJSElement(
"img",
close_tag=False,
attrs={
"src": block["data"]["url"],
"alt": block["data"]["caption"],
"style": {
"border": "1px solid black" if block["data"]["withBorder"] else "none",
"background-color": "lightgray" if block["data"]["withBackground"] else "none",
"width": "100%" if block["data"]["stretched"] else "auto",
}
},
)
@hooks.register(REGISTER_HOOK_NAME)
def register_editorjs_features(features: EditorJSFeatures):
# The feature name as you'd like to use in your field/block.
feature_name = "simple-image"
# The classname as defined in javascript.
# This is accessed with `window.[feature_js_class]`.
# In this case; `window.SimpleImage`.
feature_js_class = "SimpleImage"
# Register the feature with the editor.
features.register(
feature_name,
CustomImageFeature(
feature_name,
feature_js_class,
js = [
# Import from CDN
"https://cdn.jsdelivr.net/npm/@editorjs/simple-image",
],
),
)
| 2,512 | Python | .py | 61 | 31.885246 | 99 | 0.613759 | Nigel2392/wagtail_editorjs | 8 | 0 | 3 | GPL-2.0 | 9/5/2024, 10:48:26 PM (Europe/Amsterdam) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.