Browse Source

Autogenerate all web examples from samples

That would make it easier to keep them consistent and to test them
continuously
pull/957/head
Shagen Ogandzhanian 3 years ago
parent
commit
6fa567032e
  1. 2
      examples/falling_balls_with_web/build.gradle.kts
  2. 2
      examples/web-compose-bird/build.gradle.kts
  3. 2
      examples/web-getting-started/build.gradle.kts
  4. 2
      examples/web-with-react/build.gradle.kts
  5. 2
      examples/web_landing/build.gradle.kts
  6. 51
      web/build.gradle.kts
  7. 74
      web/samples/falling_balls_with_web/build.gradle.kts
  8. BIN
      web/samples/falling_balls_with_web/gradle/wrapper/gradle-wrapper.jar
  9. 5
      web/samples/falling_balls_with_web/gradle/wrapper/gradle-wrapper.properties
  10. 185
      web/samples/falling_balls_with_web/gradlew
  11. 89
      web/samples/falling_balls_with_web/gradlew.bat
  12. 10
      web/samples/falling_balls_with_web/settings.gradle.kts
  13. 77
      web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/Game.kt
  14. 29
      web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/Piece.kt
  15. 32
      web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/PieceData.kt
  16. 103
      web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/fallingBalls.kt
  17. 8
      web/samples/falling_balls_with_web/src/commonMain/kotlin/modifiers/position.kt
  18. 30
      web/samples/falling_balls_with_web/src/jsMain/kotlin/androidx/compose/web/with-web/App.kt
  19. 21
      web/samples/falling_balls_with_web/src/jsMain/kotlin/modifiers/position.kt
  20. 29
      web/samples/falling_balls_with_web/src/jsMain/resources/index.html
  21. 8
      web/samples/falling_balls_with_web/src/jsMain/resources/styles.css
  22. 24
      web/samples/falling_balls_with_web/src/jvmMain/kotlin/App.kt
  23. 14
      web/samples/falling_balls_with_web/src/jvmMain/kotlin/modifiers/position.kt
  24. 15
      web/samples/web-compose-bird/.gitignore
  25. 35
      web/samples/web-compose-bird/README.md
  26. 28
      web/samples/web-compose-bird/build.gradle.kts
  27. BIN
      web/samples/web-compose-bird/cover.jpeg
  28. BIN
      web/samples/web-compose-bird/demo.gif
  29. 2
      web/samples/web-compose-bird/gradle.properties
  30. BIN
      web/samples/web-compose-bird/gradle/wrapper/gradle-wrapper.jar
  31. 5
      web/samples/web-compose-bird/gradle/wrapper/gradle-wrapper.properties
  32. 185
      web/samples/web-compose-bird/gradlew
  33. 89
      web/samples/web-compose-bird/gradlew.bat
  34. 8
      web/samples/web-compose-bird/settings.gradle.kts
  35. 157
      web/samples/web-compose-bird/src/jsMain/kotlin/core/ComposeBirdGame.kt
  36. 13
      web/samples/web-compose-bird/src/jsMain/kotlin/core/Game.kt
  37. 9
      web/samples/web-compose-bird/src/jsMain/kotlin/data/GameFrame.kt
  38. 6
      web/samples/web-compose-bird/src/jsMain/kotlin/data/Tube.kt
  39. 140
      web/samples/web-compose-bird/src/jsMain/kotlin/main.kt
  40. 17
      web/samples/web-compose-bird/src/jsMain/resources/index.html
  41. 3
      web/samples/web-getting-started/.gitignore
  42. 4
      web/samples/web-getting-started/README.md
  43. 24
      web/samples/web-getting-started/build.gradle.kts
  44. 1
      web/samples/web-getting-started/gradle.properties
  45. BIN
      web/samples/web-getting-started/gradle/wrapper/gradle-wrapper.jar
  46. 5
      web/samples/web-getting-started/gradle/wrapper/gradle-wrapper.properties
  47. 185
      web/samples/web-getting-started/gradlew
  48. 89
      web/samples/web-getting-started/gradlew.bat
  49. 9
      web/samples/web-getting-started/settings.gradle.kts
  50. 34
      web/samples/web-getting-started/src/jsMain/kotlin/Main.kt
  51. 11
      web/samples/web-getting-started/src/jsMain/resources/index.html
  52. 3
      web/samples/web-with-react/.gitignore
  53. 24
      web/samples/web-with-react/README.md
  54. 31
      web/samples/web-with-react/build.gradle.kts
  55. 1
      web/samples/web-with-react/gradle.properties
  56. BIN
      web/samples/web-with-react/gradle/wrapper/gradle-wrapper.jar
  57. 5
      web/samples/web-with-react/gradle/wrapper/gradle-wrapper.properties
  58. 185
      web/samples/web-with-react/gradlew
  59. 89
      web/samples/web-with-react/gradlew.bat
  60. 9
      web/samples/web-with-react/settings.gradle.kts
  61. 149
      web/samples/web-with-react/src/jsMain/kotlin/ComposeInReactApp.kt
  62. 14
      web/samples/web-with-react/src/jsMain/kotlin/Main.kt
  63. 94
      web/samples/web-with-react/src/jsMain/kotlin/ReactInComposeApp.kt
  64. 11
      web/samples/web-with-react/src/jsMain/kotlin/ReactYoutubePlayer.kt
  65. 11
      web/samples/web-with-react/src/jsMain/resources/index.html
  66. 15
      web/samples/web_landing/.gitignore
  67. 26
      web/samples/web_landing/build.gradle.kts
  68. 1
      web/samples/web_landing/gradle.properties
  69. BIN
      web/samples/web_landing/gradle/wrapper/gradle-wrapper.jar
  70. 5
      web/samples/web_landing/gradle/wrapper/gradle-wrapper.properties
  71. 185
      web/samples/web_landing/gradlew
  72. 89
      web/samples/web_landing/gradlew.bat
  73. 201
      web/samples/web_landing/license/LICENSE.txt
  74. 5
      web/samples/web_landing/license/third_party/README.md
  75. 29
      web/samples/web_landing/license/third_party/highlightjs.txt
  76. 10
      web/samples/web_landing/settings.gradle.kts
  77. 12
      web/samples/web_landing/src/jsMain/kotlin/com/sample/HighlightJs.kt
  78. 27
      web/samples/web_landing/src/jsMain/kotlin/com/sample/Main.kt
  79. 80
      web/samples/web_landing/src/jsMain/kotlin/com/sample/components/Card.kt
  80. 54
      web/samples/web_landing/src/jsMain/kotlin/com/sample/components/Layout.kt
  81. 96
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/AboutComposeWebLibsSection.kt
  82. 90
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/CodeSamplesSwitcher.kt
  83. 276
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/CodeSnippets.kt
  84. 113
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/Footer.kt
  85. 107
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/GetStartedSection.kt
  86. 59
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/Header.kt
  87. 223
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/IntroSection.kt
  88. 72
      web/samples/web_landing/src/jsMain/kotlin/com/sample/content/JoinUs.kt
  89. 95
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/Stylesheet.kt
  90. 49
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtCard.kt
  91. 137
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtCol.kt
  92. 38
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtContainer.kt
  93. 25
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtDisplay.kt
  94. 41
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtOffest.kt
  95. 42
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtRow.kt
  96. 27
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtSection.kt
  97. 221
      web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtText.kt
  98. BIN
      web/samples/web_landing/src/jsMain/resources/favicon-32x32.png
  99. 58
      web/samples/web_landing/src/jsMain/resources/hljs.css
  100. 1
      web/samples/web_landing/src/jsMain/resources/i1.svg
  101. Some files were not shown because too many files have changed in this diff Show More

2
examples/falling_balls_with_web/build.gradle.kts

@ -1,6 +1,8 @@
import org.jetbrains.compose.compose
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
// This project is autogenerated from ../web/samples/falling_balls_with_web
// In case you want modify code, please, modify it there.
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose") version "0.5.0-build270"

2
examples/web-compose-bird/build.gradle.kts

@ -1,4 +1,6 @@
// Add compose gradle plugin
// This project is autogenerated from ../web/samples/web-compose-bird
// In case you want modify code, please, modify it there.
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose") version "0.5.0-build270"

2
examples/web-getting-started/build.gradle.kts

@ -1,3 +1,5 @@
// This project is autogenerated from ../web/samples/web-getting-started
// In case you want modify code, please, modify it there.
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose") version "0.5.0-build270"

2
examples/web-with-react/build.gradle.kts

@ -1,3 +1,5 @@
// This project is autogenerated from ../web/samples/web-with-react
// In case you want modify code, please, modify it there.
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose") version "0.5.0-build270"

2
examples/web_landing/build.gradle.kts

@ -1,3 +1,5 @@
// This project is autogenerated from ../web/samples/web_landing
// In case you want modify code, please, modify it there.
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose") version "0.5.0-build270"

51
web/build.gradle.kts

@ -1,3 +1,4 @@
val COMPOSE_CORE_VERSION: String by project
val COMPOSE_WEB_VERSION: String by project
val COMPOSE_REPO_USERNAME: String? by project
val COMPOSE_REPO_KEY: String? by project
@ -5,12 +6,62 @@ val COMPOSE_WEB_BUILD_WITH_SAMPLES = project.property("compose.web.buildSamples"
apply<jetbrains.compose.web.gradle.SeleniumDriverPlugin>()
fun Project.isSampleProject() = projectDir.parentFile.name == "samples"
tasks.register("generateExamples") {
dependsOn(
subprojects.filter { it.isSampleProject() }.map { ":samples:${it.name}:sync" }
)
}
subprojects {
apply(plugin = "maven-publish")
group = "org.jetbrains.compose.web"
version = COMPOSE_WEB_VERSION
if (isSampleProject()) {
val buildGradleSpec = copySpec {
from("build.gradle.kts") {
filter { line ->
line
.replace(
"plugins {",
"""// This project is autogenerated from ../web/samples/${project.projectDir.name}
// In case you want modify code, please, modify it there.
plugins {"""
)
.replace(
"id(\"org.jetbrains.compose\")",
"id(\"org.jetbrains.compose\") version \"$COMPOSE_CORE_VERSION\"",
)
.replace(
"implementation(project(\":web-core\"))",
"implementation(compose.web.core)"
)
.replace(
"implementation(project(\":web-widgets\"))",
"implementation(compose.web.widgets)"
)
}
}
}
tasks.register<Sync>("sync") {
val targetDir = rootProject.projectDir.resolve("../examples/${project.projectDir.name}").normalize()
duplicatesStrategy = DuplicatesStrategy.INCLUDE
from(project.projectDir)
into(targetDir)
exclude("build")
with(buildGradleSpec)
doLast {
println("from ${project.projectDir} => $targetDir")
}
}
}
pluginManager.withPlugin("maven-publish") {
configure<PublishingExtension> {
repositories {

74
web/samples/falling_balls_with_web/build.gradle.kts

@ -0,0 +1,74 @@
import org.jetbrains.compose.compose
import org.jetbrains.compose.desktop.application.dsl.TargetFormat
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose")
}
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
jvm()
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
implementation(compose.web.widgets)
implementation(compose.runtime)
}
}
val jvmMain by getting {
dependencies {
implementation(compose.desktop.currentOs)
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
}
}
compose.desktop {
application {
mainClass = "org.jetbrains.compose.common.demo.AppKt"
nativeDistributions {
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb)
packageName = "ImageViewer"
packageVersion = "1.0.0"
modules("jdk.crypto.ec")
val iconsRoot = project.file("../common/src/desktopMain/resources/images")
macOS {
iconFile.set(iconsRoot.resolve("icon-mac.icns"))
}
windows {
iconFile.set(iconsRoot.resolve("icon-windows.ico"))
menuGroup = "Compose Examples"
// see https://wixtoolset.org/documentation/manual/v3/howtos/general/generate_guids.html
upgradeUuid = "18159995-d967-4CD2-8885-77BFA97CFA9F"
}
linux {
iconFile.set(iconsRoot.resolve("icon-linux.png"))
}
}
}
}

BIN
web/samples/falling_balls_with_web/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
web/samples/falling_balls_with_web/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
web/samples/falling_balls_with_web/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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 UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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 "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
web/samples/falling_balls_with_web/gradlew.bat vendored

@ -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

10
web/samples/falling_balls_with_web/settings.gradle.kts

@ -0,0 +1,10 @@
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") }
}
}
rootProject.name = "falling_balls_with_web"

77
web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/Game.kt

@ -0,0 +1,77 @@
package org.jetbrains.compose.demo.falling
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.jetbrains.compose.common.ui.unit.IntSize
import org.jetbrains.compose.common.core.graphics.Color
import kotlin.random.Random
private fun Color.Companion.random() =
Color((0..255).random(), (0..255).random(), (0..255).random())
abstract class Game {
internal var previousTime: Long = Long.MAX_VALUE
private var startTime = 0L
var size by mutableStateOf(IntSize(0, 0))
var width: Int
get() = size.width
set(newWidth: Int) {
size = IntSize(newWidth, height)
}
var height: Int
get() = size.height
set(newHeight) {
size = IntSize(width, newHeight)
}
var pieces = mutableStateListOf<PieceData>()
private set
var elapsed by mutableStateOf(0L)
var score by mutableStateOf(0)
var clicked by mutableStateOf(0)
var started by mutableStateOf(false)
var paused by mutableStateOf(false)
var finished by mutableStateOf(false)
var numBlocks by mutableStateOf(5)
fun isInBoundaries(pieceData: PieceData) = pieceData.position < size.height
abstract fun now(): Long
fun togglePause() {
paused = !paused
previousTime = Long.MAX_VALUE
}
fun start() {
previousTime = now()
startTime = previousTime
clicked = 0
started = true
finished = false
paused = false
pieces.clear()
repeat(numBlocks) { index ->
pieces.add(
PieceData(this, index * 1.5f + 5f, Color.random()).also { piece ->
piece.position = Random.nextDouble(0.0, 100.0).toFloat()
}
)
}
}
fun update(nanos: Long) {
val dt = (nanos - previousTime).coerceAtLeast(0)
previousTime = nanos
elapsed = nanos - startTime
pieces.forEach { it.update(dt) }
}
}

29
web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/Piece.kt

@ -0,0 +1,29 @@
package org.jetbrains.compose.demo.falling.views
import androidx.compose.runtime.Composable
import org.jetbrains.compose.demo.falling.PieceData
import org.jetbrains.compose.common.ui.Modifier
import org.jetbrains.compose.common.foundation.layout.Box
import org.jetbrains.compose.common.ui.unit.dp
import org.jetbrains.compose.common.ui.unit.Dp
import org.jetbrains.compose.common.foundation.layout.offset
import org.jetbrains.compose.common.ui.background
import org.jetbrains.compose.common.ui.size
import org.jetbrains.compose.common.foundation.clickable
import org.jetbrains.compose.common.ui.draw.clip
import org.jetbrains.compose.common.core.graphics.Color
import jetbrains.compose.common.shapes.CircleShape
import org.jetbrains.compose.common.demo.position
@Composable
fun Piece(index: Int, piece: PieceData) {
val boxSize = 40.dp
Box(
Modifier
.position(Dp(boxSize.value * index * 5 / 3), Dp(piece.position))
.size(boxSize, boxSize)
.background(if (piece.picked) Color.Gray else piece.color)
.clickable { piece.pick() }
.clip(CircleShape)
) {}
}

32
web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/PieceData.kt

@ -0,0 +1,32 @@
package org.jetbrains.compose.demo.falling
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import org.jetbrains.compose.common.core.graphics.Color
data class PieceData(val game: Game, val velocity: Float, val color: Color) {
var picked: Boolean by mutableStateOf(false)
var position: Float by mutableStateOf(0f)
private fun Game.pickPiece(piece: PieceData) {
score += piece.velocity.toInt()
clicked++
if (clicked == numBlocks) {
finished = true
}
}
fun update(dt: Long) {
if (picked) return
val delta = (dt / 1E8 * velocity).toFloat()
position = if (game.isInBoundaries(this)) position + delta else 0f
}
fun pick() {
if (!picked && !game.paused) {
picked = true
game.pickPiece(this)
}
}
}

103
web/samples/falling_balls_with_web/src/commonMain/kotlin/fallingBalls/fallingBalls.kt

@ -0,0 +1,103 @@
package org.jetbrains.compose.demo.falling.views
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.withFrameNanos
import org.jetbrains.compose.demo.falling.Game
import org.jetbrains.compose.common.material.Text
import org.jetbrains.compose.common.foundation.layout.Column
import org.jetbrains.compose.common.material.Slider
import org.jetbrains.compose.common.foundation.layout.Row
import org.jetbrains.compose.common.foundation.layout.Box
import org.jetbrains.compose.common.material.Button
import org.jetbrains.compose.common.ui.Modifier
import org.jetbrains.compose.common.ui.unit.em
import org.jetbrains.compose.common.ui.unit.dp
import org.jetbrains.compose.common.foundation.layout.offset
import org.jetbrains.compose.common.foundation.layout.width
import org.jetbrains.compose.common.ui.layout.onSizeChanged
import org.jetbrains.compose.common.ui.background
import org.jetbrains.compose.common.foundation.border
import org.jetbrains.compose.common.ui.size
import org.jetbrains.compose.common.core.graphics.Color
import org.jetbrains.compose.common.foundation.layout.fillMaxHeight
import org.jetbrains.compose.common.foundation.layout.fillMaxWidth
@Composable
fun fallingBalls(game: Game) {
Column(Modifier.fillMaxWidth().fillMaxHeight(1f)) {
Box() {
Text(
"Catch balls!${if (game.finished) " Game over!" else ""}",
size = 1.8f.em,
color = Color(218, 120, 91)
)
}
Box() {
Text(
"Score: ${game.score} Time: ${game.elapsed / 1_000_000} Blocks: ${game.numBlocks}",
size = 1.8f.em
)
}
Row() {
if (!game.started) {
Slider(
value = game.numBlocks / 20f,
onValueChange = { game.numBlocks = (it * 20f).toInt().coerceAtLeast(1) },
modifier = Modifier.width(100.dp)
)
}
Button(
Modifier
.border(2.dp, Color(255, 215, 0))
.background(Color.Yellow),
onClick = {
game.started = !game.started
if (game.started) {
game.start()
}
}
) {
Text(if (game.started) "Stop" else "Start", size = 2f.em)
}
if (game.started) {
Button(
Modifier
.offset(10.dp, 0.dp)
.border(2.dp, Color(255, 215, 0))
.background(Color.Yellow),
onClick = {
game.togglePause()
}
) {
Text(if (game.paused) "Resume" else "Pause", size = 2f.em)
}
}
}
if (game.started) {
Box(
Modifier
.fillMaxWidth()
.fillMaxHeight(1f)
.size(game.width.dp, game.height.dp)
.onSizeChanged {
game.size = it
}
) {
game.pieces.forEachIndexed { index, piece ->
Piece(index, piece)
}
}
}
LaunchedEffect(Unit) {
while (true) {
withFrameNanos {
if (game.started && !game.paused && !game.finished)
game.update(it)
}
}
}
}
}

8
web/samples/falling_balls_with_web/src/commonMain/kotlin/modifiers/position.kt

@ -0,0 +1,8 @@
package org.jetbrains.compose.common.demo
import androidx.compose.runtime.Composable
import org.jetbrains.compose.common.ui.Modifier
import org.jetbrains.compose.common.ui.unit.Dp
@Composable
expect fun Modifier.position(width: Dp, height: Dp): Modifier

30
web/samples/falling_balls_with_web/src/jsMain/kotlin/androidx/compose/web/with-web/App.kt

@ -0,0 +1,30 @@
package org.jetbrainsc.compose.common.demo
import org.jetbrains.compose.web.renderComposable
import kotlinx.browser.document
import org.w3c.dom.HTMLElement
import org.jetbrains.compose.demo.falling.views.fallingBalls
import org.jetbrains.compose.demo.falling.Game
import androidx.compose.runtime.remember
import kotlinx.browser.window
import org.jetbrains.compose.web.css.Style
import org.jetbrains.compose.web.ui.Styles
class JsGame : Game() {
override fun now() = window.performance.now().toLong()
}
fun main() {
val root = document.getElementById("root") as HTMLElement
renderComposable(root = root) {
Style(Styles)
val game = remember {
JsGame().apply {
width = root.offsetWidth
height = root.offsetHeight
}
}
fallingBalls(game)
}
}

21
web/samples/falling_balls_with_web/src/jsMain/kotlin/modifiers/position.kt

@ -0,0 +1,21 @@
package org.jetbrains.compose.common.demo
import androidx.compose.runtime.Composable
import org.jetbrains.compose.common.ui.Modifier
import org.jetbrains.compose.common.foundation.layout.offset
import org.jetbrains.compose.common.ui.unit.Dp
import org.jetbrains.compose.common.internal.castOrCreate
import org.jetbrains.compose.web.css.top
import org.jetbrains.compose.web.css.left
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.css.position
import org.jetbrains.compose.web.css.Position
@Composable
actual fun Modifier.position(width: Dp, height: Dp): Modifier = castOrCreate().apply {
add {
position(Position.Absolute)
top(height.value.px)
left(width.value.px)
}
}

29
web/samples/falling_balls_with_web/src/jsMain/resources/index.html

@ -0,0 +1,29 @@
<!--
~ Copyright 2021 The Android Open Source Project
~
~ 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
~
~ http://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.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>compose-browser-with-web-demo</title>
<link type="text/css" rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script src="falling_balls_with_web.js">
</script>
</body>
</html>

8
web/samples/falling_balls_with_web/src/jsMain/resources/styles.css

@ -0,0 +1,8 @@
#root {
width: 100%;
height: 100vh;
}
#root > .compose-web-column > div {
position: relative;
}

24
web/samples/falling_balls_with_web/src/jvmMain/kotlin/App.kt

@ -0,0 +1,24 @@
package org.jetbrains.compose.common.demo
import androidx.compose.desktop.Window
import androidx.compose.ui.unit.IntSize
import org.jetbrains.compose.demo.falling.views.fallingBalls
import org.jetbrains.compose.demo.falling.Game
import androidx.compose.runtime.remember
class JvmGame : Game() {
override fun now() = System.nanoTime()
}
fun main() {
Window(title = "Demo", size = IntSize(600, 400)) {
fallingBalls(
remember {
JvmGame().apply {
width = 600
height = 400
}
}
)
}
}

14
web/samples/falling_balls_with_web/src/jvmMain/kotlin/modifiers/position.kt

@ -0,0 +1,14 @@
package org.jetbrains.compose.common.demo
import androidx.compose.runtime.Composable
import org.jetbrains.compose.common.ui.Modifier
import org.jetbrains.compose.common.foundation.layout.offset
import org.jetbrains.compose.common.ui.unit.Dp
import org.jetbrains.compose.common.internal.castOrCreate
import org.jetbrains.compose.common.ui.unit.implementation
import androidx.compose.foundation.layout.offset
@Composable
actual fun Modifier.position(width: Dp, height: Dp): Modifier = castOrCreate().apply {
modifier = modifier.offset(width.implementation, height.implementation)
}

15
web/samples/web-compose-bird/.gitignore vendored

@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
build/
/captures
.externalNativeBuild
.cxx

35
web/samples/web-compose-bird/README.md

@ -0,0 +1,35 @@
# 🐦 Compose Bird
![](demo.gif)
![latestVersion](https://img.shields.io/github/v/release/theapache64/compose-bird)
<a href="https://twitter.com/theapache64" target="_blank">
<img alt="Twitter: theapache64" src="https://img.shields.io/twitter/follow/theapache64.svg?style=social" />
</a>
> A flappy bird clone using Compose Web and radio buttons
## ▶ Play
- https://theapache64.github.io/compose-bird/
## 🏃 Run
```
./gradlew jsBrowserRun
```
## 📦 Distribute
```
./gradlew jsBrowserDistribution // and then open index.html (build/distributions)
```
## ✍ Author
👤 **theapache64**
* Twitter: <a href="https://twitter.com/theapache64" target="_blank">@theapache64</a>
* Email: theapache64@gmail.com
Feel free to ping me 😉

28
web/samples/web-compose-bird/build.gradle.kts

@ -0,0 +1,28 @@
// Add compose gradle plugin
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose")
}
group = "com.theapache64.composebird"
version = "1.0.0-alpha01"
// Add maven repositories
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(project(":web-core"))
implementation(compose.runtime)
}
}
}
}

BIN
web/samples/web-compose-bird/cover.jpeg

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

BIN
web/samples/web-compose-bird/demo.gif

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

2
web/samples/web-compose-bird/gradle.properties

@ -0,0 +1,2 @@
kotlin.code.style=official
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

BIN
web/samples/web-compose-bird/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
web/samples/web-compose-bird/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
web/samples/web-compose-bird/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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 UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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 "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
web/samples/web-compose-bird/gradlew.bat vendored

@ -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

8
web/samples/web-compose-bird/settings.gradle.kts

@ -0,0 +1,8 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
}
rootProject.name = "web-compose-bird"

157
web/samples/web-compose-bird/src/jsMain/kotlin/core/ComposeBirdGame.kt

@ -0,0 +1,157 @@
package core
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import data.GameFrame
import data.Tube
import kotlin.js.Date
/**
* Game logic
*/
class ComposeBirdGame : Game {
companion object {
const val COLUMNS = 15
const val ROWS = 9
const val BIRD_COLUMN = 1
private const val TUBES_START_FROM = (COLUMNS * 0.75).toInt()
const val TOTAL_TUBES = 10
private const val TUBE_HORIZONTAL_DISTANCE = 3
private const val TUBE_VERTICAL_DISTANCE = 3
private const val TUBE_WEIGHT = 500
private const val BIRD_WEIGHT = 300
}
private val tubeGapRange = TUBE_VERTICAL_DISTANCE until ROWS
private var tubeLastSteppedAt = 0.0
private var birdLastSteppedAt = 0.0
private var shouldMoveBirdUp = false
private val _gameFrame: MutableState<GameFrame> by lazy {
mutableStateOf(
// First frame
GameFrame(
birdPos = ROWS / 2,
tubes = buildLevel(),
isGameOver = false,
isGameWon = false,
score = 0
)
)
}
/**
* To build a random level
*/
private fun buildLevel(): List<Tube> {
return mutableListOf<Tube>().apply {
var tubesAdded = 0
var tubePosition = 0
while (tubesAdded < TOTAL_TUBES) {
if (tubePosition > TUBES_START_FROM && tubePosition % TUBE_HORIZONTAL_DISTANCE == 0) { // To give space to each tube
add(
Tube(
tubePosition,
buildRandomTube()
)
)
tubesAdded++
}
tubePosition++
}
}
}
/**
* To build a random vertical tube/pipe
*/
private fun buildRandomTube(): List<Boolean> {
// creating a full tube
val tube = mutableListOf<Boolean>().apply {
repeat(ROWS) {
add(true)
}
}
// Adding gaps in random middle positions to make it two tubes.
val gap1 = tubeGapRange.random()
repeat(TUBE_VERTICAL_DISTANCE) { index ->
tube[gap1 - index] = false
}
return tube
}
override val gameFrame: State<GameFrame> = _gameFrame
override fun step() {
update {
val now = Date().getTime()
// Stepping tube
val tubeDiff = now - tubeLastSteppedAt
val newTubes = if (tubeDiff > TUBE_WEIGHT) {
tubeLastSteppedAt = now
tubes.map {
it.copy(position = it.position - 1)
}
} else {
tubes
}
// Stepping bird position
val birdDiff = now - birdLastSteppedAt
val newBirdPos = when {
shouldMoveBirdUp -> {
birdLastSteppedAt = now
shouldMoveBirdUp = false
birdPos - 1 // move up
}
birdDiff > BIRD_WEIGHT -> {
birdLastSteppedAt = now
birdPos + 1 // move down
}
else -> {
birdPos
}
}
val newScore = newTubes.filter { it.position < BIRD_COLUMN }.size // All passed tube
val newIsGameWon = newScore >= TOTAL_TUBES // If all tubes passed
// Checking if bird gone out
val newIsGameOver = if (newBirdPos < 0 || newBirdPos >= ROWS || isCollidedWithTube(newBirdPos, tubes)) {
true
} else {
isGameOver
}
copy(
isGameOver = newIsGameOver,
tubes = newTubes,
birdPos = newBirdPos,
score = newScore,
isGameWon = newIsGameWon
)
}
}
/**
* To check if the bird collided with the tube (collision-detection)
*/
private fun isCollidedWithTube(newBirdPos: Int, tubes: List<Tube>): Boolean {
val birdTube = tubes.find { it.position == BIRD_COLUMN }
return birdTube?.coordinates?.get(newBirdPos) ?: false
}
override fun moveBirdUp() {
shouldMoveBirdUp = true
}
private inline fun update(func: GameFrame.() -> GameFrame) {
_gameFrame.value = _gameFrame.value.func()
}
}

13
web/samples/web-compose-bird/src/jsMain/kotlin/core/Game.kt

@ -0,0 +1,13 @@
package core
import androidx.compose.runtime.State
import data.GameFrame
/**
* A generic game interface
*/
interface Game {
val gameFrame: State<GameFrame>
fun step()
fun moveBirdUp()
}

9
web/samples/web-compose-bird/src/jsMain/kotlin/data/GameFrame.kt

@ -0,0 +1,9 @@
package data
data class GameFrame(
val birdPos: Int,
val tubes: List<Tube>,
val isGameOver: Boolean,
val isGameWon : Boolean,
val score: Int,
)

6
web/samples/web-compose-bird/src/jsMain/kotlin/data/Tube.kt

@ -0,0 +1,6 @@
package data
data class Tube(
var position: Int,
val coordinates: List<Boolean>
)

140
web/samples/web-compose-bird/src/jsMain/kotlin/main.kt

@ -0,0 +1,140 @@
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import core.ComposeBirdGame
import core.Game
import data.GameFrame
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.coroutines.delay
import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.attributes.checked
import org.jetbrains.compose.web.attributes.disabled
import org.jetbrains.compose.web.css.marginTop
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.renderComposable
import org.w3c.dom.HTMLElement
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.get
fun main() {
val game: Game = ComposeBirdGame()
val body = document.getElementsByTagName("body")[0] as HTMLElement
// Enabling keyboard control
body.addEventListener("keyup", {
when ((it as KeyboardEvent).keyCode) {
38 -> { // Arrow up
game.moveBirdUp()
}
}
})
renderComposable(rootElementId = "root") {
Div(
attrs = {
style {
property("text-align", "center")
}
}
) {
// The current frame!
val gameFrame by game.gameFrame
// Igniting the game loop
LaunchedEffect(Unit) {
while (!gameFrame.isGameOver) {
delay(60)
game.step()
}
}
Header(gameFrame)
Div(
attrs = {
style {
marginTop(30.px)
}
}
) {
if (gameFrame.isGameOver || gameFrame.isGameWon) {
GameResult(gameFrame)
} else {
// Play area
repeat(ComposeBirdGame.ROWS) { rowIndex ->
Div {
repeat(ComposeBirdGame.COLUMNS) { columnIndex ->
Input(
InputType.Radio,
attrs = {
val tube = gameFrame.tubes.find { it.position == columnIndex }
val isTube = tube?.coordinates?.get(rowIndex) ?: false
val isBird =
!isTube && columnIndex == ComposeBirdGame.BIRD_COLUMN && rowIndex == gameFrame.birdPos
if (isTube || isBird) {
// if it's either a tube node or bird, check it
checked()
}
if (!isBird) {
// if it's a bird, enable it. (to change to blue color)
disabled()
}
}
)
}
}
}
}
}
}
}
}
@Composable
private fun Header(gameFrame: GameFrame) {
// Game title
H1 {
Text(value = "🐦 Compose Bird!")
}
// Game score
Text(value = "Your Score: ${gameFrame.score} || Top Score: ${ComposeBirdGame.TOTAL_TUBES}")
}
@Composable
private fun GameResult(gameFrame: GameFrame) {
// Game Status
H2 {
if (gameFrame.isGameWon) {
Text("🚀 Won the game! 🚀")
} else {
// core.Game over
Text("💀 Game Over 💀")
}
}
// Try Again
Button(
attrs = {
onClick {
window.location.reload()
}
}
) {
Text("Try Again!")
}
}

17
web/samples/web-compose-bird/src/jsMain/resources/index.html

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>compose-bird</title>
<style>
input[type=radio]{
width:25px;
height:25px;
}
</style>
</head>
<body>
<div id="root"></div>
<script src="web-compose-bird.js"></script>
</body>
</html>

3
web/samples/web-getting-started/.gitignore vendored

@ -0,0 +1,3 @@
/.gradle/
/.idea/
/build/

4
web/samples/web-getting-started/README.md

@ -0,0 +1,4 @@
### Running web application
```
./gradlew jsBrowserRun
```

24
web/samples/web-getting-started/build.gradle.kts

@ -0,0 +1,24 @@
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose")
}
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(project(":web-core"))
implementation(compose.runtime)
}
}
}
}

1
web/samples/web-getting-started/gradle.properties

@ -0,0 +1 @@
kotlin.code.style=official

BIN
web/samples/web-getting-started/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
web/samples/web-getting-started/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
web/samples/web-getting-started/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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 UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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 "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
web/samples/web-getting-started/gradlew.bat vendored

@ -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

9
web/samples/web-getting-started/settings.gradle.kts

@ -0,0 +1,9 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
}
rootProject.name = "web-getting-started"

34
web/samples/web-getting-started/src/jsMain/kotlin/Main.kt

@ -0,0 +1,34 @@
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import org.jetbrains.compose.web.css.padding
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.dom.Button
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Span
import org.jetbrains.compose.web.dom.Text
import org.jetbrains.compose.web.renderComposable
fun main() {
var count: Int by mutableStateOf(0)
renderComposable(rootElementId = "root") {
Div({ style { padding(25.px) } }) {
Button(attrs = {
onClick { count -= 1 }
}) {
Text("-")
}
Span({style { padding(15.px) }}) {
Text("$count")
}
Button({
onClick { count += 1 }
}) {
Text("+")
}
}
}
}

11
web/samples/web-getting-started/src/jsMain/resources/index.html

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Getting Started</title>
</head>
<body>
<div id="root"></div>
<script src="web-getting-started.js"></script>
</body>
</html>

3
web/samples/web-with-react/.gitignore vendored

@ -0,0 +1,3 @@
/.gradle/
/.idea/
/build/

24
web/samples/web-with-react/README.md

@ -0,0 +1,24 @@
### Use Compose(web) in React app
[see ComposeInReactApp.kt](src/jsMain/kotlin/ComposeInReactApp.kt)
`useCompose(...)` is a custom React effect to render a content using Compose.
It's not a part of any library.
### Use React in Compose(web) app
`UseReactEffect(...)` is a custom Compose effect to render a content using React.
It's not a part of any library.
[see ReactInComposeApp.kt](src/jsMain/kotlin/ReactInComposeApp.kt)
### How to use existing React components:
It requires adding `external` declarations. For example: [ReactYoutubePlayer.kt](src/jsMain/kotlin/ReactYoutubePlayer.kt)
Here is a good tutorial - [Using packages from NPM](https://play.kotlinlang.org/hands-on/Building%20Web%20Applications%20with%20React%20and%20Kotlin%20JS/07_Using_Packages_From_NPM)
### Running web application
```
./gradlew jsBrowserRun
```

31
web/samples/web-with-react/build.gradle.kts

@ -0,0 +1,31 @@
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose")
}
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/kotlin-js-wrappers")
}
kotlin {
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(project(":web-core"))
implementation(compose.runtime)
implementation("org.jetbrains.kotlin-wrappers:kotlin-react:17.0.2-pre.201-kotlin-1.5.0")
implementation("org.jetbrains.kotlin-wrappers:kotlin-react-dom:17.0.2-pre.201-kotlin-1.5.0")
implementation("org.jetbrains.kotlin-wrappers:kotlin-styled:5.3.0-pre.201-kotlin-1.5.0")
implementation(npm("react", "17.0.2"))
implementation(npm("react-dom", "17.0.2"))
implementation(npm("react-youtube-lite", "1.0.1"))
}
}
}
}

1
web/samples/web-with-react/gradle.properties

@ -0,0 +1 @@
kotlin.code.style=official

BIN
web/samples/web-with-react/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
web/samples/web-with-react/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
web/samples/web-with-react/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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 UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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 "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
web/samples/web-with-react/gradlew.bat vendored

@ -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

9
web/samples/web-with-react/settings.gradle.kts

@ -0,0 +1,9 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
}
rootProject.name = "web-with-react"

149
web/samples/web-with-react/src/jsMain/kotlin/ComposeInReactApp.kt

@ -0,0 +1,149 @@
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Text
import org.jetbrains.compose.web.renderComposable
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.css.*
import kotlinx.html.InputType
import kotlinx.html.js.onClickFunction
import kotlinx.html.js.onInputFunction
import org.w3c.dom.HTMLElement
import react.*
import react.dom.*
import styled.css
import styled.styledDiv
@Composable
private fun ComposableComponentToUseInReact(count: State<Int>) {
repeat(count.value) {
Div {
Text("Item $it")
}
}
}
/**
* @param containerRef - [RMutableRef] - reference to the HTMLElement that is used as a root for Composition
* @param stateInitialValue - initial state value for the Composition
* @param stateValueProvider - a lambda that's used to change the state's value
* @param composable - the content controlled by Compose and mounted in a root provided by [containerRef]
*/
private fun <T> useCompose(
containerRef: RMutableRef<HTMLElement>,
stateInitialValue: T,
stateValueProvider: () -> T,
composable: @Composable (state: State<T>) -> Unit
) {
val mutableState = useRef(mutableStateOf(stateInitialValue))
useEffect {
mutableState.current?.value = stateValueProvider()
}
useLayoutEffectWithCleanup(dependencies = emptyList()) {
val composition = renderComposable(containerRef.current!!) {
composable(mutableState.current!!)
}
return@useLayoutEffectWithCleanup {
composition.dispose()
}
}
}
private external interface ListProps : RProps {
var countOfItems: Int
}
private val composeListComponentWrapper = functionalComponent<ListProps> { props ->
val containerRef = useRef<HTMLElement>(null)
useCompose(
containerRef = containerRef,
stateInitialValue = 0,
stateValueProvider = { props.countOfItems }
) {
ComposableComponentToUseInReact(it)
}
// This div will be a root for the Composition managed by Compose
div { ref { containerRef.current = it } }
}
private val column = functionalComponent<RProps> {
val (counter, setCounter) = useState(0)
styledDiv {
css {
padding = "25px"
}
h3 {
+"Update items count using slider:"
}
input(type = InputType.range) {
attrs {
onInputFunction = {
setCounter(it.target?.asDynamic().value.toString().toInt())
}
value = "$counter"
}
}
h3 {
+"Compose controlled items:"
}
child(composeListComponentWrapper) {
this.attrs {
countOfItems = counter
}
}
}
}
private val appContent = functionalComponent<RProps> {
val (columnsCount, setColumnsCount) = useState(3)
a(href = "${window.location.origin}?app=composeApp") {
+"GO TO REACT IN COMPOSE EXAMPLE"
}
button {
attrs {
onClickFunction = {
setColumnsCount(columnsCount - 1)
}
}
+"Remove column"
}
button {
attrs {
onClickFunction = {
setColumnsCount(columnsCount + 1)
}
}
+"Add column"
}
styledDiv {
css {
display = Display.flex
flexDirection = FlexDirection.row
}
repeat(columnsCount) {
child(column)
}
}
}
fun composeInReactAppExample() {
render(document.getElementById("root")) {
child(appContent)
}
}

14
web/samples/web-with-react/src/jsMain/kotlin/Main.kt

@ -0,0 +1,14 @@
import kotlinx.browser.window
import org.w3c.dom.url.URLSearchParams
fun main() {
val urlParams = URLSearchParams(window.location.search)
val app = urlParams.get("app") ?: "composeApp"
when (app) {
"composeApp" -> reactInComposeAppExample()
"reactApp" -> composeInReactAppExample()
}
}

94
web/samples/web-with-react/src/jsMain/kotlin/ReactInComposeApp.kt

@ -0,0 +1,94 @@
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import org.jetbrains.compose.web.css.margin
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.css.width
import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.renderComposable
import kotlinx.browser.window
import org.w3c.dom.HTMLElement
import react.RBuilder
import react.dom.render
import react.dom.unmountComponentAtNode
/**
* @param key - when UseReactEffect is invoked with a new [key], compose forces react to render with a new content.
* @param content - the builder for the content managed by React
*/
@Composable
private fun ElementScope<HTMLElement>.UseReactEffect(
key: Any?,
content: RBuilder.() -> Unit
) {
DomSideEffect(key = key) { htmlElement ->
render(htmlElement) {
content()
}
}
DisposableRefEffect { htmlElement ->
onDispose {
unmountComponentAtNode(htmlElement)
}
}
}
@Composable
fun YoutubeReactPlayerWrapper(videoUrl: String) {
if (videoUrl.isEmpty()) return
Div({
style {
width(50.percent)
}
}) {
UseReactEffect(key = videoUrl) {
reactPlayer {
attrs.url = videoUrl
}
}
}
}
private val videos = listOf(
"https://www.youtube.com/watch?v=UryyHq45Y_8",
"https://www.youtube.com/watch?v=698I_AH8h6s",
"https://www.youtube.com/watch?v=F8jj7e-_jFA"
)
fun reactInComposeAppExample() {
var videoUrl by mutableStateOf("")
renderComposable(rootElementId = "root") {
A(href = "${window.location.origin}?app=reactApp") { Text("GO TO COMPOSE IN REACT EXAMPLE") }
Div {
videos.forEachIndexed { ix, url ->
Button(
attrs = {
onClick { videoUrl = url }
style {
margin(10.px)
}
}
) { Text("Video ${ix + 1}") }
}
Button(
attrs = {
onClick {
videoUrl = ""
style {
margin(10.px)
}
}
},
) { Text("Reset") }
YoutubeReactPlayerWrapper(videoUrl)
}
}
}

11
web/samples/web-with-react/src/jsMain/kotlin/ReactYoutubePlayer.kt

@ -0,0 +1,11 @@
@file:JsModule("react-youtube-lite")
@file:JsNonModule
import react.*
@JsName("ReactYouTubeLite")
external val reactPlayer: RClass<ReactYouTubeProps>
external interface ReactYouTubeProps : RProps {
var url: String
}

11
web/samples/web-with-react/src/jsMain/resources/index.html

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Compose for Web: with react component</title>
</head>
<body>
<div id="root"></div>
<script src="web-with-react.js"></script>
</body>
</html>

15
web/samples/web_landing/.gitignore vendored

@ -0,0 +1,15 @@
*.iml
.gradle
/local.properties
/.idea
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
build/
/captures
.externalNativeBuild
.cxx

26
web/samples/web_landing/build.gradle.kts

@ -0,0 +1,26 @@
plugins {
kotlin("multiplatform") version "1.5.21"
id("org.jetbrains.compose")
}
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
js(IR) {
browser()
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(npm("highlight.js", "10.7.2"))
implementation(project(":web-core"))
implementation(compose.runtime)
}
}
}
}

1
web/samples/web_landing/gradle.properties

@ -0,0 +1 @@
kotlin.code.style=official

BIN
web/samples/web_landing/gradle/wrapper/gradle-wrapper.jar vendored

Binary file not shown.

5
web/samples/web_landing/gradle/wrapper/gradle-wrapper.properties vendored

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

185
web/samples/web_landing/gradlew vendored

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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 UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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 "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
web/samples/web_landing/gradlew.bat vendored

@ -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

201
web/samples/web_landing/license/LICENSE.txt

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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
http://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.

5
web/samples/web_landing/license/third_party/README.md vendored

@ -0,0 +1,5 @@
Following third-party dependencies exist in web_landing:
* highlight.js@10.7.2:
* BSD 3-Clause License: [highlight.js](highlightjs.txt)
* https://github.com/highlightjs/highlight.js/blob/main/LICENSE

29
web/samples/web_landing/license/third_party/highlightjs.txt vendored

@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2006, Ivan Sagalaev.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

10
web/samples/web_landing/settings.gradle.kts

@ -0,0 +1,10 @@
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
maven { url = uri("https://maven.pkg.jetbrains.space/public/p/compose/dev") }
}
}
rootProject.name = "compose-web-lp"

12
web/samples/web_landing/src/jsMain/kotlin/com/sample/HighlightJs.kt

@ -0,0 +1,12 @@
package com.sample
import org.w3c.dom.HTMLElement
@JsName("hljs")
@JsModule("highlight.js")
@JsNonModule
external class HighlightJs {
companion object {
fun highlightElement(block: HTMLElement)
}
}

27
web/samples/web_landing/src/jsMain/kotlin/com/sample/Main.kt

@ -0,0 +1,27 @@
package com.sample
import org.jetbrains.compose.web.css.Style
import org.jetbrains.compose.web.renderComposable
import com.sample.components.*
import com.sample.content.*
import com.sample.style.AppStylesheet
import org.w3c.dom.HTMLElement
fun main() {
renderComposable(rootElementId = "root") {
Style(AppStylesheet)
Layout {
Header()
MainContentLayout {
Intro()
ComposeWebLibraries()
GetStarted()
CodeSamples()
JoinUs()
}
PageFooter()
}
}
}

80
web/samples/web_landing/src/jsMain/kotlin/com/sample/components/Card.kt

