Skip to content

Instantly share code, notes, and snippets.

@johndhancock
Forked from hjhilden/ai2html2react.py
Created June 20, 2024 18:45
Show Gist options
  • Save johndhancock/e94fe4888624af858d6a690fb77f3829 to your computer and use it in GitHub Desktop.
Save johndhancock/e94fe4888624af858d6a690fb77f3829 to your computer and use it in GitHub Desktop.
Prototype command line script to convert ai2html output to valid React
import sys
import os
import re
dir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
static_content_folder = 'static/custom/ai2html-output/'
# script takes two arguments "input" and "output" and optional static content folder arg
# .js extension is added to output
# check if there are any arguments, else exit.
if len(sys.argv)>1:
# ignore script name
args = sys.argv[1:]
for arg in args:
print(arg)
print(dir_path)
INPUT = args[0]
OUTPUT = args[1]
# if we pass a folder argument
try:
static_content_folder = args[2]
except:
pass
# start and end strings
react_start = "// converted from " + INPUT + "\n\n\nimport React from 'react'\nexport default ({ props }) => (\n\n <div className='container'>\n\n"
react_end = "\n </div>\n )"
# here we put replacements:
# 0-1 comments,
# 2-3 style def
# 4 className
replacements = [
('<!--','{/*'),
('-->','*/}'),
("<style type='text/css' media='screen,print'>"
, "<style jsx type='text/css' media='screen,print'>{`"),
("</style>", "`}</style>"),
('class=', 'className=')]
text = open(dir_path + INPUT).read()
text_new = text
for r in replacements:
text_new = text_new.replace(*r)
# split string into two parts, style defs and contents
parts = re.split('(</style>)', text_new)
style_defs = parts[0] + parts[1]
divs = parts[2]
# quote inline style defs
divs = re.sub('(?<=style\=)"([a-z\,0-9\s\-\.%\(\):;]+)"', '{{\g<1>}}', divs )
divs = re.sub('(?<=:)([a-z\,0-9\s\-\.%\(\)]+);', '"\g<1>", ', divs)
divs = re.sub('\s-(\w)',' \g<1>' , divs)
callback = lambda pat: pat.group(1).upper()
divs = re.sub('-(\w)(?=[\w\-]+:)',callback , divs)
divs = re.sub('src="', 'src="'+ static_content_folder, divs )
content = react_start + style_defs + divs +react_end
print(content)
f= open(dir_path + args[1] +'.js',"w+")
f.write(content)
f.close()
else: print("please provide names of input and output files: ai2html2react.py -input -output")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment