diff --git a/html-to-j2html/.gitignore b/html-to-j2html/.gitignore new file mode 100644 index 00000000..70c9a9e4 --- /dev/null +++ b/html-to-j2html/.gitignore @@ -0,0 +1,44 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +kotlin-js-store/ \ No newline at end of file diff --git a/html-to-j2html/build.gradle.kts b/html-to-j2html/build.gradle.kts new file mode 100644 index 00000000..9bcdb6fa --- /dev/null +++ b/html-to-j2html/build.gradle.kts @@ -0,0 +1,84 @@ +plugins { + kotlin("multiplatform") version "1.9.22" + application +} + +group = "com.j2html" +version = "1.6.1-SNAPSHOT" + +repositories { + mavenCentral() + maven("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven") +} + +kotlin { + jvm { + jvmToolchain(17) + withJava() + testRuns.named("test") { + executionTask.configure { + useJUnitPlatform() + } + } + } + js { + binaries.executable() + browser { + commonWebpackConfig { + cssSupport { + enabled.set(true) + } + } + webpackTask { + output.libraryTarget = "umd" + } + } + } + sourceSets { + val commonMain by getting { + dependencies { + implementation("org.jetbrains.kotlin:kotlin-stdlib") + implementation("com.mohamedrejeb.ksoup:ksoup-html:0.3.1") + } + } + val commonTest by getting { + dependencies { + implementation(kotlin("test")) + } + } + val jvmMain by getting { + dependencies { + implementation("io.ktor:ktor-server-netty:2.3.2") + implementation("io.ktor:ktor-server-html-builder-jvm:2.3.2") + implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:0.7.2") + implementation("org.slf4j:slf4j-api:1.6.1") + implementation("org.slf4j:slf4j-simple:1.6.1") + } + } + val jvmTest by getting + val jsMain by getting { + dependencies { + implementation(kotlin("stdlib-js")) + implementation("com.mohamedrejeb.ksoup:ksoup-html:0.3.1") + //implementation("org.jetbrains.kotlin-wrappers:kotlin-react:18.2.0-pre.346") + //implementation("org.jetbrains.kotlin-wrappers:kotlin-react-dom:18.2.0-pre.346") + //implementation("org.jetbrains.kotlin-wrappers:kotlin-emotion:11.9.3-pre.346") + } + } + val jsTest by getting + } +} + +application { + mainClass.set("com.html.to.j2html.jvm.JvmMainKt") +} + +tasks.named("jvmProcessResources") { + val jsBrowserDistribution = tasks.named("jsBrowserDistribution") + from(jsBrowserDistribution) +} + +tasks.named("run") { + dependsOn(tasks.named("jvmJar")) + classpath(tasks.named("jvmJar")) +} diff --git a/html-to-j2html/gradle.properties b/html-to-j2html/gradle.properties new file mode 100644 index 00000000..9dcc3a76 --- /dev/null +++ b/html-to-j2html/gradle.properties @@ -0,0 +1,2 @@ +kotlin.code.style=official +kotlin.js.compiler=ir diff --git a/html-to-j2html/gradle/wrapper/gradle-wrapper.jar b/html-to-j2html/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/html-to-j2html/gradle/wrapper/gradle-wrapper.jar differ diff --git a/html-to-j2html/gradle/wrapper/gradle-wrapper.properties b/html-to-j2html/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..8f5ef1a1 --- /dev/null +++ b/html-to-j2html/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists \ No newline at end of file diff --git a/html-to-j2html/gradlew b/html-to-j2html/gradlew new file mode 100644 index 00000000..1b6c7873 --- /dev/null +++ b/html-to-j2html/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/html-to-j2html/gradlew.bat b/html-to-j2html/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/html-to-j2html/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/html-to-j2html/index.html b/html-to-j2html/index.html new file mode 100644 index 00000000..948759eb --- /dev/null +++ b/html-to-j2html/index.html @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + HTML to J2HTML converter + + +
+ + + +

HTML to J2HTML converter

+ + + + +
+
+

J2HTML code :

+
+
+
+
+
+
+ +
+
+
+ + + +
+ + diff --git a/html-to-j2html/settings.gradle.kts b/html-to-j2html/settings.gradle.kts new file mode 100644 index 00000000..d97ad3ff --- /dev/null +++ b/html-to-j2html/settings.gradle.kts @@ -0,0 +1,12 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0" +} + +rootProject.name = "html-to-j2html" \ No newline at end of file diff --git a/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/SupportedJ2HtmlAttributes.kt b/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/SupportedJ2HtmlAttributes.kt new file mode 100644 index 00000000..8997bb84 --- /dev/null +++ b/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/SupportedJ2HtmlAttributes.kt @@ -0,0 +1,227 @@ +package com.html.to.j2html.common +/** + * attributes that require specific treatment + */ +fun specialAttributes() = listOf ( + "class", // withClasses(val1, val2, val3) for each space separated token // DONE + "data-*", // the * is the key and the value is the value, and becomes .withData("key", "value") // DONE + +) + +/** + * we produce raw html for these + */ +val unsupportedTags : List = listOf( + "svg", + "path", +) + +/** + * Not much to do with those, just taking them out of the supported list without losing track of them + * + * we default to attr("key", "value") for those + * + */ +val unsupportedAttributes : List = listOf( + "accept-charset", // valid html5 + "http-equiv", // valid html5 + "inputmode", // valid html5 + "popovertarget", // valid html5 + "popovertargetaction", // valid html5 + "inert", // valid html5 + "enterkeyhint", // valid html5 + "onblur", // valid html5 + "onchange", // valid html5 + "onclick", // valid html5 + "oncontextmenu", // valid html5 + "oncopy", // valid html5 + "oncut", // valid html5 + "ondblclick", // valid html5 + "ondrag", // valid html5 + "ondragend", // valid html5 + "ondragenter", // valid html5 + "ondragleave", // valid html5 + "ondragover", // valid html5 + "ondragstart", // valid html5 + "ondrop", // valid html5 + "onfocus", // valid html5 + "oninput", // valid html5 + "oninvalid", // valid html5 + "onkeydown", // valid html5 + "onkeypress", // valid html5 + "onkeyup", // valid html5 + "onmousedown", // valid html5 + "onmousemove", // valid html5 + "onmouseout", // valid html5 + "onmouseover", // valid html5 + "onmouseup", // valid html5 + "onmousewheel", // valid html5 + "onpaste", // valid html5 + "onscroll", // valid html5 + "onselect", // valid html5 + "onwheel", // valid html5 + "popover", // valid html5 + +) + +/** + * we default to attr("key", "value") for those + * + */ +val buggedAttributes : List = listOf( + "autocomplete", // input().withCondAutocomplete(true) but mozilla docs say it's not just a boolean: valid values are "off", "on", "name", "email", etc + "onvolumechange", // audio().withOnvolumechanged("value") exists instead of withOnvolumechange +) + +/** + * list of HTML integer attributes + * + * these have been tested to exist in j2html with the associated comment code + */ +val knownIntegerHtmlAttributes : List = listOf( + "tabindex", // div().withTabindex(5) // tabindex +) + +/** + * list of HTML boolean attributes copied on 28-02-2024 from + * https://meiert.com/en/blog/boolean-attributes-of-html/ + * with a few that I found myself during tests, and a few taken out because unsupported + * + * these have been tested to exist in j2html with the associated comment code + */ +val knownBooleanHtmlAttributes : List = listOf( + "async", // script().withCondAsync(true), // async + "autofocus", // input().withCondAutofocus(true), // autofocus + "autoplay", // video().withCondAutoplay(true), // autoplay + "checked", // input().withCondChecked(true), // checked + "controls", // audio().withCondControls(true), // controls + "default", // track().withCondDefault(true), // default + "defer", // script().withCondDefer(true), // defer + "disabled", // input().withCondDisabled(true), // disabled + "ismap", // img().withCondIsmap(true), // ismap + "loop", // audio().withCondLoop(true), // loop + "multiple", // select().withCondMultiple(true), // multiple + "muted", // video().withCondMuted(true), // muted + "novalidate", // form().withCondNovalidate(true), // novalidate + "open", // details().withCondOpen(true), // open + "readonly", // input().withCondReadonly(true), // readonly + "required", // select().withCondRequired(true), // required + "reversed", // ol().withCondReversed(true), // reversed + "selected", // option().withCondSelected(true), // selected + // boolean attributes I found during tests: + "contenteditable", // div().withCondContenteditable(true) // contenteditable + "download", // area().withCondDownload(true), // download + "draggable", // img().withCondDraggable(true), // draggable + "hidden", // img().withCondHidden(true), // hidden + "sandbox", // iframe().withCondSandbox(true), // sandbox + "spellcheck", // input().withCondSpellcheck(true), // spellcheck + "translate", // input().withCondTranslate(true), // translate +) + + +/** + * these have been tested to exist in j2html with the associated comment code + */ +val knownStringHtmlAttributes : List = listOf( + "accept", // input().withAccept("value"), // accept + "accesskey", // div().withAccesskey("value"), // accesskey + "action", // form().withAction("value"), // action + "alt", // input().withAlt("value"), // alt + "charset", // meta().withCharset("value"), // charset + "cite", // del().withCite("value"), // cite + "cols", // textarea().withCols("value"), // cols + "colspan", // td().withColspan("value"), // colspan + "content", // meta().withContent("value"), // content + "coords", // area().withCoords("value"), // coords + "datetime", // time().withDatetime("value"), // datetime + "dir", // div().withDir("value"), // dir + "dirname", // input().withDirname("value"), // dirname + "enctype", // form().withEnctype("value"), // enctype + "for", // label().withFor("value"), // for + "form", // input().withForm("value"), // form + "formaction", // button().withFormaction("value"), // formaction + "headers", // td().withHeaders("value"), // headers + "height", // canvas().withHeight("value"), // height + "high", // meter().withHigh("value"), // high + "href", // a().withHref("value"), // href + "hreflang", // a().withHreflang("value"), // hreflang + "id", // div().withId("value"), // id + "kind", // track().withKind("value"), // kind + "label", // option().withLabel("value"), // label + "lang", // div().withLang("value"), // lang + "list", // input().withList("value"), // list + "low", // meter().withLow("value"), // low + "max", // input().withMax("value"), // max + "maxlength", // input().withMaxlength("value"), // maxlength + "media", // a().withMedia("value"), // media + "method", // form().withMethod("value"), // method + "min", // input().withMin("value"), // min + "name", // input().withName("value"), // name + "optimum", // meter().withOptimum("value"), // optimum + "onabort", // img().withOnabort("value"), // onabort + "onafterprint", // body().withOnafterprint("value"), // onafterprint + "onbeforeprint", // body().withOnbeforeprint("value"), // onbeforeprint + "onbeforeunload", // body().withOnbeforeunload("value"), // onbeforeunload + "oncanplay", // video().withOncanplay("value"), // oncanplay + "oncanplaythrough", // video().withOncanplaythrough("value"), // oncanplaythrough + "oncuechange", // track().withOncuechange("value"), // oncuechange + "ondurationchange", // video().withOndurationchange("value"), // ondurationchange + "onemptied", // video().withOnemptied("value"), // onemptied + "onended", // video().withOnended("value"), // onended + "onerror", // video().withOnerror("value"), // onerror + "onhashchange", // body().withOnhashchange("value"), // onhashchange + "onload", // input().withOnload("value"), // onload + "onloadeddata", // video().withOnloadeddata("value"), // onloadeddata + "onloadedmetadata", // video().withOnloadedmetadata("value"), // onloadedmetadata + "onloadstart", // video().withOnloadstart("value"), // onloadstart + "onoffline", // body().withOnoffline("value"), // onoffline + "ononline", // body().withOnonline("value"), // ononline + "onpagehide", // body().withOnpagehide("value"), // onpagehide + "onpageshow", // body().withOnpageshow("value"), // onpageshow + "onpause", // video().withOnpause("value"), // onpause + "onplay", // video().withOnplay("value"), // onplay + "onplaying", // video().withOnplaying("value"), // onplaying + "onpopstate", // body().withOnpopstate("value"), // onpopstate + "onprogress", // video().withOnprogress("value"), // onprogress + "onratechange", // video().withOnratechange("value"), // onratechange + "onreset", // form().withOnreset("value"), // onreset + "onresize", // body().withOnresize("value"), // onresize + "onsearch", // input().withOnsearch("value"), // onsearch + "onseeked", // video().withOnseeked("value"), // onseeked + "onseeking", // video().withOnseeking("value"), // onseeking + "onstalled", // video().withOnstalled("value"), // onstalled + "onstorage", // body().withOnstorage("value"), // onstorage + "onsubmit", // form().withOnsubmit("value"), // onsubmit + "onsuspend", // video().withOnsuspend("value"), // onsuspend + "ontimeupdate", // video().withOntimeupdate("value"), // ontimeupdate + "ontoggle", // details().withOntoggle("value"), // ontoggle + "onunload", // body().withOnunload("value"), // onunload + "onwaiting", // video().withOnwaiting("value"), // onwaiting + "pattern", // input().withPattern("value"), // pattern + "placeholder", // input().withPlaceholder("value"), // placeholder + "poster", // video().withPoster("value"), // poster + "preload", // video().withPreload("value"), // preload + "rel", // form().withRel("value"), // rel + "rows", // textarea().withRows("value"), // rows + "rowspan", // td().withRowspan("value"), // rowspan + "scope", // th().withScope("value"), // scope + "shape", // area().withShape("value"), // shape + "size", // input().withSize("value"), // size + "sizes", // img().withSizes("value"), // sizes + "span", // col().withSpan("value"), // span + "src", // input().withSrc("value"), // src + "srcdoc", // iframe().withSrcdoc("value"), // srcdoc + "srclang", // track().withSrclang("value"), // srclang + "srcset", // img().withSrcset("value"), // srcset + "start", // ol().withStart("value"), // start + "step", // input().withStep("value"), // step + "style", // div().withStyle("value"), // style + "target", // form().withTarget("value"), // target + "title", // div().withTitle("value"), // title + "type", // input().withType("value"), // type + "usemap", // img().withUsemap("value"), // usemap + "value", // input().withValue("value"), // value + "width", // input().withWidth("value"), // width + "wrap" // textarea().withWrap("value") // wrap +) + diff --git a/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/converter.kt b/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/converter.kt new file mode 100644 index 00000000..55882a96 --- /dev/null +++ b/html-to-j2html/src/commonMain/kotlin/com/html/to/j2html/common/converter.kt @@ -0,0 +1,437 @@ +package com.html.to.j2html.common +import com.mohamedrejeb.ksoup.html.parser.KsoupHtmlHandler +import com.mohamedrejeb.ksoup.html.parser.KsoupHtmlParser + +data class Tag(val name : String, val attributes : Map, val children : MutableList, val parent: Tag?) { + override fun toString(): String { + return " name($name), attributes($attributes}, children($children)" + } +} + +class TagOrString private constructor(private val tag: Tag?, private val string: String?) { + constructor(string: String) : this(null, string) + constructor(tag: Tag) : this(tag, null) + fun getTag() : Tag?{ + return tag + } + fun getString() : String?{ + return string + } + override fun toString(): String { + val s1 : String = string ?: "" + val s2 : String = tag?.toString() ?: "" + return "$s1$s2" + } +} + +fun convert(input: String): String { + + val mainLevelTagsOrStrings: List = extractAndSanitize(input) + + val tabStr = " " + + var output = "" + val howManyNonCommentTagsOrStringsWeHave = mainLevelTagsOrStrings.filter { "comment" != it.getTag()?.name }.size + var nonCommentIndex = 0 + + for ((index, mainLevelTagOrString) in mainLevelTagsOrStrings.withIndex()) { + val isLastNonComment = nonCommentIndex >= (howManyNonCommentTagsOrStringsWeHave - 1) + val isLast = index >= (mainLevelTagsOrStrings.size - 1) + + if( mainLevelTagOrString.getTag() != null){ + + val mainLevelTag = mainLevelTagOrString.getTag()!! + output += outputTag(mainLevelTag, 0, tabStr) + + } + else if( mainLevelTagOrString.getString() != null ) { + + output += outputStringValue(true, tabStr, 0, true, mainLevelTagOrString.getString()!!) + + } + + if (!isLastNonComment && "comment" != mainLevelTagOrString.getTag()?.name) { + output += "," + } + if (!isLast && "comment" != mainLevelTagOrString.getTag()?.name) { + output += "\n" + } + if ("comment" != mainLevelTagOrString.getTag()?.name) { + nonCommentIndex++ + } + } + + return output + +} + +private fun extractAndSanitize(input: String): List { + val mainLevelTagsOrStrings: MutableList = mutableListOf() + var currentTag: Tag? = null + + val handler = KsoupHtmlHandler + .Builder() + .onOpenTag { name, attributes, _ -> + + if (currentTag != null + && "comment" != currentTag!!.name + ) { + val newTag = Tag(name, attributes, mutableListOf(), currentTag) + currentTag!!.children += TagOrString(newTag) + currentTag = newTag + } else { + currentTag = Tag(name, attributes, mutableListOf(), null) + mainLevelTagsOrStrings += TagOrString(currentTag!!) + } + } + .onComment { comment -> + if (comment.isNotBlank()) { + val newTag = Tag("comment", mapOf(), mutableListOf(), currentTag) + newTag.children += TagOrString(comment.trim()) + if (currentTag != null) { + currentTag!!.children += TagOrString(newTag) + } else { + mainLevelTagsOrStrings += TagOrString(newTag) + } + } + } + .onText { text -> + + if (text.isNotBlank()) { + val tagOrString = TagOrString(sanitizeWhitespace(text)) + + if (currentTag != null + && "comment" != currentTag!!.name + ) { + currentTag!!.children += tagOrString + } else { + mainLevelTagsOrStrings += tagOrString + } + } + } + .onCloseTag { _, _ -> + // we go back to the parent + currentTag = currentTag?.parent + } + .build() + + val parser = KsoupHtmlParser(handler) + parser.write(input) + parser.end() + return mainLevelTagsOrStrings +} + +fun sanitizeWhitespace(text: String): String{ + + // If we don't detect any newlines we assume unformatted input and leave any excess whitespace in + if ( ! text.contains("\n")){ + return text; + } + else { + // if we detect newlines, we strip out the unnecessary whitespace from the inputs + + // this seems to work, but it's hard to not lose a space when they're meant to be there + // while removing all the html indentation spaces for every case + val startsWithReturn = text.startsWith("\n") + val lines = text.split("\n") + var endsWithReturnAndMaybeSpace = false + if(lines.isNotEmpty()){ + endsWithReturnAndMaybeSpace = lines.last().isBlank() + } + + var sanitized = text + + // meant to keep " text" as is but change "\n text" into "text" + if(startsWithReturn){ + sanitized = sanitized.trimStart('\n', ' ') + } + + // meant to keep "text " as is but change "text\n " into "text" + if(endsWithReturnAndMaybeSpace){ + sanitized = sanitized.trimEnd('\n', ' ') + } + + // meant to keep the browser-rendered html identical between the input html and the html produced by j2html + // either though render() or renderFormatter() + // https://stackoverflow.com/questions/588356/why-does-the-browser-renders-a-newline-as-space + // Browsers condense multiple whitespace characters (including newlines) + // to a single space when rendering. The only exception is within
 elements
+        // or those that have the CSS property white-space set to
+        // pre or pre-wrap set. (Or in XHTML, the xml:space="preserve" attribute.)
+        sanitized =  sanitized.replace("\\s+".toRegex(), " ")
+
+
+        return sanitized
+
+    }
+
+}
+
+fun printRawHtmlReturnsAndIndents() : Boolean {
+    return true
+}
+
+fun maxCharactersBeforeSwitchingToMultiline(): Int {
+    return 150
+}
+
+fun outputTag(tag: Tag, indentationLevel : Int, tab : String) : String {
+    var output = ""
+    if ("comment" == tag.name) {
+        // we print each line of multi-line comments on a separate java comment
+        for( commentLine in tag.children[0].getString()!!.split("\n") ){
+            output += tab.repeat(indentationLevel) + "// " + commentLine.trimStart(' ') + "\n"
+        }
+
+    } else if (tag.name in unsupportedTags) {
+        // currently unsupported tags such as 
+        // we have to do a rawHtml("")
+
+        output += tab.repeat(indentationLevel) + "rawHtml(\n"
+        output += tab.repeat(indentationLevel) + "\"\"\"\n"
+        output += printRawHtml(tag, tab, indentationLevel + 1, printRawHtmlReturnsAndIndents())
+        if (!printRawHtmlReturnsAndIndents()) {
+            output += "\n"
+        }
+        output += tab.repeat(indentationLevel) + "\"\"\")"
+
+
+    } else if (tag.attributes.isEmpty()) {
+        // no attributes -> we do the children directly the tag declaration block
+        // div(bla, bla, bla)
+
+        output += tab.repeat(indentationLevel) + tag.name
+        output += outputChildren(tag.children, indentationLevel + 1, tab, false)
+
+
+    } else {
+        // we have attributes,
+        // so we do an empty declaration
+        // then we do the attributes
+        // then we do the children in a 'with' block
+        // div().withClasses("bla", "bla").with(bla, bla, bla)
+
+        output += tab.repeat(indentationLevel) + tag.name + "()"
+        output += outputAttributes(tag.attributes, indentationLevel + 1, tab)
+        if (tag.children.isNotEmpty()) {
+            output += "\n"
+            output += tab.repeat(indentationLevel + 1) + ".with"
+            output += outputChildren(tag.children, indentationLevel + 1, tab, true)
+        }
+    }
+    return output
+}
+
+fun printRawHtml(tag : Tag, tab : String, indentationLevel: Int, printReturnsAndIndent : Boolean) : String {
+    var output = ""
+    if("comment" == tag.name) {
+        if(printReturnsAndIndent){
+            output += tab.repeat(indentationLevel)
+        }
+        output += "<-- "
+        output += tag.children[0].getString()
+        output += " -->"
+        if(printReturnsAndIndent){
+            output += "\n"
+        }
+    }
+    else {
+        if(printReturnsAndIndent){
+            output += tab.repeat(indentationLevel)
+        }
+        output += "<${tag.name}"
+        for (attribute in tag.attributes) {
+            output += " "
+            output += attribute.key
+            output += "=\""
+            output += attribute.value
+            output += "\""
+        }
+        if(tag.children.isNotEmpty()){
+            output += ">"
+            if(printReturnsAndIndent && notAllChildrenAreText(tag.children)){
+                output += "\n"
+            }
+        }
+
+        if(tag.children.isEmpty()) {
+            output += "/>"
+        }
+        else {
+            for (child in tag.children) {
+                if (child.getString() != null) {
+                    output += escapeSoThatJavaPrintsItLikeItIsInTheInput(child.getString()!!)
+                } else if (child.getTag() != null) {
+                    output += printRawHtml(child.getTag()!!, tab, indentationLevel + 1, printReturnsAndIndent)
+                }
+
+            }
+            if(printReturnsAndIndent && notAllChildrenAreText(tag.children)){
+                output += tab.repeat(indentationLevel)
+            }
+            output += ""
+        }
+        if(printReturnsAndIndent){
+            output += "\n"
+        }
+    }
+
+
+    return output
+}
+
+fun notAllChildrenAreText(children : List): Boolean {
+    return ! children.all{ it.getString() != null }
+}
+
+fun outputAttributes(attributes : Map, indentationLevel : Int, tab : String): String{
+
+    val singleAttribute = attributes.size == 1
+
+    var output = ""
+    for(attribute in attributes.entries){
+        val attributeText =
+            if (attribute.key == "class" )
+                ".withClasses(${attribute.value.split(" ").joinToString(", ") { fragment -> "\"$fragment\"" }})"
+            else if (attribute.key.startsWith("data-"))
+                ".withData(\"${attribute.key.replaceFirst("data-", "")}\",\"${attribute.value}\")"
+            else if (attribute.key in knownIntegerHtmlAttributes) //
+                ".with${attribute.key.replaceFirstChar(Char::titlecase)}(${attribute.value.toInt()})"
+            else if (attribute.key in knownBooleanHtmlAttributes)
+                ".withCond${attribute.key.replaceFirstChar(Char::titlecase)}(${parseBooleanFromAttribute(attribute)})"
+            else if (attribute.key in knownStringHtmlAttributes)
+                ".with${attribute.key.replaceFirstChar(Char::titlecase)}(\"${attribute.value}\")"
+            else
+                ".attr(\"${attribute.key}\", \"${attribute.value}\")"
+
+        if(!singleAttribute) {
+            output += "\n"
+            output += tab.repeat(indentationLevel)
+        }
+        output += attributeText
+
+    }
+
+    return output
+}
+
+/**
+ * https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
+ *
+ * Boolean attribute (HTML)
+ * A boolean attribute in HTML is an attribute that represents true or false values. If an HTML tag contains a
+ * boolean attribute - no matter the value of that attribute - the attribute is set to true on that element.
+ * If an HTML tag does not contain the attribute, the attribute is set to false.
+ *
+ * If the attribute is present, it can have one of the following values:
+ *
+ * no value at all, e.g. attribute
+ * the empty string, e.g. attribute=""
+ * attribute's name itself, with no leading or trailing whitespace, e.g. attribute="attribute"
+ *
+ * Addendum by me : some boolean attributes (translate, spellcheck, autocomplete, draggable, probably others)
+ * use "true"/"false", "yes"/"no", or "on"/"off" so I'm parsing those as booleans too
+ *
+ */
+fun parseBooleanFromAttribute(attribute : Map.Entry) : Boolean {
+    return "true" == attribute.value.trim()
+            || "" == attribute.value
+            || attribute.key == attribute.value.trim()
+            || "yes" == attribute.value.trim()
+            || "on" == attribute.value.trim()
+
+}
+
+fun outputChildren(children: MutableList, indentationLevel : Int, tab : String, inWithBlock : Boolean): String{
+
+    var output = ""
+    if(children.isEmpty()) {
+        output += "()"
+    }
+    else {
+        val singleTextValue = children.size == 1 && children[0].getString() != null
+
+        output += "("
+        if (!singleTextValue) {
+            output += "\n"
+        }
+        var nonCommentChildIndex = 0
+        for (child: TagOrString in children) {
+            val isLast = nonCommentChildIndex >= (children.filter { "comment" != it.getTag()?.name }.size - 1)
+
+            if (child.getTag() != null) {
+                output += outputTag(child.getTag()!!, indentationLevel + 1, tab)
+            } else if (child.getString() != null) {
+                output += outputStringValue(singleTextValue, tab, indentationLevel, inWithBlock, child.getString()!!)
+            }
+
+            if (!isLast && "comment" != child.getTag()?.name) {
+                output += ", " + "\n"
+            }
+
+            if ("comment" != child.getTag()?.name) {
+                nonCommentChildIndex++
+            }
+
+        }
+        if (!singleTextValue) {
+            output += "\n"
+            output += tab.repeat(indentationLevel - 1)
+        }
+        output += ")"
+
+    }
+    return output
+}
+
+private fun outputStringValue(singleTextValue: Boolean, tab: String, indentationLevel: Int, inWithBlock: Boolean, childString: String): String {
+    var output = ""
+    if (!singleTextValue) {
+        output += tab.repeat(indentationLevel + 1)
+    }
+    // we're only allowed to only allowed to do p("message"), not p().withId("id").with("message")
+    // so if we had attributes, we're in a with block, we
+    // need a 'text' call to do h2().withId("id").with(text("message"))
+    // since we've kept the attributes before the values like in the html
+    if (!singleTextValue || inWithBlock) {
+        output += "text("
+    }
+    if (false && childString.contains("\n") || childString.length >= maxCharactersBeforeSwitchingToMultiline()) {
+        // triple quotes if long or several lines
+        output += "\n"
+        output += tab.repeat(indentationLevel) + "\"\"\"\n"
+        output += tab.repeat(indentationLevel)
+        output += "${escapeSoThatJavaPrintsItLikeItIsInTheInput(childString)}\n"
+        output += tab.repeat(indentationLevel) + "\"\"\""
+    } else {
+        output += "\"${escapeSoThatJavaPrintsItLikeItIsInTheInput(childString)}\""
+    }
+    // closing the text()
+    if (!singleTextValue || inWithBlock) {
+        output += ")"
+    }
+    return output
+}
+
+fun escapeSoThatJavaPrintsItLikeItIsInTheInput(str : String) : String{
+    var output = ""
+    var index = 0
+    while(index < str.length){
+        output += javaEscapeCode("" + str[index])
+        index++
+    }
+    return output
+}
+
+fun javaEscapeCode(c : String): String{
+    return when(c){
+        "\"" -> "\\\""
+        "\\" -> "\\\\"
+        "\n" -> "\\n"
+        "\r" -> "\\r"
+        "\t" -> "\\t"
+        "\b" -> "\\b"
+        else -> c
+    }
+}
+
diff --git a/html-to-j2html/src/commonTest/kotlin/.gitkeep b/html-to-j2html/src/commonTest/kotlin/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/html-to-j2html/src/commonTest/kotlin/com/html/to/j2html/common/test/ConverterTests.kt b/html-to-j2html/src/commonTest/kotlin/com/html/to/j2html/common/test/ConverterTests.kt
new file mode 100644
index 00000000..450fe0b5
--- /dev/null
+++ b/html-to-j2html/src/commonTest/kotlin/com/html/to/j2html/common/test/ConverterTests.kt
@@ -0,0 +1,668 @@
+package com.html.to.j2html.common.test
+
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import com.html.to.j2html.common.convert
+
+class ConverterTests {
+
+    @Test
+    fun createDiv() {
+        val input = """
+            
Hello world
+ """.trimIndent() + + + val expectedOutput = """ + div("Hello world") + """.trimIndent() + + val output = convert(input) + + assertEquals(expectedOutput, output) + } + + @Test + fun attributes() { + val input = """ +
Hello world
+ """.trimIndent() + + + val expectedOutput = """ + div().attr("att", "one two three") + .with(text("Hello world")) + """.trimIndent() + + val output = convert(input) + + assertEquals(expectedOutput, output) + } + + @Test + fun classes() { + val input = """ +
Hello world
+ """.trimIndent() + + val expectedOutput = """ + div().withClasses("one", "two", "three") + .with(text("Hello world")) + """.trimIndent() + + val output = convert(input) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetWithMainLevelStringsAndSpacesThatNeedToBePreservedTest(){ + val inputSnippetWithMainLevelStringsAndSpacesThatNeedToBePreserved = """ + + text1 link text2 + + """.trimIndent() + + val expectedOutput = """ + // text link text + text("text1 "), + a("link"), + text(" text2") + // post comment + + """.trimIndent() + val output = convert(inputSnippetWithMainLevelStringsAndSpacesThatNeedToBePreserved) + assertEquals(expectedOutput, output) + + } + + @Test + fun inputSnippetWithNewLinesThatAreConsideredSignificantByBrowsersTest(){ + + val inputSnippetWithNewLinesThatAreConsideredSignificantByBrowsers = """ + + text1 + link + text2 + + """.trimIndent() + + // this test documents a compromise with the best solution we could find, for the problem of + // how to sanitize new lines and whitespace without knowing for sure what is and + // isn't significant in the user submitted input. + // the input html renders in a browser as "text1 link text2" + // and at the time of writing this, the html produced by + // text("text1"), + // a("link"), + // text("text2") + // renders as "text1 link text2" or as "text1linktext2" depending on + // wether renderFormatted() or render() is used. + // But as a compomise, that still seems like the most accurate way of generating the code + + val expectedOutput = """ + // text link text + text("text1"), + a("link"), + text("text2") + // post comment + + """.trimIndent() + val output = convert(inputSnippetWithNewLinesThatAreConsideredSignificantByBrowsers) + assertEquals(expectedOutput, output) + + } + + @Test + fun textWithSpacesAroundALinkTest(){ + + val textWithSpacesAroundALinkAndAnAnchorHRefLink = """ +

before link $ space link after link & a space

+ """ + + val expectedOutput = """ + p( + text("before link $ space "), + a().withHref("#faq") + .with(text("link")), + text(" after link & a space") + ) + """.trimIndent() + + val output = convert(textWithSpacesAroundALinkAndAnAnchorHRefLink) + assertEquals(expectedOutput, output) + + } + + @Test + fun inputSnippetWithNewLinesAtBegginingAndEndOfParagraphTest() { + + // not that easy to fulfill without breaking textWithSpacesAroundALinkTest() + + val inputSnippetWithNewLinesAtBegginingAndEndOfParagraph = + """ +
+
+

+ Hello world +

+
+
+ """.trimIndent() + + val expectedOutput = """ + main( + div( + p("Hello world") + ) + ) + """.trimIndent() + + val output = convert(inputSnippetWithNewLinesAtBegginingAndEndOfParagraph) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetOfj2htmlDefaultExampleTest() { + + val inputSnippetOfj2htmlExamplePage = """ + +
+
+

David

+ +

Creator of Bad Libraries

+
+
+

Christian

+ +

Fanboi of Jenkins

+
+
+

Paul\n

+ +

Hater of Lambda Expressions

+
+
+ """.trimIndent() + + val expectedOutput = """ + // j2html default snippet + div().withId("employees") + .with( + div().withClasses("employee") + .with( + h2("David"), + img().withSrc("/img/david.png"), + p("Creator of Bad Libraries") + ), + div().withClasses("employee") + .with( + h2("Christian"), + img().withSrc("/img/christian.png"), + p("Fanboi of Jenkins") + ), + div().withClasses("employee") + .with( + h2("Paul\\n"), + img().withSrc("/img/paul.png"), + p("Hater of Lambda Expressions") + ) + ) + """.trimIndent() + + val output = convert(inputSnippetOfj2htmlExamplePage) + + assertEquals(expectedOutput, output) + + } + @Test + fun inputSnippetWithDataAttributesBooleanParsingAndIntegerParsingTest() { + + val inputSnippetWithDataAttributesBooleanParsingAndIntegerParsing = """ + +
+

Special attribute animals

+
    +
  • Owl
  • +
  • Salmon
  • +
  • Tarantula
  • +
  • Panda
  • +
  • Penguin
  • +
  • Megalodon
  • +
+
+ """.trimIndent() + + val expectedOutput = """ + // special attributes test snippet + div() + .withClasses("special-attr-test") + .withTabindex(5) + .with( + h2("Special attribute animals"), + ul( + li() + .withData("animal-type","bird") + .withCondTranslate(true) + .with(text("Owl")), + li() + .withData("animal-type","fish") + .withCondTranslate(true) + .with(text("Salmon")), + li() + .withData("animal-type","spider") + .withCondTranslate(true) + .with(text("Tarantula")), + li() + .withData("animal-type","bear") + .withCondTranslate(true) + .with(text("Panda")), + li() + .withData("animal-type","bird") + .withCondTranslate(false) + .with(text("Penguin")), + li() + .withData("animal-type","fish") + .withCondTranslate(false) + .with(text("Megalodon")) + ) + ) + """.trimIndent() + + val output = convert(inputSnippetWithDataAttributesBooleanParsingAndIntegerParsing) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetOfCommonHtmxUseCasesTest() { + + val inputSnippetOfCommonHtmxUseCases = """ + +
+

HTMX snippets

+ +
+

Lazy loading

+
+ Result loading... +
+
+
+ """.trimIndent() + + val expectedOutput = """ + // htmx snippets + div().withId("misc-htmx-snippets") + .with( + h2("HTMX snippets"), + // https://htmx.org/examples/lazy-load/ + div().withId("htmx lazy-loading") + .with( + h3("Lazy loading"), + div() + .attr("hx-get", "/graph") + .attr("hx-trigger", "load") + .with( + img() + .withAlt("Result loading...") + .withClasses("htmx-indicator") + .withWidth("150") + .withSrc("/img/bars.svg") + ) + ) + ) + """.trimIndent() + + val output = convert(inputSnippetOfCommonHtmxUseCases) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetOfHtmxInfiniteScrollTest() { + + val inputSnippetOfHtmxInfiniteScroll = """ + +
+

HTMX snippets

+ +
+

Infinite scroll

+ + Agent Smith + void29@null.org + 55F49448C0 + +
+
+ """.trimIndent() + + val expectedOutput = """ + // htmx snippets + div().withId("misc-htmx-snippets") + .with( + h2("HTMX snippets"), + // https://htmx.org/examples/infinite-scroll/ + div( + h3("Infinite scroll"), + tr() + .attr("hx-get", "/contacts/?page=2") + .attr("hx-trigger", "revealed") + .attr("hx-swap", "afterend") + .with( + td("Agent Smith"), + td("void29@null.org"), + td("55F49448C0") + ) + ) + ) + """.trimIndent() + + val output = convert(inputSnippetOfHtmxInfiniteScroll) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetOfSomePicoCssComponentsAndCharactersThatNeedEscapingTest() { + + val inputSnippetOfAPicoCssAccordionWithCharactersThatNeedEscapingBothInSingleAndMultilineStrings = """ + +
+

Pico CSS snippets

+ +
+ +
+

Accordions

+
+ Accordion 1 +

+ n \n \\n \\\n \\\\n f \f \\f \\\f \\\\f Lorem ipsum dolor sit amet\", consectetur ad"ipiscing elit. Pelle\"ntesque urna diam, + " \" \\" \\\" \\\\" tincidunt nec port"a sed, auctor id veli\t. Et"iam ve\\nenatis nisl ut "orci consequat, vitae + tempus quam commodo. Nulla non mauris ipsum. Aliquam eu posuere orci. Nulla co\\\\nvallis + lectus rutrum quam hendrerit, in facilisis elit sollicitu"din. Ma"uri"s pulvinar pulvinar + mi, dictum tr"istique elit auctor quis. Maecenas ac ipsum u\\"ltrices, porta turpis sit + amet, congue turpis. +

+

n \n \\n \\\n \\\\n f \f \\f \\\f \\\\f Lorem ipsum dolor sit amet\", consectetur ad"ipiscing elit. Pelle\"ntesque urna diam, " \" \\" \\\" \\\\" tincidunt nec port"a sed, auctor id veli\t. Et"iam ve\\nenatis nisl ut "orci consequat, vitae tempus quam commodo. Nulla non mauris ipsum. Aliquam eu posuere orci. Nulla co\\\\nvallis lectus rutrum quam hendrerit, in facilisis elit sollicitu"din. Ma"uri"s pulvinar pulvinar mi, dictum tr"istique elit auctor quis. Maecenas ac ipsum u\\"ltrices, porta turpis sit amet, congue turpis.

+
+
+ Accordion 2 +
    +
  • Vestibu\"lum i"d e"lit q"uis massa interdum sodales.
  • +
  • n \n \\n \\\n \\\\n Nunc quis eros vel odio pretium tincidunt nec quis neque.
  • +
  • f \f \\f \\\f \\\\f Quisque sed eros non eros ornare elementum.
  • +
  • " \" \\" \\\" \\\\" Cras sed libero aliquet, porta dolor quis, dapibus ipsum.
  • +
  • ' \' \\' \\\' \\\\' Cras sed libero aliquet, porta dolor quis, dapibus ipsum.
  • +
+
+
+
+
+ """.trimIndent() + + val expectedOutput = """ + // pico css snippets + div().withId("misc-picocss-snippets") + .with( + h2("Pico CSS snippets"), + // https://github.com/picocss/examples/blob/master/v2-html-classless/index.html + div().withId("pico-css-accordion") + .with( + // Accordions + section().withId("accordions") + .with( + h3("Accordions"), + details( + summary("Accordion 1"), + p( + ""${'"'} + n \\n \\\\n \\\\\\n \\\\\\\\n f \\f \\\\f \\\\\\f \\\\\\\\f Lorem ipsum dolor sit amet\\\", consectetur ad\"ipiscing elit. Pelle\\\"ntesque urna diam, \" \\\" \\\\\" \\\\\\\" \\\\\\\\\" tincidunt nec port\"a sed, auctor id veli\\t. Et\"iam ve\\\\nenatis nisl ut \"orci consequat, vitae tempus quam commodo. Nulla non mauris ipsum. Aliquam eu posuere orci. Nulla co\\\\\\\\nvallis lectus rutrum quam hendrerit, in facilisis elit sollicitu\"din. Ma\"uri\"s pulvinar pulvinar mi, dictum tr\"istique elit auctor quis. Maecenas ac ipsum u\\\\\"ltrices, porta turpis sit amet, congue turpis. + ""${'"'}), + p( + ""${'"'} + n \\n \\\\n \\\\\\n \\\\\\\\n f \\f \\\\f \\\\\\f \\\\\\\\f Lorem ipsum dolor sit amet\\\", consectetur ad\"ipiscing elit. Pelle\\\"ntesque urna diam, \" \\\" \\\\\" \\\\\\\" \\\\\\\\\" tincidunt nec port\"a sed, auctor id veli\\t. Et\"iam ve\\\\nenatis nisl ut \"orci consequat, vitae tempus quam commodo. Nulla non mauris ipsum. Aliquam eu posuere orci. Nulla co\\\\\\\\nvallis lectus rutrum quam hendrerit, in facilisis elit sollicitu\"din. Ma\"uri\"s pulvinar pulvinar mi, dictum tr\"istique elit auctor quis. Maecenas ac ipsum u\\\\\"ltrices, porta turpis sit amet, congue turpis. + ""${'"'}) + ), + details().withCondOpen(true) + .with( + summary("Accordion 2"), + ul( + li("Vestibu\\\"lum i\"d e\"lit q\"uis massa interdum sodales."), + li("n \\n \\\\n \\\\\\n \\\\\\\\n Nunc quis eros vel odio pretium tincidunt nec quis neque."), + li("f \\f \\\\f \\\\\\f \\\\\\\\f Quisque sed eros non eros ornare elementum."), + li("\" \\\" \\\\\" \\\\\\\" \\\\\\\\\" Cras sed libero aliquet, porta dolor quis, dapibus ipsum."), + li("' \\' \\\\' \\\\\\' \\\\\\\\' Cras sed libero aliquet, porta dolor quis, dapibus ipsum.") + ) + ) + ) + ) + ) + """.trimIndent() + + val output = + convert(inputSnippetOfAPicoCssAccordionWithCharactersThatNeedEscapingBothInSingleAndMultilineStrings) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetContainingUnsupportedTagsTest() { + + val inputSnippetContainingUnsupportedTags = """ + +
+ +
+
Info
+
+
+ """.trimIndent() + + val expectedOutput = """ + // https://flowbite.com/docs/components/drawer/ + div().withId("flowbyte drawer") + .with( + // drawer component + div() + .withId("drawer-example") + .withClasses("fixed", "top-0", "left-0", "z-40", "h-screen", "p-4", "overflow-y-auto", "transition-transform", "-translate-x-full", "bg-white", "w-80", "dark:bg-gray-800") + .withTabindex(-1) + .attr("aria-labelledby", "drawer-label") + .with( + h5() + .withId("drawer-label") + .withClasses("inline-flex", "items-center", "mb-4", "text-base", "font-semibold", "text-gray-500", "dark:text-gray-400") + .with( + rawHtml( + ""${'"'} + + ""${'"'}), + text("Info") + ) + ) + ) + """.trimIndent() + + val output = convert(inputSnippetContainingUnsupportedTags) + + assertEquals(expectedOutput, output) + } + + + + + + @Test + fun inputSnippetWithCharactersThatNeedEscapingWhileInAUnsupportedTagTest() { + + val inputSnippetWithCharactersThatNeedEscapingWhileInAUnsupportedTag = """ + +
+

Flowbyte simple toast

+ +
+ """.trimIndent() + + val expectedOutput = """ + // https://flowbite.com/docs/components/toast/ + div().withId("flowbyte simple toast") + .with( + h3("Flowbyte simple toast"), + div() + .withId("toast-simple") + .withClasses("flex", "items-center", "w-full", "max-w-xs", "p-4", "space-x-4", "rtl:space-x-reverse", "text-gray-500", "bg-white", "divide-x", "rtl:divide-x-reverse", "divide-gray-200", "rounded-lg", "shadow", "dark:text-gray-400", "dark:divide-gray-700", "space-x", "dark:bg-gray-800") + .attr("role", "alert") + .with( + rawHtml( + ""${'"'} +
  • n \\n \\\\n \\\\\\n \\\\\\\\n Nunc quis eros vel odio pretium tincidunt nec quis neque.
  • +
  • f \\f \\\\f \\\\\\f \\\\\\\\f Quisque sed eros non eros ornare elementum.
  • +
  • \" \\\" \\\\\" \\\\\\\" \\\\\\\\\" Cras sed libero aliquet, porta dolor quis, dapibus ipsum.
  • +
  • ' \\' \\\\' \\\\\\' \\\\\\\\' Cras sed libero aliquet, porta dolor quis, dapibus ipsum.
  • + + + ""${'"'}), + div().withClasses("ps-4", "text-sm", "font-normal") + .with(text("Message sent successfully.")) + ) + ) + """.trimIndent() + + val output = convert(inputSnippetWithCharactersThatNeedEscapingWhileInAUnsupportedTag) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetOfSomeTailWindComponentsTest() { + + val inputSnippetOfSomeTailWindComponents = """ + +
    +

    TW select multiple

    + + +
    + """.trimIndent() + + val expectedOutput = """ + // https://tw-elements.com/docs/standard/forms/select/ + div().withId("tailwind-select-multiple") + .with( + h3("TW select multiple"), + select() + .withData("te-select-init","") + .withCondMultiple(true) + .with( + option().withValue("1") + .with(text("One")), + option().withValue("2") + .with(text("Two")), + option().withValue("3") + .with(text("Three")) + ), + label().withData("te-select-label-ref","") + .with(text("Example label")) + ) + """.trimIndent() + + val output = convert(inputSnippetOfSomeTailWindComponents) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetWithSeveralTopLevelElementsPlusCommentsBeforeAndAfterTest() { + + val inputSnippetWithSeveralTopLevelElementsPlusCommentsBeforeAndAfter = """ + +
    +
    +
    +
    +

    Hello world

    +
    +
    + + """.trimIndent() + + val expectedOutput = """ + // test beggining comment + div().withId("first main level tag"), + div().withId("second main level tag") + .with( + div( + p("Hello world") + ) + ) + // test end comment + + """.trimIndent() + + val output = convert(inputSnippetWithSeveralTopLevelElementsPlusCommentsBeforeAndAfter) + + assertEquals(expectedOutput, output) + } + + @Test + fun inputSnippetWithMultilineCommentsTest() { + + val inputSnippetWithMultilineComments = """ + +
    +
    +
    +
    +

    Hello world

    +
    +
    + + """.trimIndent() + + val expectedOutput = """ + // test beggining + // multiline comment + div().withId("first main level tag"), + div().withId("second main level tag") + .with( + div( + p("Hello world") + ) + ) + // test end + // multiline comment + + """.trimIndent() + + val output = convert(inputSnippetWithMultilineComments) + + assertEquals(expectedOutput, output) + } + +} diff --git a/html-to-j2html/src/jsMain/kotlin/.gitkeep b/html-to-j2html/src/jsMain/kotlin/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/html-to-j2html/src/jsMain/kotlin/jsConvert.kt b/html-to-j2html/src/jsMain/kotlin/jsConvert.kt new file mode 100644 index 00000000..946c6b05 --- /dev/null +++ b/html-to-j2html/src/jsMain/kotlin/jsConvert.kt @@ -0,0 +1,9 @@ +import com.html.to.j2html.common.convert + +@JsExport +@OptIn(kotlin.js.ExperimentalJsExport::class) +@JsName("j2htmlconvert") +fun j2htmlconvert(input: String): String { + + return convert(input) +} diff --git a/html-to-j2html/src/jsTest/kotlin/.gitkeep b/html-to-j2html/src/jsTest/kotlin/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/html-to-j2html/src/jvmMain/kotlin/.gitkeep b/html-to-j2html/src/jvmMain/kotlin/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/html-to-j2html/src/jvmMain/kotlin/com/html/to/j2html/jvm/jvmMain.kt b/html-to-j2html/src/jvmMain/kotlin/com/html/to/j2html/jvm/jvmMain.kt new file mode 100644 index 00000000..f9abeb4a --- /dev/null +++ b/html-to-j2html/src/jvmMain/kotlin/com/html/to/j2html/jvm/jvmMain.kt @@ -0,0 +1,20 @@ +package com.html.to.j2html.jvm + +import com.html.to.j2html.common.convert +import java.io.File + +fun main() { + val inputFile = File("input.html") + if(inputFile.exists()){ + println("input path : ${inputFile.absolutePath}") + val outputFile = File("output.java") + val output = convert(inputFile.readText()) + outputFile.writeText(output) + println("converted to ${inputFile.absolutePath}") + } + else { + println("input.html not found") + } + +} + diff --git a/html-to-j2html/src/jvmTest/kotlin/.gitkeep b/html-to-j2html/src/jvmTest/kotlin/.gitkeep new file mode 100644 index 00000000..e69de29b