@ -0,0 +1,80 @@
package com.sample.components
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.style.*
data class LinkOnCard(val linkText: String, val linkUrl: String)
@Composable
private fun CardTitle(title: String, darkTheme: Boolean = false) {
H3({
classes(WtTexts.wtH3)
if (darkTheme) {
classes(WtTexts.wtH3ThemeDark)
}
}) {
Text(title)
}
}
@Composable
private fun CardLink(link: LinkOnCard) {
A(
attrs = {
classes(WtTexts.wtLink, WtOffsets.wtTopOffset24)
target(ATarget.Blank)
},
href = link.linkUrl
) {
Text(link.linkText)
}
}
@Composable
fun Card(
title: String,
links: List<LinkOnCard>,
darkTheme: Boolean = false,
wtExtraStyleClasses: List<String> = listOf(WtCols.wtCol6, WtCols.wtColMd6, WtCols.wtColSm12),
content: @Composable () -> Unit
) {
Div({
classes(WtCards.wtCard, WtOffsets.wtTopOffset24, *wtExtraStyleClasses.toTypedArray())
classes(if (darkTheme) WtCards.wtCardThemeDark else WtCards.wtCardThemeLight)
}) {
Div({
classes(WtCards.wtCardSection, WtCards.wtVerticalFlex)
}) {
Div({ classes(WtCards.wtVerticalFlexGrow) }) {
CardTitle(title = title, darkTheme = darkTheme)
content()
}
links.forEach {
CardLink(it)
}
}
}
}
@Composable
fun CardDark(
title: String,
links: List<LinkOnCard>,
wtExtraStyleClasses: List<String> = listOf(WtCols.wtCol6, WtCols.wtColMd6, WtCols.wtColSm12),
content: @Composable () -> Unit
) {
Card(
title = title,
links = links,
darkTheme = true,
wtExtraStyleClasses = wtExtraStyleClasses,
content = content
)
}

54
web/samples/web_landing/src/jsMain/kotlin/com/sample/components/Layout.kt

@ -0,0 +1,54 @@
package com.sample.components
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Main
import org.jetbrains.compose.web.dom.Section
import com.sample.style.WtContainer
import com.sample.style.WtOffsets
import com.sample.style.WtSections
@Composable
fun Layout(content: @Composable () -> Unit) {
Div({
style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
height(100.percent)
margin(0.px)
property("box-sizing", "border-box")
}
}) {
content()
}
}
@Composable
fun MainContentLayout(content: @Composable () -> Unit) {
Main({
style {
property("flex", "1 0 auto")
property("box-sizing", "border-box")
}
}) {
content()
}
}
@Composable
fun ContainerInSection(sectionThemeStyleClass: String? = null, content: @Composable () -> Unit) {
Section({
if (sectionThemeStyleClass != null) {
classes(WtSections.wtSection, sectionThemeStyleClass)
} else {
classes(WtSections.wtSection)
}
}) {
Div({
classes(WtContainer.wtContainer, WtOffsets.wtTopOffset96)
}) {
content()
}
}
}

96
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/AboutComposeWebLibsSection.kt

@ -0,0 +1,96 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.css.value
import org.jetbrains.compose.web.dom.*
import com.sample.components.Card
import com.sample.components.ContainerInSection
import com.sample.components.LinkOnCard
import com.sample.style.*
data class CardWithListPresentation(
val title: String,
val list: List<String>,
val links: List<LinkOnCard> = emptyList()
)
private fun createAboutComposeWebCards(): List<CardWithListPresentation> {
return listOf(
CardWithListPresentation(
title = "Composable DOM API",
list = listOf(
"Express your design and layout in terms of DOM elements and HTML tags",
"Use a type-safe HTML DSL to build your UI representation",
"Get full control over the look and feel of your application by creating stylesheets with a typesafe CSS DSL",
"Integrate with other JavaScript libraries via DOM subtrees"
)
),
CardWithListPresentation(
title = "Multiplatform Widgets With Web Support",
list = listOf(
"Use and build Compose widgets that work on Android, Desktop, and Web by utilizing Kotlin's expect-actual mechanisms to provide platform-specific implementations",
"Experiment with a set of layout primitives and APIs that mimic the features you already know from Compose for Desktop and Android"
)
)
)
}
@Composable
fun ComposeWebLibraries() {
ContainerInSection(WtSections.wtSectionBgGrayLight) {
H2(attrs = { classes(WtTexts.wtH2) }) {
Text("Building user interfaces with Compose for Web")
}
Div(attrs = {
classes(WtRows.wtRow, WtRows.wtRowSizeM)
}) {
Div(attrs = {
classes(WtCols.wtCol6, WtCols.wtColMd6, WtCols.wtColSm12, WtOffsets.wtTopOffset24)
}) {
P(attrs = {
classes(WtTexts.wtText1)
}) {
Text("Compose for Web allows you to build reactive user interfaces for the web in Kotlin, using the concepts and APIs of Jetpack Compose to express the state, behavior, and logic of your application.")
}
}
Div(attrs = {
classes(WtCols.wtCol6, WtCols.wtColMd6, WtCols.wtColSm12, WtOffsets.wtTopOffset24)
}) {
P(attrs = {
classes(WtTexts.wtText1)
}) {
Text("Compose for Web provides multiple ways of declaring user interfaces in Kotlin code, allowing you to have full control over your website layout with a declarative DOM API, or use versions of the widgets you already know from Jetpack Compose for Desktop and Android.\n")
}
}
}
Div(attrs = {
classes(WtRows.wtRow, WtRows.wtRowSizeM, WtOffsets.wtTopOffset48)
}) {
createAboutComposeWebCards().forEach { CardWithList(it) }
}
}
}
@Composable
private fun CardWithList(card: CardWithListPresentation) {
Card(
title = card.title,
links = card.links
) {
Ul(attrs = {
classes(WtTexts.wtText2)
}) {
card.list.forEachIndexed { _, it ->
Li({
style {
property("padding-top", 24.px)
}
}) { Text(it) }
}
}
}
}

90
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/CodeSamplesSwitcher.kt

@ -0,0 +1,90 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.InputType
import org.jetbrains.compose.web.attributes.checked
import org.jetbrains.compose.web.attributes.name
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.selectors.CSSSelector
import org.jetbrains.compose.web.css.selectors.descendant
import org.jetbrains.compose.web.css.selectors.selector
import org.jetbrains.compose.web.dom.Form
import org.jetbrains.compose.web.dom.Input
import org.jetbrains.compose.web.dom.Label
import org.jetbrains.compose.web.dom.Text
import com.sample.style.AppStylesheet
import org.jetbrains.compose.web.attributes.value
private object SwitcherVariables {
val labelWidth by variable<CSSpxValue>()
val labelPadding by variable<CSSpxValue>()
}
object SwitcherStylesheet : StyleSheet(AppStylesheet) {
val boxed by style {
media(mediaMaxWidth(640.px)) {
self style {
SwitcherVariables.labelWidth(48.px)
SwitcherVariables.labelPadding(5.px)
}
}
descendant(self, CSSSelector.Type("label")) style {
display(DisplayStyle.InlineBlock)
property("width", SwitcherVariables.labelWidth.value(56.px))
property("padding", SwitcherVariables.labelPadding.value(10.px))
property("transition", "all 0.3s")
property("text-align", "center")
property("box-sizing", "border-box")
border {
style(LineStyle.Solid)
width(3.px)
color(Color("transparent"))
borderRadius(20.px, 20.px, 20.px)
}
color(Color("#aaa"))
}
border {
style(LineStyle.Solid)
width(1.px)
color(Color("#aaa"))
padding(0.px)
borderRadius(22.px, 22.px, 22.px)
}
descendant(self, selector("input[type=\"radio\"]")) style {
display(DisplayStyle.None)
}
descendant(self, selector("input[type=\"radio\"]:checked + label")) style {
border {
style(LineStyle.Solid)
width(3.px)
color(Color("#167dff"))
borderRadius(20.px, 20.px, 20.px)
}
color(Color("#000"))
}
}
}
@Composable
fun CodeSampleSwitcher(count: Int, current: Int, onSelect: (Int) -> Unit) {
Form(attrs = {
classes(SwitcherStylesheet.boxed)
}) {
repeat(count) { ix ->
Input(type = InputType.Radio, attrs = {
name("code-snippet")
value("snippet$ix")
id("snippet$ix")
if (current == ix) checked()
onChange { onSelect(ix) }
})
Label(forId = "snippet$ix") { Text("${ix + 1}") }
}
}
}

276
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/CodeSnippets.kt

@ -0,0 +1,276 @@
package com.sample.content
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.HighlightJs
import com.sample.components.ContainerInSection
import com.sample.style.*
import org.jetbrains.compose.web.css.keywords.auto
import org.w3c.dom.HTMLElement
private fun HTMLElement.setHighlightedCode(code: String) {
innerText = code
HighlightJs.highlightElement(this)
}
private val SimpleCounterSnippet = CodeSnippetData(
title = "Simple Counter using Composable DOM",
source = """
fun main() {
val count = mutableStateOf(0)
renderComposable(rootElementId = "root") {
Button(attrs = {
onClick { count.value = count.value - 1 }
}) {
Text("-")
}
Span(attrs = { style { padding(15.px) }}) { /* we use inline style here */
Text("${"$"}{count.value}")
}
Button(attrs = {
onClick { count.value = count.value + 1 }
}) {
Text("+")
}
}
}
""".trimIndent()
)
private val DeclareAndUseStylesheet = CodeSnippetData(
title = "Declare and use a stylesheet",
source = """
object MyStyleSheet : StyleSheet() {
val container by style { /* define a class `container` */
border(1.px, LineStyle.Solid, Color.RGB(255, 0, 0))
}
}
@Composable
fun MyComponent() {
Div(attrs = {
classes(MyStyleSheet.container) /* use `container` class */
}) {
Text("Hello world!")
}
}
fun main() {
renderComposable(rootElementId = "root") {
Style(MyStyleSheet) /* mount the stylesheet */
MyComponent()
}
}
""".trimIndent()
)
private val DeclareAndUseCssVariable = CodeSnippetData(
title = "Declare and use CSS variables",
source = """
object MyVariables : CSSVariables {
val contentBackgroundColor by variable<Color>() /* declare a variable */
}
object MyStyleSheet: StyleSheet() {
val container by style {
MyVariables.contentBackgroundColor(Color("blue")) /* set its value */
}
val content by style {
backgroundColor(MyVariables.contentBackgroundColor.value()) /* use it */
}
}
@Composable
fun MyComponent() {
Div(attrs = {
classes(MyStyleSheet.container)
}) {
Span(attrs = {
classes(MyStyleSheet.content)
}) {
Text("Hello world!")
}
}
}
""".trimIndent()
)
private val HoverSelectorAndMedia = CodeSnippetData(
title = "Hover selector and media query examples",
source = """
object MyStyleSheet: StyleSheet() {
val container by style {
backgroundColor(Color("blue"))
padding(20.px)
hover(self) style { /* `self` is a reference to the class */
backgroundColor(Color("red"))
}
media(maxWidth(500.px)) {
self style {
padding(10.px)
}
}
}
}
""".trimIndent()
)
private val DefineCssClassInComponent = CodeSnippetData(
title = "Define a CSS class in a component",
source = """
object MyStyleSheet: StyleSheet() {}
@Composable
fun MyComponent() {
Div(attrs = {
/* the class name will be generated at runtime */
classes(MyStyleSheet.css {
backgroundColor(Color("blue"))
self + ":hover" style { /* this is an example of a raw selector */
backgroundColor(Color("red"))
}
})
}) {
Text("Hello world!")
}
}
""".trimIndent()
)
private val LayoutsSample = CodeSnippetData(
title = "Counter for Web and Desktop",
source = """
/* Shared code in commonMain - App.kt (No direct control over DOM or CSS here) */
private val counter = mutableStateOf(0)
@Composable
fun App() {
Row {
Button(onClick = { counter.value = counter.value - 1 }) {
Text("-")
}
Text("${"$"}{counter.value}", modifier = Modifier.padding(16.dp))
Button(onClick = { counter.value = counter.value + 1 }) {
Text("+")
}
}
}
/* Desktop specific code in desktopMain: */
fun main() = Window(title = "Demo", size = IntSize(800, 800)) {
App()
}
/* Web specific code in jsMain: */
fun main() = renderComposable(rootElementId = "root") {
App()
}
""".trimIndent()
)
private val allSnippets = arrayOf(
SimpleCounterSnippet,
DeclareAndUseStylesheet,
DeclareAndUseCssVariable,
HoverSelectorAndMedia,
DefineCssClassInComponent,
LayoutsSample
)
private var currentCodeSnippet: CodeSnippetData by mutableStateOf(allSnippets[0])
private var selectedSnippetIx: Int by mutableStateOf(0)
@Composable
fun CodeSamples() {
ContainerInSection {
Div({
classes(WtRows.wtRow)
style {
justifyContent(JustifyContent.SpaceBetween)
}
}) {
Div({ classes(WtCols.wtCol6, WtCols.wtColMd4, WtCols.wtColSm12) }) {
H1({
classes(WtTexts.wtH2)
}) {
Text("Code samples")
}
}
Div({ classes(WtOffsets.wtTopOffsetSm24) }) {
CodeSampleSwitcher(count = allSnippets.size, current = selectedSnippetIx) {
selectedSnippetIx = it
currentCodeSnippet = allSnippets[it]
}
}
}
TitledCodeSample(title = currentCodeSnippet.title, code = currentCodeSnippet.source)
}
}
@Composable
private fun TitledCodeSample(title: String, code: String) {
H3({
classes(WtTexts.wtH3, WtOffsets.wtTopOffset48)
}) {
Text(title)
}
Div({
classes(WtOffsets.wtTopOffset24)
style {
backgroundColor(rgba(39, 40, 44, 0.05))
borderRadius(8.px, 8.px, 8.px)
property("padding", "12px 16px")
}
}) {
FormattedCodeSnippet(code = code)
}
}
@Composable
fun FormattedCodeSnippet(code: String, language: String = "kotlin") {
Pre({
style {
property("max-height", 25.em)
property("overflow", "auto")
height(auto)
}
}) {
Code({
classes("language-$language", "hljs")
style {
property("font-family", "'JetBrains Mono', monospace")
property("tab-size", 4)
fontSize(10.pt)
backgroundColor(Color("transparent"))
}
}) {
DomSideEffect(code) {
it.setHighlightedCode(code)
}
}
}
}
private data class CodeSnippetData(
val title: String,
val source: String
)

113
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/Footer.kt

@ -0,0 +1,113 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.style.*
@Composable
fun PageFooter() {
Footer({
style {
flexShrink(0)
property("box-sizing", "border-box")
}
}) {
Section({
classes(WtSections.wtSectionBgGrayDark)
style {
property("padding", "24px 0")
}
}) {
Div({ classes(WtContainer.wtContainer) }) {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeM, WtRows.wtRowSmAlignItemsCenter)
style {
justifyContent(JustifyContent.Center)
flexWrap(FlexWrap.Wrap)
}
}) {
Div({
classes(WtCols.wtColInline)
}) {
P({
classes(WtTexts.wtText1, WtTexts.wtText1ThemeDark)
}) {
Text("Follow us")
}
}
Div({
classes(WtCols.wtColInline)
}) {
getSocialLinks().forEach { SocialIconLink(it) }
}
}
CopyrightInFooter()
}
}
}
}
@Composable
private fun CopyrightInFooter() {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeM, WtRows.wtRowSmAlignItemsCenter, WtOffsets.wtTopOffset48)
style {
justifyContent(JustifyContent.SpaceEvenly)
flexWrap(FlexWrap.Wrap)
property("padding", "0px 12px")
}
}) {
Span({
classes(WtTexts.wtText3, WtTexts.wtTextPale)
}) {
Text("Copyright © 2000-2021 JetBrains s.r.o.")
}
Span({
classes(WtTexts.wtText3, WtTexts.wtTextPale)
}) {
Text("Developed with drive and IntelliJ IDEA")
}
}
}
@Composable
private fun SocialIconLink(link: SocialLink) {
A(attrs = {
classes(WtTexts.wtSocialButtonItem)
target(ATarget.Blank)
}, href = link.url) {
Img(src = link.iconSvg) {}
}
}
private data class SocialLink(
val id: String,
val url: String,
val title: String,
val iconSvg: String
)
private fun getSocialLinks(): List<SocialLink> {
return listOf(
SocialLink("facebook", "https://www.facebook.com/JetBrains", "JetBrains on Facebook", "ic_fb.svg"),
SocialLink("twitter", "https://twitter.com/jetbrains", "JetBrains on Twitter", "ic_twitter.svg"),
SocialLink(
"linkedin",
"https://www.linkedin.com/company/jetbrains",
"JetBrains on Linkedin",
"ic_linkedin.svg"
),
SocialLink("youtube", "https://www.youtube.com/user/JetBrainsTV", "JetBrains on YouTube", "ic_youtube.svg"),
SocialLink("instagram", "https://www.instagram.com/jetbrains/", "JetBrains on Instagram", "ic_insta.svg"),
SocialLink("blog", "https://blog.jetbrains.com/", "JetBrains blog", "ic_jb_blog.svg"),
SocialLink("rss", "https://blog.jetbrains.com/feed/", "JetBrains RSS Feed", "ic_feed.svg"),
)
}

107
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/GetStartedSection.kt

@ -0,0 +1,107 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.components.CardDark
import com.sample.components.ContainerInSection
import com.sample.components.LinkOnCard
import com.sample.style.*
private data class GetStartedCardPresentation(
val title: String,
val content: String,
val links: List<LinkOnCard>
)
private fun getCards(): List<GetStartedCardPresentation> {
return listOf(
GetStartedCardPresentation(
title = "Start tutorial here",
content = "In this tutorial we will see how to create our first web UI application using Compose for Web.",
links = listOf(
LinkOnCard(
linkText = "View tutorial",
linkUrl = "https://github.com/JetBrains/compose-jb/tree/master/tutorials/Web/Getting_Started"
)
)
),
GetStartedCardPresentation(
title = "Landing page example",
content = "An example of a landing page built using the Composable DOM API and Stylesheet DSL.",
links = listOf(
LinkOnCard(
linkText = "Explore the source code",
linkUrl = "https://github.com/JetBrains/compose-jb/tree/master/examples/web_landing"
)
)
),
GetStartedCardPresentation(
title = "Falling Balls app example",
content = "This example demonstrates the use of multiplatform widgets – sharing user interface code between Compose for Desktop and Web.",
links = listOf(
LinkOnCard(
linkText = "Explore the source code",
linkUrl = "https://github.com/JetBrains/compose-jb/tree/master/examples/falling_balls_with_web"
),
LinkOnCard(
linkText = "Play",
linkUrl = "https://falling-balls.ui.pages.jetbrains.team/"
)
)
)
)
}
@Composable
private fun CardContent(text: String) {
P(attrs = {
classes(WtTexts.wtText2, WtTexts.wtText2ThemeDark, WtOffsets.wtTopOffset24)
}) {
Text(text)
}
}
@Composable
fun GetStarted() {
ContainerInSection(WtSections.wtSectionBgGrayDark) {
H1(attrs = {
classes(WtTexts.wtH2, WtTexts.wtH2ThemeDark)
}) {
Text("Try out the Compose for Web")
}
Div(attrs = {
classes(WtRows.wtRowSizeM, WtRows.wtRow, WtOffsets.wtTopOffset24)
}) {
Div(attrs = {
classes(WtCols.wtCol6, WtCols.wtColMd10, WtCols.wtColSm12, WtOffsets.wtTopOffset24)
}) {
P(attrs = {
classes(WtTexts.wtText1)
style {
color(Color("#fff"))
}
}) {
Text("Ready for your next adventure? Learn how to build reactive user interfaces with Compose for Web.")
}
}
}
Div(
attrs = {
classes(WtRows.wtRow, WtRows.wtRowSizeM, WtOffsets.wtTopOffset24)
}
) {
getCards().forEach {
CardDark(
title = it.title,
links = it.links,
wtExtraStyleClasses = listOf(WtCols.wtCol4, WtCols.wtColMd6, WtCols.wtColSm12)
) {
CardContent(it.content)
}
}
}
}
}

59
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/Header.kt

@ -0,0 +1,59 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.style.*
import kotlinx.browser.window
@Composable
fun Header() {
Section(attrs = {
classes(WtSections.wtSectionBgGrayDark)
}) {
Div({ classes(WtContainer.wtContainer) }) {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeM)
}) {
Logo()
// TODO: support i18n
//LanguageButton()
}
}
}
}
@Composable
private fun Logo() {
Div(attrs = {
classes(WtCols.wtColInline)
}) {
A(attrs = {
target(ATarget.Blank)
}, href = "https://www.jetbrains.com/") {
Div(attrs = {
classes("jetbrains-logo", "_logo-jetbrains-square", "_size-3")
}) {}
}
}
}
@Composable
private fun LanguageButton() {
Div(attrs = {
classes(WtCols.wtColInline)
}) {
Button(attrs = {
classes(WtTexts.wtButton, WtTexts.wtLangButton)
onClick { window.alert("Oops! This feature is yet to be implemented") }
}) {
Img(src = "ic_lang.svg", attrs = { style {
property("padding-left", 8.px)
property("padding-right", 8.px)
}})
Text("English")
}
}
}

223
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/IntroSection.kt

@ -0,0 +1,223 @@
package com.sample.content
import androidx.compose.runtime.*
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.AttrsBuilder
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.dom.*
import com.sample.components.ContainerInSection
import com.sample.style.*
import org.w3c.dom.HTMLElement
@Composable
fun Intro() {
ContainerInSection {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeM, WtRows.wtRowSmAlignItemsCenter)
}) {
Div({
classes(WtCols.wtCol2, WtCols.wtColMd3)
style {
alignSelf(AlignSelf.Start)
}
}) {
Img(src = "i1.svg", attrs = { classes(AppStylesheet.composeLogo) })
}
Div({
classes(
WtCols.wtCol10,
WtCols.wtColMd8,
WtCols.wtColSm12,
WtOffsets.wtTopOffsetSm12
)
}) {
H1(attrs = { classes(WtTexts.wtHero) }) {
Text("Compose for ")
Span({
classes(WtTexts.wtHero)
style {
display(DisplayStyle.InlineBlock)
property("white-space", "nowrap")
}
}) {
Text("Web")
Span(attrs = { classes(AppStylesheet.composeTitleTag) }) {
Text("Technology preview")
}
}
}
Div({
classes(WtDisplay.wtDisplayMdNone)
}) {
IntroAboutComposeWeb()
}
}
}
Div(attrs = {
classes(WtDisplay.wtDisplayNone, WtDisplay.wtDisplayMdBlock)
}) {
IntroAboutComposeWeb()
}
}
}
@Composable
private fun IntroAboutComposeWeb() {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeM)
}) {
Div({
classes(WtCols.wtCol9, WtCols.wtColMd9, WtCols.wtColSm12)
}) {
P({ classes(WtTexts.wtSubtitle2, WtOffsets.wtTopOffset24) }) {
Text("Reactive web UIs for Kotlin, based on Google's ")
A(href = "https://developer.android.com/jetpack/compose", attrs = {
classes(WtTexts.wtLink)
target(ATarget.Blank)
}) {
Text("modern toolkit")
}
Text(" and brought to you by JetBrains")
}
P({
classes(WtTexts.wtText1, WtOffsets.wtTopOffset24)
}) {
Text(
"Compose for Web simplifies and accelerates UI development for web applications, " +
"and aims to enable UI code sharing between web, desktop, and Android applications " +
"in the future. Currently in technology preview."
)
}
ComposeWebStatusMessage()
IntroCodeSample()
A(
attrs = {
classes(WtTexts.wtButton, WtOffsets.wtTopOffset24)
target(ATarget.Blank)
},
href = "https://github.com/jetbrains/compose-jb"
) {
Text("Explore on GitHub")
}
}
}
}
@Composable
private fun IntroCodeSample() {
Div({
style {
marginTop(24.px)
backgroundColor(rgba(39, 40, 44, 0.05))
borderRadius(8.px)
property("font-family", "'JetBrains Mono', monospace")
}
}) {
Div({
style {
property("padding", "12px 16px")
}
}) {
FormattedCodeSnippet(
code = """
fun greet() = listOf("Hello", "Hallo", "Hola", "Servus").random()
renderComposable("greetingContainer") {
var greeting by remember { mutableStateOf(greet()) }
Button(attrs = { onClick { greeting = greet() } }) {
Text(greeting)
}
}
""".trimIndent()
)
}
Hr({
style {
height(1.px)
border(width = 0.px)
backgroundColor(rgba(39, 40, 44, 0.15))
}
})
IntroCodeSampleResult()
}
}
@Composable
private fun IntroCodeSampleResult() {
Div({
style {
property("padding", "12px 16px")
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Row)
alignItems(AlignItems.Center)
}
}) {
Span({
classes(WtTexts.wtText2)
style {
property("margin-right", 8.px)
}
}) {
Text("Result:")
}
fun greet() = listOf("Hello", "Hallo", "Hola", "Servus").random()
Div({
id("greetingContainer")
}) {
var greeting by remember { mutableStateOf(greet()) }
Button(attrs = { onClick { greeting = greet() } }) {
Text(greeting)
}
}
}
}
@Composable
private fun ComposeWebStatusMessage() {
Div({
classes(WtRows.wtRow, WtRows.wtRowSizeXs, WtOffsets.wtTopOffset24)
}) {
Div({
classes(WtCols.wtColInline)
}) {
Img(src = "ic_info.svg", attrs = {
style {
width(24.px)
height(24.px)
}
})
}
Div({
classes(WtCols.wtColAutoFill)
}) {
P({
classes(WtTexts.wtText3)
}) {
Text(
"With its current status Technology Preview, Compose for Web " +
"is not production-ready, and should only be used in experiments. " +
"We are hard at work to bring you great learning materials, tutorials, " +
"and documentation, and optimize the performance of Compose for Web in the future!"
)
}
}
}
}

72
web/samples/web_landing/src/jsMain/kotlin/com/sample/content/JoinUs.kt

@ -0,0 +1,72 @@
package com.sample.content
import androidx.compose.runtime.Composable
import org.jetbrains.compose.web.attributes.ATarget
import org.jetbrains.compose.web.attributes.target
import org.jetbrains.compose.web.dom.*
import org.jetbrains.compose.web.css.*
import com.sample.components.ContainerInSection
import com.sample.style.*
@Composable
fun JoinUs() {
ContainerInSection(WtSections.wtSectionBgGrayLight) {
Div(attrs = {
classes(WtRows.wtRow, WtRows.wtRowSizeM)
}) {
Div(attrs = {
classes(WtCols.wtCol9, WtCols.wtColMd11, WtCols.wtColSm12)
}) {
P(attrs = {
classes(WtTexts.wtSubtitle2)
}) {
Text("Interested in Compose for other platforms?")
P {
Text("Have a look at ")
A(href = "https://www.jetbrains.com/lp/compose/", attrs = {
classes(WtTexts.wtLink)
target(ATarget.Blank)
}) {
Text("Compose for Desktop")
}
}
}
P(attrs = {
classes(WtTexts.wtSubtitle2, WtOffsets.wtTopOffset24)
}) {
Text("Feel free to join the ")
LinkToSlack(
url = "https://kotlinlang.slack.com/archives/C01F2HV7868",
text = "#compose-web"
)
Text(" channel on Kotlin Slack to discuss Compose for Web, or ")
LinkToSlack(
url = "https://kotlinlang.slack.com/archives/CJLTWPH7S",
text = "#compose"
)
Text(" for general Compose discussions")
}
}
}
A(attrs = {
classes(WtTexts.wtButton, WtTexts.wtButtonContrast, WtOffsets.wtTopOffset24)
target(ATarget.Blank)
}, href = "https://surveys.jetbrains.com/s3/kotlin-slack-sign-up") {
Text("Join Kotlin Slack")
}
}
}
@Composable
private fun LinkToSlack(url: String, text: String) {
A(href = url, attrs = {
target(ATarget.Blank)
classes(WtTexts.wtLink)
}) {
Text(text)
}
}

95
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/Stylesheet.kt

@ -0,0 +1,95 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.selectors.CSSSelector
object AppCSSVariables {
val wtColorGreyLight by variable<CSSColorValue>()
val wtColorGreyDark by variable<CSSColorValue>()
val wtOffsetTopUnit by variable<CSSUnitValue>()
val wtHorizontalLayoutGutter by variable<CSSUnitValue>()
val wtFlowUnit by variable<CSSUnitValue>()
val wtHeroFontSize by variable<CSSUnitValue>()
val wtHeroLineHeight by variable<CSSUnitValue>()
val wtSubtitle2FontSize by variable<CSSUnitValue>()
val wtSubtitle2LineHeight by variable<CSSUnitValue>()
val wtH2FontSize by variable<CSSUnitValue>()
val wtH2LineHeight by variable<CSSUnitValue>()
val wtH3FontSize by variable<CSSUnitValue>()
val wtH3LineHeight by variable<CSSUnitValue>()
val wtColCount by variable<StylePropertyNumber>()
}
object AppStylesheet : StyleSheet() {
val composeLogo by style {
property("max-width", 100.percent)
}
val composeTitleTag by style {
property("padding", "5px 12px")
property("letter-spacing", "normal")
property("font-weight", 400)
property("line-height", 24.px)
position(Position.Relative)
top((-32).px)
marginLeft(8.px)
fontSize(15.px)
backgroundColor(rgba(39, 40, 44, .05))
color(rgba(39,40,44,.7))
borderRadius(4.px, 4.px, 4.px)
media(mediaMaxWidth(640.px)) {
self style {
top((-16).px)
}
}
}
init {
"label, a, button" style {
property(
"font-family",
"system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
CSSSelector.Universal style {
AppCSSVariables.wtColorGreyLight(Color("#f4f4f4"))
AppCSSVariables.wtColorGreyDark(Color("#323236"))
AppCSSVariables.wtOffsetTopUnit(24.px)
margin(0.px)
}
media(mediaMaxWidth(640.px)) {
CSSSelector.Universal style {
AppCSSVariables.wtOffsetTopUnit(16.px)
AppCSSVariables.wtFlowUnit(16.px)
}
}
CSSSelector.Attribute(
name = "class",
value = "wtCol",
operator = CSSSelector.Attribute.Operator.Contains
) style {
property("margin-right", AppCSSVariables.wtHorizontalLayoutGutter.value())
property("margin-left", AppCSSVariables.wtHorizontalLayoutGutter.value())
property(
"flex-basis",
"calc(8.33333%*${AppCSSVariables.wtColCount.value()} - ${AppCSSVariables.wtHorizontalLayoutGutter.value()}*2)"
)
property(
"max-width",
"calc(8.33333%*${AppCSSVariables.wtColCount.value()} - ${AppCSSVariables.wtHorizontalLayoutGutter.value()}*2)"
)
property("box-sizing", "border-box")
}
}
}

49
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtCard.kt

@ -0,0 +1,49 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtCards : StyleSheet(AppStylesheet) {
val wtCard by style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
border(1.px, LineStyle.Solid)
property("min-height", 0)
property("box-sizing", "border-box")
}
val wtCardThemeLight by style {
border(color = rgba(39,40,44,.2))
color(Color("#27282c"))
backgroundColor(Color("white"))
}
val wtCardThemeDark by style {
backgroundColor(rgba(255, 255, 255, 0.05))
color(rgba(255, 255, 255, 0.6))
border(0.px)
}
val wtCardSection by style {
position(Position.Relative)
property("overflow", "auto")
property("flex", "1 1 auto")
property("min-height", 0)
property("box-sizing", "border-box")
property("padding", "24px 32px")
media(mediaMaxWidth(640.px)) {
self style { padding(16.px) }
}
}
val wtVerticalFlex by style {
display(DisplayStyle.Flex)
flexDirection(FlexDirection.Column)
alignItems(AlignItems.FlexStart)
}
val wtVerticalFlexGrow by style {
flexGrow(1)
property("max-width", 100.percent)
}
}

137
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtCol.kt

@ -0,0 +1,137 @@
package com.sample.style
import org.jetbrains.compose.web.css.CSSBuilder
import org.jetbrains.compose.web.css.CSSUnitValue
import org.jetbrains.compose.web.css.GenericStyleSheetBuilder
import org.jetbrains.compose.web.css.StyleSheet
import org.jetbrains.compose.web.css.flexGrow
import org.jetbrains.compose.web.css.maxWidth
import org.jetbrains.compose.web.css.media
import org.jetbrains.compose.web.css.percent
import org.jetbrains.compose.web.css.px
import org.jetbrains.compose.web.css.mediaMaxWidth
import org.jetbrains.compose.web.css.selectors.CSSSelector
fun <TBuilder> GenericStyleSheetBuilder<TBuilder>.mediaMaxWidth(
value: CSSUnitValue,
cssSelector: CSSSelector,
rulesBuild: TBuilder.() -> Unit
) {
media(mediaMaxWidth(value)) {
cssSelector style rulesBuild
}
}
fun CSSBuilder.forMaxWidth(value: CSSUnitValue, builder: CSSBuilder.() -> Unit) {
mediaMaxWidth(value, self, builder)
}
object WtCols : StyleSheet(AppStylesheet) {
val wtCol2 by style {
AppCSSVariables.wtColCount(2)
}
val wtCol3 by style {
AppCSSVariables.wtColCount(3)
}
val wtCol4 by style {
AppCSSVariables.wtColCount(4)
}
val wtCol5 by style {
AppCSSVariables.wtColCount(5)
}
val wtCol6 by style {
AppCSSVariables.wtColCount(6)
}
val wtCol9 by style {
AppCSSVariables.wtColCount(9)
}
val wtCol10 by style {
AppCSSVariables.wtColCount(10)
}
val wtColMd3 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(3)
}
}
val wtColMd4 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(4)
}
}
val wtColMd8 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(8)
}
}
val wtColMd9 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(9)
}
}
val wtColMd10 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(10)
}
}
val wtColMd11 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(11)
}
}
val wtColMd6 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(6)
}
}
val wtColMd12 by style {
forMaxWidth(1000.px) {
AppCSSVariables.wtColCount(12)
}
}
val wtColSm12 by style {
forMaxWidth(640.px) {
AppCSSVariables.wtColCount(12)
}
}
val wtColLg6 by style {
forMaxWidth(1276.px) {
AppCSSVariables.wtColCount(6)
}
}
val wtColSmAutoFill by style {
forMaxWidth(640.px) {
AppCSSVariables.wtColCount(0)
flexGrow(1)
property("max-width", 100.percent)
}
}
val wtColAutoFill by style {
AppCSSVariables.wtColCount(0)
flexGrow(1)
property("max-width", 100.percent)
}
val wtColInline by style {
AppCSSVariables.wtColCount(0)
property("max-width", 100.percent)
property("flex-basis", "auto")
}
}

38
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtContainer.kt

@ -0,0 +1,38 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtContainer : StyleSheet(AppStylesheet) {
val wtContainer by style {
property("margin-left", "auto")
property("margin-right", "auto")
property("box-sizing", "border-box")
property("padding-left", 22.px)
property("padding-right", 22.px)
property("max-width", 1276.px)
media(mediaMaxWidth(640.px)) {
self style {
property("max-width", 100.percent)
property("padding-left", 16.px)
property("padding-right", 16.px)
}
}
media(mediaMaxWidth(1276.px)) {
self style {
property("max-width", 996.px)
property("padding-left", 22.px)
property("padding-right", 22.px)
}
}
media(mediaMaxWidth(1000.px)) {
self style {
property("max-width", 100.percent)
property("padding-left", 22.px)
property("padding-right", 22.px)
}
}
}
}

25
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtDisplay.kt

@ -0,0 +1,25 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtDisplay : StyleSheet(AppStylesheet) {
val wtDisplayNone by style {
display(DisplayStyle.None)
}
val wtDisplayMdBlock by style {
media(mediaMaxWidth(1000.px)) {
self style {
display(DisplayStyle.Block)
}
}
}
val wtDisplayMdNone by style {
media(mediaMaxWidth(1000.px)) {
self style {
display(DisplayStyle.None)
}
}
}
}

41
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtOffest.kt

@ -0,0 +1,41 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtOffsets : StyleSheet(AppStylesheet) {
val wtTopOffset96 by style {
marginTop(96.px)
property(
"margin-top",
"calc(4*${AppCSSVariables.wtOffsetTopUnit.value(24.px)})"
)
}
val wtTopOffset24 by style {
marginTop(24.px)
property(
"margin-top",
"calc(1*${AppCSSVariables.wtOffsetTopUnit.value(24.px)})"
)
}
val wtTopOffset48 by style {
marginTop(48.px)
}
val wtTopOffsetSm12 by style {
media(mediaMaxWidth(640.px)) {
self style {
marginTop(12.px)
}
}
}
val wtTopOffsetSm24 by style {
media(mediaMaxWidth(640.px)) {
self style {
marginTop(24.px)
}
}
}
}

42
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtRow.kt

@ -0,0 +1,42 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtRows : StyleSheet(AppStylesheet) {
val wtRow by style {
AppCSSVariables.wtHorizontalLayoutGutter(0.px)
display(DisplayStyle.Flex)
flexWrap(FlexWrap.Wrap)
property(
"margin-right",
"calc(-1*${AppCSSVariables.wtHorizontalLayoutGutter.value()})"
)
property(
"margin-left",
"calc(-1*${AppCSSVariables.wtHorizontalLayoutGutter.value()})"
)
property("box-sizing", "border-box")
}
val wtRowSizeM by style {
AppCSSVariables.wtHorizontalLayoutGutter(16.px)
media(mediaMaxWidth(640.px)) {
self style {
AppCSSVariables.wtHorizontalLayoutGutter(8.px)
}
}
}
val wtRowSizeXs by style {
AppCSSVariables.wtHorizontalLayoutGutter(6.px)
}
val wtRowSmAlignItemsCenter by style {
self style {
alignItems(AlignItems.Center)
}
}
}

27
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtSection.kt

@ -0,0 +1,27 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
object WtSections : StyleSheet(AppStylesheet) {
val wtSection by style {
property("box-sizing", "border-box")
property("padding-bottom", 96.px)
property("padding-top", 1.px)
property(
propertyName = "padding-bottom",
value = "calc(4*${AppCSSVariables.wtOffsetTopUnit.value(24.px)})"
)
backgroundColor(Color("#fff"))
}
val wtSectionBgGrayLight by style {
backgroundColor(Color("#f4f4f4"))
backgroundColor(AppCSSVariables.wtColorGreyLight.value())
}
val wtSectionBgGrayDark by style {
backgroundColor(Color("#323236"))
backgroundColor(AppCSSVariables.wtColorGreyDark.value())
}
}

221
web/samples/web_landing/src/jsMain/kotlin/com/sample/style/WtText.kt

@ -0,0 +1,221 @@
package com.sample.style
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.selectors.hover
object WtTexts : StyleSheet(AppStylesheet) {
val wtHero by style {
color(Color("#27282c"))
fontSize(60.px)
property("font-size", AppCSSVariables.wtHeroFontSize.value(60.px))
property("letter-spacing", (-1.5).px)
property("font-weight", 900)
property("line-height", 64.px)
property("line-height", AppCSSVariables.wtHeroLineHeight.value(64.px))
media(mediaMaxWidth(640.px)) {
self style {
AppCSSVariables.wtHeroFontSize(42.px)
AppCSSVariables.wtHeroLineHeight(48.px)
}
}
property(
"font-family",
"Gotham SSm A,Gotham SSm B,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtSubtitle2 by style {
color(Color("#27282c"))
fontSize(28.px)
property("font-size", AppCSSVariables.wtSubtitle2FontSize.value(28.px))
property("letter-spacing", "normal")
property("font-weight", 300)
property("line-height", 40.px)
property("line-height", AppCSSVariables.wtSubtitle2LineHeight.value(40.px))
media(mediaMaxWidth(640.px)) {
self style {
AppCSSVariables.wtSubtitle2FontSize(24.px)
AppCSSVariables.wtSubtitle2LineHeight(32.px)
}
}
property(
"font-family",
"Gotham SSm A,Gotham SSm B,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtText1 by style {
color(rgba(39, 40, 44, .7))
fontSize(18.px)
property("letter-spacing", "normal")
property("font-weight", 400)
property("line-height", 28.px)
property(
"font-family",
"system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtText1ThemeDark by style {
color(rgba(255, 255, 255, 0.6))
}
val wtText2 by style {
color(rgba(39, 40, 44, .7))
fontSize(15.px)
property("letter-spacing", "normal")
property("font-weight", 400)
property("line-height", 24.px)
property(
"font-family",
"system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtText3 by style {
color(rgba(39, 40, 44, .7))
fontSize(12.px)
property("letter-spacing", "normal")
property("font-weight", 400)
property("line-height", 16.px)
property(
"font-family",
"system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtTextPale by style {
color(rgba(255, 255, 255, 0.30))
}
val wtText2ThemeDark by style {
color(rgba(255, 255, 255, 0.6))
}
val wtText3ThemeDark by style {
color(rgba(255, 255, 255, 0.6))
}
val wtLink by style {
property("border-bottom", "1px solid transparent")
property("text-decoration", "none")
color(Color("#167dff"))
hover(self) style {
property("border-bottom-color", "#167dff")
}
}
val wtH2 by style {
color(Color("#27282c"))
fontSize(31.px)
property("font-size", AppCSSVariables.wtH2FontSize.value(31.px))
property("letter-spacing", (-.5).px)
property("font-weight", 700)
property("line-height", 40.px)
property("line-height", 40.px)
media(mediaMaxWidth(640.px)) {
self style {
AppCSSVariables.wtH2FontSize(24.px)
AppCSSVariables.wtH2LineHeight(32.px)
}
}
property(
"font-family",
"Gotham SSm A,Gotham SSm B,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtH2ThemeDark by style {
color(Color("#fff"))
}
val wtH3 by style {
color(Color("#27282c"))
fontSize(21.px)
property("font-size", AppCSSVariables.wtH3FontSize.value(20.px))
property("letter-spacing", "normal")
property("font-weight", 700)
property("line-height", 28.px)
property("line-height", AppCSSVariables.wtH3LineHeight.value(28.px))
property(
"font-family",
"system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Droid Sans,Helvetica Neue,Arial,sans-serif"
)
}
val wtH3ThemeDark by style {
color(Color("#fff"))
}
val wtButton by style {
color(Color("white"))
backgroundColor(Color("#167dff"))
fontSize(15.px)
display(DisplayStyle.InlineBlock)
property("text-decoration", "none")
property("border-radius", "24px")
property("padding", "12px 32px")
property("line-height", 24.px)
property("font-weight", 400)
property("width", "fit-content")
hover(self) style {
backgroundColor(rgba(22, 125, 255, .8))
}
}
val wtLangButton by style {
display(DisplayStyle.LegacyInlineFlex)
justifyContent(JustifyContent.Center)
alignItems(AlignItems.Center)
backgroundColor(Color("transparent"))
border(0.px)
property("outline", "none")
hover(self) style {
backgroundColor(rgba(255, 255, 255, 0.1))
}
}
val wtButtonContrast by style {
color(Color("white"))
backgroundColor(Color("#27282c"))
hover(self) style {
backgroundColor(rgba(39, 40, 44, .7))
}
}
val wtSocialButtonItem by style {
property("margin-right", 16.px)
marginLeft(16.px)
padding(12.px)
backgroundColor(Color("transparent"))
display(DisplayStyle.LegacyInlineFlex)
hover(self) style {
backgroundColor(rgba(255, 255, 255, 0.1))
property("border-radius", "24px")
}
media(mediaMaxWidth(640.px)) {
self style {
property("margin-right", 8.px)
property("margin-left", 8.px)
}
}
}
}

BIN
web/samples/web_landing/src/jsMain/resources/favicon-32x32.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

58
web/samples/web_landing/src/jsMain/resources/hljs.css

@ -0,0 +1,58 @@
/*!
* StackOverflow.com light style
*
* @stackoverflow/stacks v0.56.0
* https://github.com/StackExchange/Stacks
*/
.hljs {
display: block;
overflow-x: auto;
padding: .5em;
color: #2f3337;
background: #f6f6f6
}
.hljs-comment {
color: #656e77
}
.hljs-attr, .hljs-doctag, .hljs-keyword, .hljs-meta, .hljs-meta-keyword, .hljs-section, .hljs-selector-class, .hljs-selector-pseudo, .hljs-selector-tag {
color: #015692;
font-weight: bold;
}
.hljs-attribute {
color: #803378
}
.hljs-built_in, .hljs-literal, .hljs-name, .hljs-number, .hljs-quote, .hljs-selector-id, .hljs-template-tag, .hljs-title, .hljs-type {
color: #b75501
}
.hljs-title {
font-style: italic;
}
.hljs-link, .hljs-meta-string, .hljs-regexp, .hljs-selector-attr, .hljs-string, .hljs-symbol, .hljs-template-variable, .hljs-variable {
color: #54790d
}
.hljs-bullet, .hljs-code {
color: #535a60
}
.hljs-deletion {
color: #c02d2e
}
.hljs-addition {
color: #2f6f44
}
.hljs-emphasis {
font-style: italic
}
.hljs-strong {
font-weight: 700
}

1
web/samples/web_landing/src/jsMain/resources/i1.svg

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.9 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save