From 1492ef5779dcf587ce30d7ccb7adb1337806fdf5 Mon Sep 17 00:00:00 2001 From: Sebastiano Poggi Date: Fri, 6 Sep 2024 16:00:43 +0200 Subject: [PATCH] Pre-apply ktfmt formatting to minimize merge diff --- build.gradle.kts | 11 +- buildSrc/build.gradle.kts | 18 +- buildSrc/settings.gradle.kts | 8 +- ...droid-studio-releases-generator.gradle.kts | 5 +- .../kotlin/icon-keys-generator.gradle.kts | 134 +- .../intellij-theme-generator.gradle.kts | 11 +- .../kotlin/jewel-check-public-api.gradle.kts | 19 +- .../src/main/kotlin/jewel-publish.gradle.kts | 28 +- buildSrc/src/main/kotlin/jewel.gradle.kts | 58 +- .../jetbrains/jewel/window/DecoratedWindow.kt | 47 +- .../org/jetbrains/jewel/window/Theme.kt | 6 +- .../jetbrains/jewel/window/TitleBar.Linux.kt | 50 +- .../jetbrains/jewel/window/TitleBar.MacOS.kt | 10 +- .../org/jetbrains/jewel/window/TitleBar.kt | 44 +- .../window/styling/DecoratedWindowStyling.kt | 14 +- .../jewel/window/styling/TitleBarStyling.kt | 9 +- .../jewel/window/utils/DesktopPlatform.kt | 3 +- .../jetbrains/jewel/window/utils/JnaLoader.kt | 4 +- .../jewel/window/utils/UnsafeAccessing.kt | 18 +- .../jewel/window/utils/macos/Foundation.kt | 79 +- .../window/utils/macos/FoundationLibrary.kt | 70 +- .../jetbrains/jewel/window/utils/macos/ID.kt | 9 +- .../jewel/window/utils/macos/MacUtil.kt | 11 +- foundation/build.gradle.kts | 6 +- .../jewel/foundation/Compatibility.kt | 11 +- .../jewel/foundation/GenerateDataFunctions.kt | 10 +- .../jewel/foundation/GlobalColors.kt | 13 +- .../jewel/foundation/GlobalMetrics.kt | 12 +- .../org/jetbrains/jewel/foundation/Stroke.kt | 20 +- .../actionSystem/DataProviderContext.kt | 10 +- .../actionSystem/DataProviderElement.kt | 5 +- .../actionSystem/DataProviderNode.kt | 5 +- .../foundation/actionSystem/ProvideData.kt | 13 +- .../jewel/foundation/lazy/Keybindings.kt | 60 +- .../lazy/SelectableColumnOnKeyEvent.kt | 147 +- .../foundation/lazy/SelectableLazyColumn.kt | 73 +- .../lazy/SelectableLazyListScope.kt | 31 +- .../lazy/SelectableLazyListState.kt | 83 +- .../foundation/lazy/tree/BasicLazyTree.kt | 143 +- .../jewel/foundation/lazy/tree/BuildTree.kt | 109 +- .../lazy/tree/DefaultTreeViewKeybindings.kt | 24 +- .../lazy/tree/DefaultTreeViewOnKeyEvent.kt | 24 +- .../jewel/foundation/lazy/tree/KeyActions.kt | 76 +- .../jewel/foundation/lazy/tree/Tree.kt | 59 +- .../jewel/foundation/lazy/tree/TreeState.kt | 5 +- .../lazy/tree/TreeViewOnKeyEvent.kt | 18 +- .../jewel/foundation/modifier/Activation.kt | 17 +- .../jewel/foundation/modifier/Border.kt | 225 +- .../state/FocusableComponentState.kt | 9 +- .../jewel/foundation/theme/JewelTheme.kt | 130 +- .../foundation/theme/ThemeColorPalette.kt | 6 +- .../jewel/foundation/theme/ThemeIconData.kt | 6 +- .../jewel/foundation/util/JewelLogger.kt | 203 +- .../lazy/SelectableLazyColumnTest.kt | 381 +-- ide-laf-bridge/build.gradle.kts | 10 +- .../org/jetbrains/jewel/bridge/Bridge.kt | 15 +- .../jetbrains/jewel/bridge/BridgeOverride.kt | 9 +- .../bridge/BridgePainterHintsProvider.kt | 22 +- .../jewel/bridge/BridgeResourceResolver.kt | 10 +- .../org/jetbrains/jewel/bridge/BridgeUtils.kt | 34 +- .../jewel/bridge/JewelBridgeException.kt | 2 +- .../jewel/bridge/JewelComposePanel.kt | 33 +- .../jetbrains/jewel/bridge/ScrollbarHelper.kt | 3 +- .../jewel/bridge/SwingBridgeService.kt | 45 +- .../org/jetbrains/jewel/bridge/Typography.kt | 21 +- .../jewel/bridge/UiThemeExtensions.kt | 3 +- .../jewel/bridge/theme/BridgeSliderStyling.kt | 3 +- .../bridge/theme/BridgeThemeColorPalette.kt | 25 +- .../jewel/bridge/theme/IntUiBridge.kt | 49 +- .../jewel/bridge/theme/ScrollbarBridge.kt | 4 +- .../IntUiDecoratedWindowResourceResolver.kt | 4 +- .../jewel/intui/window/IntUiTheme.kt | 20 +- .../styling/IntUiDecoratedWindowStyling.kt | 3 +- .../window/styling/IntUiTitleBarStyling.kt | 48 +- .../intui/standalone/JetBrainsMonoFont.kt | 36 +- .../jewel/intui/standalone/PainterProvider.kt | 8 +- .../StandalonePainterHintsProvider.kt | 22 +- .../styling/IntUiCheckboxStyling.kt | 19 +- .../styling/IntUiCircularProgressStyling.kt | 7 +- .../styling/IntUiDropdownStyling.kt | 3 +- .../styling/IntUiGroupHeaderStyling.kt | 12 +- .../IntUiHorizontalProgressBarStyling.kt | 4 +- .../styling/IntUiLazyTreeStyling.kt | 8 +- .../standalone/styling/IntUiMenuStyling.kt | 33 +- .../styling/IntUiRadioButtonStyling.kt | 10 +- .../styling/IntUiScrollbarStyling.kt | 4 +- .../IntUiSegmentedControlButtonStyling.kt | 7 +- .../standalone/styling/IntUiSliderStyling.kt | 3 +- .../styling/IntUiTabStripScrollbarStyling.kt | 2 +- .../standalone/styling/IntUiTooltipStyling.kt | 18 +- .../standalone/theme/IntUiGlobalColors.kt | 16 +- .../standalone/theme/IntUiGlobalMetrics.kt | 6 +- .../intui/standalone/theme/IntUiTheme.kt | 28 +- .../jewel/markdown/InlineMarkdown.kt | 30 +- .../org/jetbrains/jewel/markdown/Markdown.kt | 11 +- .../jetbrains/jewel/markdown/MarkdownBlock.kt | 21 +- .../org/jetbrains/jewel/markdown/MimeType.kt | 137 +- .../jewel/markdown/extensions/Markdown.kt | 21 +- .../MarkdownBlockProcessorExtension.kt | 12 +- .../MarkdownBlockRendererExtension.kt | 9 +- .../MarkdownInlineProcessorExtension.kt | 10 +- .../MarkdownInlineRendererExtension.kt | 15 +- .../extensions/MarkdownProcessorExtension.kt | 27 +- .../extensions/MarkdownRendererExtension.kt | 16 +- .../processing/MarkdownParserFactory.kt | 22 +- .../markdown/processing/MarkdownProcessor.kt | 124 +- .../markdown/processing/ProcessingUtil.kt | 163 +- .../DefaultInlineMarkdownRenderer.kt | 27 +- .../rendering/DefaultMarkdownBlockRenderer.kt | 65 +- .../rendering/InlineMarkdownRenderer.kt | 5 +- .../rendering/MarkdownBlockRenderer.kt | 41 +- .../markdown/rendering/MarkdownStyling.kt | 36 +- ...rkdownProcessorDocumentParsingExtraTest.kt | 61 +- .../MarkdownProcessorDocumentParsingTest.kt | 3007 +++++------------ .../org/jetbrains/jewel/markdown/TestUtils.kt | 131 +- .../MarkdownProcessorOptimizeEditsTest.kt | 112 +- .../autolink/AutolinkProcessorExtension.kt | 3 +- .../github/alerts/GitHubAlertBlockRenderer.kt | 43 +- .../alerts/GitHubAlertProcessorExtension.kt | 21 +- .../alerts/GitHubAlertBlockExtensionTest.kt | 97 +- .../bridge/BridgeProvideMarkdownStyling.kt | 6 +- .../bridge/styling/BridgeMarkdownStyling.kt | 71 +- .../styling/IntUiMarkdownStyling.kt | 124 +- samples/ide-plugin/build.gradle.kts | 14 +- .../src/main/kotlin/icons/JewelIcons.kt | 3 +- .../samples/ideplugin/ComponentShowcaseTab.kt | 170 +- .../ideplugin/JewelDemoToolWindowFactory.kt | 24 +- .../ideplugin/ScrollbarsShowcaseTab.kt | 2 +- .../ideplugin/SwingComparisonTabPanel.kt | 147 +- .../ideplugin/dialog/JewelDemoAction.kt | 20 +- .../ideplugin/dialog/WizardDialogWrapper.kt | 31 +- .../releasessample/AndroidStudioReleases.kt | 3 +- .../ideplugin/releasessample/ContentItem.kt | 3 +- .../ideplugin/releasessample/ContentSource.kt | 6 +- .../ideplugin/releasessample/FoilModifier.kt | 17 +- .../releasessample/ReleaseChannel.kt | 5 +- .../releasessample/ReleasesSampleCompose.kt | 150 +- .../releasessample/ReleasesSampleService.kt | 12 +- samples/standalone/build.gradle.kts | 12 +- .../jewel/samples/standalone/IntUiThemes.kt | 3 +- .../jewel/samples/standalone/Main.kt | 64 +- .../standalone/StandaloneSampleIcons.kt | 3 +- .../samples/standalone/view/ComponentsView.kt | 7 +- .../samples/standalone/view/MarkdownView.kt | 10 +- .../samples/standalone/view/TitleBarView.kt | 69 +- .../samples/standalone/view/WelcomeView.kt | 17 +- .../standalone/view/component/Borders.kt | 81 +- .../standalone/view/component/Buttons.kt | 42 +- .../standalone/view/component/Checkboxes.kt | 67 +- .../standalone/view/component/ChipsAndTree.kt | 90 +- .../standalone/view/component/Dropdowns.kt | 152 +- .../standalone/view/component/Links.kt | 34 +- .../standalone/view/component/ProgressBar.kt | 27 +- .../standalone/view/component/RadioButtons.kt | 32 +- .../standalone/view/component/Scrollbars.kt | 21 +- .../view/component/SegmentedControls.kt | 14 +- .../standalone/view/component/Slider.kt | 26 +- .../samples/standalone/view/component/Tabs.kt | 10 +- .../standalone/view/component/TextAreas.kt | 5 +- .../standalone/view/component/TextFields.kt | 48 +- .../standalone/view/component/Tooltips.kt | 4 +- .../standalone/view/markdown/JewelReadme.kt | 3 +- .../view/markdown/MarkdownEditor.kt | 41 +- .../view/markdown/MarkdownPreview.kt | 20 +- .../viewmodel/ComponentsViewModel.kt | 66 +- .../standalone/viewmodel/MainViewModel.kt | 3 +- ui/build.gradle.kts | 6 +- .../jetbrains/jewel/ui/ComponentStyling.kt | 30 +- .../kotlin/org/jetbrains/jewel/ui/Outline.kt | 8 +- .../jewel/ui/component/ActionButton.kt | 28 +- .../jetbrains/jewel/ui/component/Button.kt | 19 +- .../jetbrains/jewel/ui/component/Checkbox.kt | 59 +- .../org/jetbrains/jewel/ui/component/Chip.kt | 77 +- .../ui/component/CircularProgressIndicator.kt | 111 +- .../jewel/ui/component/ContextMenu.kt | 37 +- .../jetbrains/jewel/ui/component/Divider.kt | 6 +- .../jetbrains/jewel/ui/component/Dropdown.kt | 73 +- .../org/jetbrains/jewel/ui/component/Icon.kt | 153 +- .../jewel/ui/component/IconActionButton.kt | 43 +- .../jewel/ui/component/IconButton.kt | 139 +- .../jewel/ui/component/InputField.kt | 6 +- .../jetbrains/jewel/ui/component/LazyTree.kt | 7 +- .../jewel/ui/component/LinearProgressBar.kt | 58 +- .../org/jetbrains/jewel/ui/component/Link.kt | 64 +- .../org/jetbrains/jewel/ui/component/Menu.kt | 265 +- .../jewel/ui/component/MenuManager.kt | 20 +- .../org/jetbrains/jewel/ui/component/Popup.kt | 19 +- .../jewel/ui/component/RadioButton.kt | 52 +- .../jewel/ui/component/ScrollableContainer.kt | 2 +- .../jetbrains/jewel/ui/component/Scrollbar.kt | 2 +- .../jewel/ui/component/SegmentedControl.kt | 59 +- .../ui/component/SegmentedControlButton.kt | 41 +- .../jetbrains/jewel/ui/component/Slider.kt | 279 +- .../jewel/ui/component/SplitLayout.kt | 52 +- .../jetbrains/jewel/ui/component/TabStrip.kt | 36 +- .../org/jetbrains/jewel/ui/component/Tabs.kt | 47 +- .../org/jetbrains/jewel/ui/component/Text.kt | 14 +- .../jetbrains/jewel/ui/component/TextField.kt | 4 +- .../jetbrains/jewel/ui/component/Tooltip.kt | 50 +- .../jewel/ui/component/Typography.kt | 55 +- .../ui/component/styling/ButtonStyling.kt | 20 +- .../ui/component/styling/CheckboxStyling.kt | 9 +- .../jewel/ui/component/styling/ChipStyling.kt | 18 +- .../styling/CircularProgressStyle.kt | 12 +- .../ui/component/styling/DividerStyling.kt | 23 +- .../ui/component/styling/DropdownStyling.kt | 22 +- .../component/styling/GroupHeaderStyling.kt | 17 +- .../styling/HorizontalProgressBarStyling.kt | 2 +- .../ui/component/styling/IconButtonStyling.kt | 28 +- .../ui/component/styling/InputFieldStyling.kt | 8 +- .../ui/component/styling/LazyTreeStyling.kt | 14 +- .../jewel/ui/component/styling/LinkStyling.kt | 17 +- .../jewel/ui/component/styling/MenuStyling.kt | 15 +- .../component/styling/RadioButtonStyling.kt | 14 +- .../ui/component/styling/ScrollbarStyling.kt | 14 +- .../styling/SegmentedControlStyling.kt | 12 +- .../ui/component/styling/SliderStyling.kt | 26 +- .../jewel/ui/component/styling/TabStyling.kt | 32 +- .../ui/component/styling/TextAreaStyling.kt | 13 +- .../ui/component/styling/TextFieldStyling.kt | 13 +- .../ui/component/styling/TooltipStyling.kt | 26 +- .../org/jetbrains/jewel/ui/icon/IconKey.kt | 5 +- .../jetbrains/jewel/ui/icon/NewUiChecker.kt | 5 +- .../jewel/ui/painter/BadgePainter.kt | 24 +- .../jewel/ui/painter/DelegatePainter.kt | 4 +- .../jetbrains/jewel/ui/painter/PainterHint.kt | 90 +- .../jewel/ui/painter/PainterHintsProvider.kt | 21 +- .../jewel/ui/painter/PainterProvider.kt | 19 +- .../ui/painter/PalettePainterHintsProvider.kt | 17 +- .../ui/painter/ResourcePainterProvider.kt | 67 +- .../jewel/ui/painter/badge/BadgeShape.kt | 15 +- .../jewel/ui/painter/badge/DotBadgeShape.kt | 31 +- .../jetbrains/jewel/ui/painter/hints/Badge.kt | 11 +- .../hints/ColorBasedPaletteReplacement.kt | 27 +- .../jewel/ui/painter/hints/DarkAndStroke.kt | 16 +- .../jetbrains/jewel/ui/painter/hints/HiDpi.kt | 13 +- .../jewel/ui/painter/hints/PathOverride.kt | 9 +- .../jewel/ui/painter/hints/Selected.kt | 8 +- .../jetbrains/jewel/ui/painter/hints/Size.kt | 51 +- .../jewel/ui/painter/hints/Stateful.kt | 39 +- .../jetbrains/jewel/ui/theme/JewelTheme.kt | 111 +- .../jewel/ui/util/ColorExtensions.kt | 14 +- .../jewel/ui/util/ModifierExtensions.kt | 10 +- .../org/jetbrains/jewel/BasicJewelUiTest.kt | 15 +- .../org/jetbrains/jewel/PainterHintTest.kt | 52 +- 245 files changed, 4066 insertions(+), 8139 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index ecaa66b5a..afebca7ef 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -20,10 +20,11 @@ dependencies { } tasks { - val mergeSarifReports by registering(MergeSarifTask::class) { - source(configurations.outgoingSarif) - include { it.file.extension == "sarif" } - } + val mergeSarifReports by + registering(MergeSarifTask::class) { + source(configurations.outgoingSarif) + include { it.file.extension == "sarif" } + } register("check") { dependsOn(mergeSarifReports) } -} +} \ No newline at end of file diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index c5db83d5e..dfa271cdd 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -6,21 +6,15 @@ plugins { } val properties = Properties() + project.file("../gradle.properties").inputStream().use { properties.load(it) } val jdkLevel = properties.getProperty("jdk.level") as String + kotlin { - jvmToolchain { - languageVersion = JavaLanguageVersion.of(jdkLevel) - } - - sourceSets { - all { - languageSettings { - optIn("kotlinx.serialization.ExperimentalSerializationApi") - } - } - } + jvmToolchain { languageVersion = JavaLanguageVersion.of(jdkLevel) } + + sourceSets { all { languageSettings { optIn("kotlinx.serialization.ExperimentalSerializationApi") } } } } dependencies { @@ -39,4 +33,4 @@ dependencies { // version catalogs. // Context: https://github.com/gradle/gradle/issues/15383#issuecomment-779893192 implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) -} +} \ No newline at end of file diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts index 909d005c6..763fd1d5a 100644 --- a/buildSrc/settings.gradle.kts +++ b/buildSrc/settings.gradle.kts @@ -15,9 +15,5 @@ dependencyResolutionManagement { mavenCentral() } - versionCatalogs { - create("libs") { - from(files("../gradle/libs.versions.toml")) - } - } -} + versionCatalogs { create("libs") { from(files("../gradle/libs.versions.toml")) } } +} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/android-studio-releases-generator.gradle.kts b/buildSrc/src/main/kotlin/android-studio-releases-generator.gradle.kts index dfba3fc28..a476248e3 100644 --- a/buildSrc/src/main/kotlin/android-studio-releases-generator.gradle.kts +++ b/buildSrc/src/main/kotlin/android-studio-releases-generator.gradle.kts @@ -10,9 +10,8 @@ val extension: StudioVersionsGenerationExtension = val task = tasks.register("generateAndroidStudioReleasesList") { val className = ClassName.bestGuess(STUDIO_RELEASES_OUTPUT_CLASS_NAME) - val filePath = className.packageName.replace(".", "/") + - "/${className.simpleName}.kt" + val filePath = className.packageName.replace(".", "/") + "/${className.simpleName}.kt" outputFile = extension.targetDir.file(filePath) dataUrl = extension.dataUrl resourcesDirs = extension.resourcesDirs - } + } \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/icon-keys-generator.gradle.kts b/buildSrc/src/main/kotlin/icon-keys-generator.gradle.kts index df315b03e..1a5489984 100644 --- a/buildSrc/src/main/kotlin/icon-keys-generator.gradle.kts +++ b/buildSrc/src/main/kotlin/icon-keys-generator.gradle.kts @@ -5,6 +5,8 @@ import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import io.gitlab.arturbosch.detekt.Detekt +import java.lang.reflect.Field +import java.net.URLClassLoader import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement @@ -14,32 +16,24 @@ import kotlinx.serialization.json.JsonPrimitive import org.jetbrains.dokka.gradle.DokkaTask import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension import org.jetbrains.kotlin.gradle.tasks.BaseKotlinCompile -import java.lang.reflect.Field -import java.net.URLClassLoader private val defaultOutputDir: Provider = layout.buildDirectory.dir("generated/iconKeys") -class IconKeysGeneratorContainer( - container: NamedDomainObjectContainer, -) : NamedDomainObjectContainer by container +class IconKeysGeneratorContainer(container: NamedDomainObjectContainer) : + NamedDomainObjectContainer by container -class IconKeysGeneration( - val name: String, - project: Project, -) { - val outputDirectory: DirectoryProperty = - project.objects - .directoryProperty() - .convention(defaultOutputDir) +class IconKeysGeneration(val name: String, project: Project) { + val outputDirectory: DirectoryProperty = project.objects.directoryProperty().convention(defaultOutputDir) val sourceClassName: Property = project.objects.property() val generatedClassName: Property = project.objects.property() } -val iconGeneration by configurations.registering { - isCanBeConsumed = false - isCanBeResolved = true -} +val iconGeneration by + configurations.registering { + isCanBeConsumed = false + isCanBeResolved = true + } val extension = IconKeysGeneratorContainer(container { IconKeysGeneration(it, project) }) @@ -64,25 +58,18 @@ extension.all item@{ } pluginManager.withPlugin("org.jetbrains.kotlin.jvm") { - the() - .sourceSets["main"] - .kotlin - .srcDir(defaultOutputDir) + the().sourceSets["main"].kotlin.srcDir(defaultOutputDir) } open class IconKeysGeneratorTask : DefaultTask() { - @get:OutputDirectory - val outputDirectory: DirectoryProperty = project.objects.directoryProperty() + @get:OutputDirectory val outputDirectory: DirectoryProperty = project.objects.directoryProperty() - @get:Input - val sourceClassName = project.objects.property() + @get:Input val sourceClassName = project.objects.property() - @get:Input - val generatedClassName = project.objects.property() + @get:Input val generatedClassName = project.objects.property() - @get:InputFiles - val configuration: ConfigurableFileCollection = project.objects.fileCollection() + @get:InputFiles val configuration: ConfigurableFileCollection = project.objects.fileCollection() init { group = "jewel" @@ -90,27 +77,25 @@ open class IconKeysGeneratorTask : DefaultTask() { @TaskAction fun generate() { - val guessedSourceClassName = sourceClassName - .map { ClassName.bestGuess(it).canonicalName.replace('.', '/') + ".kt" } - .get() + val guessedSourceClassName = + sourceClassName.map { ClassName.bestGuess(it).canonicalName.replace('.', '/') + ".kt" }.get() // The icons artifacts are loaded on the iconGeneration configuration's classpath, // so we need a classloader that can access these classes. val classLoader = createClassLoader() - val sourceClass = classLoader.loadClass(sourceClassName.get()) - ?: throw GradleException( - "Unable to load ${sourceClassName.get()}. " + - "Is the correct dependency declared on the iconGeneration configuration?" - ) + val sourceClass = + classLoader.loadClass(sourceClassName.get()) + ?: throw GradleException( + "Unable to load ${sourceClassName.get()}. " + + "Is the correct dependency declared on the iconGeneration configuration?" + ) // Step 1) load icon mappings from JSON val mappingsJsonBytes = - classLoader.getResourceAsStream("PlatformIconMappings.json") - ?.use { it.readAllBytes() } + classLoader.getResourceAsStream("PlatformIconMappings.json")?.use { it.readAllBytes() } ?: error("Icon mapping JSON not found") - val iconMappingJson = - json.parseToJsonElement(mappingsJsonBytes.decodeToString()) + val iconMappingJson = json.parseToJsonElement(mappingsJsonBytes.decodeToString()) // Step 2) Transform mappings to a map oldPath -> newPath val iconMapping = readIconMappingJson(iconMappingJson) @@ -136,14 +121,9 @@ open class IconKeysGeneratorTask : DefaultTask() { } private fun createClassLoader(): URLClassLoader { - val arrayOfURLs = configuration.files - .map { it.toURI().toURL() } - .toTypedArray() + val arrayOfURLs = configuration.files.map { it.toURI().toURL() }.toTypedArray() - return URLClassLoader( - arrayOfURLs, - IconKeysGeneratorTask::class.java.classLoader - ) + return URLClassLoader(arrayOfURLs, IconKeysGeneratorTask::class.java.classLoader) } private fun readIconMappingJson(rawMapping: JsonElement): Map { @@ -152,16 +132,11 @@ open class IconKeysGeneratorTask : DefaultTask() { visitMapping(oldUiPath = "", node = rawMapping, map = flattenedMappings) return flattenedMappings - .flatMap { (newPath, oldPaths) -> - oldPaths.map { oldPath -> oldPath to newPath } - }.toMap() + .flatMap { (newPath, oldPaths) -> oldPaths.map { oldPath -> oldPath to newPath } } + .toMap() } - private fun visitMapping( - oldUiPath: String, - node: JsonElement, - map: MutableMap>, - ) { + private fun visitMapping(oldUiPath: String, node: JsonElement, map: MutableMap>) { when (node) { is JsonPrimitive -> { if (!node.isString) return @@ -170,11 +145,7 @@ open class IconKeysGeneratorTask : DefaultTask() { is JsonArray -> { map[oldUiPath] = - node - .filterIsInstance() - .filter { child -> child.isString } - .map { it.content } - .toSet() + node.filterIsInstance().filter { child -> child.isString }.map { it.content }.toSet() } is JsonObject -> { @@ -189,8 +160,7 @@ open class IconKeysGeneratorTask : DefaultTask() { } private fun Field.whileForcingAccessible(action: () -> Unit) { - @Suppress("DEPRECATION") - val wasAccessible = isAccessible + @Suppress("DEPRECATION") val wasAccessible = isAccessible isAccessible = true try { action() @@ -235,11 +205,7 @@ open class IconKeysGeneratorTask : DefaultTask() { parentHolder.keys.sortBy { it.name } } - private fun validatePath( - path: String, - fieldName: String, - classLoader: ClassLoader, - ) { + private fun validatePath(path: String, fieldName: String, classLoader: ClassLoader) { val iconsClass = classLoader.loadClass(sourceClassName.get()) if (iconsClass.getResourceAsStream("/${path.trimStart('/')}") == null) { logger.warn("Icon $fieldName: '$path' does not exist") @@ -249,8 +215,7 @@ open class IconKeysGeneratorTask : DefaultTask() { private fun generateKotlinCode(rootHolder: IconKeyHolder): FileSpec { val className = ClassName.bestGuess(generatedClassName.get()) - return FileSpec - .builder(className) + return FileSpec.builder(className) .apply { indent(" ") addFileComment("Generated by the Jewel icon keys generator\n") @@ -260,8 +225,7 @@ open class IconKeysGeneratorTask : DefaultTask() { val objectName = ClassName.bestGuess(generatedClassName.get()) addType( - TypeSpec - .objectBuilder(objectName) + TypeSpec.objectBuilder(objectName) .apply { for (childHolder in rootHolder.holders) { generateKotlinCodeInner(childHolder, className) @@ -270,16 +234,17 @@ open class IconKeysGeneratorTask : DefaultTask() { for (key in rootHolder.keys) { addProperty(buildIconKeyEntry(key, className)) } - }.build(), + } + .build() ) - }.build() + } + .build() } private fun TypeSpec.Builder.generateKotlinCodeInner(holder: IconKeyHolder, rootClassName: ClassName) { val objectName = holder.name.substringAfterLast('.') addType( - TypeSpec - .objectBuilder(objectName) + TypeSpec.objectBuilder(objectName) .apply { for (childHolder in holder.holders) { generateKotlinCodeInner(childHolder, rootClassName) @@ -288,16 +253,13 @@ open class IconKeysGeneratorTask : DefaultTask() { for (key in holder.keys) { addProperty(buildIconKeyEntry(key, rootClassName)) } - }.build(), + } + .build() ) } - private fun buildIconKeyEntry( - key: IconKey, - rootClassName: ClassName, - ) = - PropertySpec - .builder(key.name.substringAfterLast('.'), keyClassName) + private fun buildIconKeyEntry(key: IconKey, rootClassName: ClassName) = + PropertySpec.builder(key.name.substringAfterLast('.'), keyClassName) .initializer( "%L", "IntelliJIconKey(\"${key.oldPath}\", " + @@ -322,8 +284,4 @@ private data class IconKeyHolder( val keys: MutableList = mutableListOf(), ) -private data class IconKey( - val name: String, - val oldPath: String, - val newPath: String?, -) +private data class IconKey(val name: String, val oldPath: String, val newPath: String?) \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/intellij-theme-generator.gradle.kts b/buildSrc/src/main/kotlin/intellij-theme-generator.gradle.kts index 8c632a040..487fa58ef 100644 --- a/buildSrc/src/main/kotlin/intellij-theme-generator.gradle.kts +++ b/buildSrc/src/main/kotlin/intellij-theme-generator.gradle.kts @@ -17,10 +17,11 @@ extensions.add("intelliJThemeGenerator", extension) extension.all { val task = tasks.register("generate${GUtil.toCamelCase(name)}Theme") { - val paths = this@all.themeClassName.map { - val className = ClassName.bestGuess(it) - className.packageName.replace(".", "/") + "/${className.simpleName}.kt" - } + val paths = + this@all.themeClassName.map { + val className = ClassName.bestGuess(it) + className.packageName.replace(".", "/") + "/${className.simpleName}.kt" + } outputFile = targetDir.file(paths) themeClassName = this@all.themeClassName @@ -38,4 +39,4 @@ extension.all { pluginManager.withPlugin("org.jetbrains.kotlin.jvm") { the().sourceSets["main"].kotlin.srcDir(targetDir) } -} +} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/jewel-check-public-api.gradle.kts b/buildSrc/src/main/kotlin/jewel-check-public-api.gradle.kts index 95653b1f1..2077a8538 100644 --- a/buildSrc/src/main/kotlin/jewel-check-public-api.gradle.kts +++ b/buildSrc/src/main/kotlin/jewel-check-public-api.gradle.kts @@ -10,26 +10,19 @@ plugins { apiValidation { /** - * Set of annotations that exclude API from being public. Typically, it is - * all kinds of `@InternalApi` annotations that mark effectively private - * API that cannot be actually private for technical reasons. + * Set of annotations that exclude API from being public. Typically, it is all kinds of `@InternalApi` annotations + * that mark effectively private API that cannot be actually private for technical reasons. */ nonPublicMarkers.add("org.jetbrains.jewel.InternalJewelApi") } -poko { - pokoAnnotation = "org.jetbrains.jewel.foundation.GenerateDataFunctions" -} +poko { pokoAnnotation = "org.jetbrains.jewel.foundation.GenerateDataFunctions" } -kotlin { - explicitApi() -} +kotlin { explicitApi() } val extension = project.extensions.create("publicApiValidation", ApiValidationExtension::class.java) -with(extension) { - excludedClassRegexes.convention(emptySet()) -} +with(extension) { excludedClassRegexes.convention(emptySet()) } tasks { val validatePublicApi = @@ -41,4 +34,4 @@ tasks { } named("check") { dependsOn(validatePublicApi) } -} +} \ No newline at end of file diff --git a/buildSrc/src/main/kotlin/jewel-publish.gradle.kts b/buildSrc/src/main/kotlin/jewel-publish.gradle.kts index 946438a66..cdbb8dd85 100644 --- a/buildSrc/src/main/kotlin/jewel-publish.gradle.kts +++ b/buildSrc/src/main/kotlin/jewel-publish.gradle.kts @@ -7,26 +7,28 @@ plugins { signing } -val sourcesJar by tasks.registering(Jar::class) { - from(kotlin.sourceSets.main.map { it.kotlin }) - archiveClassifier = "sources" - destinationDirectory = layout.buildDirectory.dir("artifacts") - duplicatesStrategy = DuplicatesStrategy.EXCLUDE -} +val sourcesJar by + tasks.registering(Jar::class) { + from(kotlin.sourceSets.main.map { it.kotlin }) + archiveClassifier = "sources" + destinationDirectory = layout.buildDirectory.dir("artifacts") + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } -val javadocJar by tasks.registering(Jar::class) { - from(tasks.dokkaHtml) - archiveClassifier = "javadoc" - destinationDirectory = layout.buildDirectory.dir("artifacts") - duplicatesStrategy = DuplicatesStrategy.EXCLUDE -} +val javadocJar by + tasks.registering(Jar::class) { + from(tasks.dokkaHtml) + archiveClassifier = "javadoc" + destinationDirectory = layout.buildDirectory.dir("artifacts") + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + } val publishingExtension = extensions.getByType() signing { useInMemoryPgpKeys( System.getenv("PGP_PRIVATE_KEY") ?: properties["signing.privateKey"] as String?, - System.getenv("PGP_PASSWORD") ?: properties["signing.password"] as String? + System.getenv("PGP_PASSWORD") ?: properties["signing.password"] as String?, ) if (project.hasProperty("no-sign")) { diff --git a/buildSrc/src/main/kotlin/jewel.gradle.kts b/buildSrc/src/main/kotlin/jewel.gradle.kts index 3d49d9b00..8a0baa98a 100644 --- a/buildSrc/src/main/kotlin/jewel.gradle.kts +++ b/buildSrc/src/main/kotlin/jewel.gradle.kts @@ -7,36 +7,35 @@ group = "org.jetbrains.jewel" val gitHubRef: String? = System.getenv("GITHUB_REF") -version = when { - properties.containsKey("versionOverride") -> { - val rawVersion = (properties["versionOverride"] as String).trim() - if (!rawVersion.matches("^\\d\\.\\d{2,}\\.\\d+$".toRegex())) { - throw GradleException("Invalid versionOverride: $rawVersion") +version = + when { + properties.containsKey("versionOverride") -> { + val rawVersion = (properties["versionOverride"] as String).trim() + if (!rawVersion.matches("^\\d\\.\\d{2,}\\.\\d+$".toRegex())) { + throw GradleException("Invalid versionOverride: $rawVersion") + } + logger.warn("Using version override: $rawVersion") + rawVersion } - logger.warn("Using version override: $rawVersion") - rawVersion - } - gitHubRef?.startsWith("refs/tags/") == true -> { - gitHubRef.substringAfter("refs/tags/") - .removePrefix("v") - } - properties.containsKey("useCurrentVersion") -> { - val rawVersion = (properties["jewel.release.version"] as String).trim() - if (!rawVersion.matches("^\\d\\.\\d{2,}\\.\\d+$".toRegex())) { - throw GradleException("Invalid jewel.release.version found in gradle.properties: $rawVersion") + gitHubRef?.startsWith("refs/tags/") == true -> { + gitHubRef.substringAfter("refs/tags/").removePrefix("v") + } + properties.containsKey("useCurrentVersion") -> { + val rawVersion = (properties["jewel.release.version"] as String).trim() + if (!rawVersion.matches("^\\d\\.\\d{2,}\\.\\d+$".toRegex())) { + throw GradleException("Invalid jewel.release.version found in gradle.properties: $rawVersion") + } + logger.warn("Using jewel.release.version: $rawVersion") + rawVersion } - logger.warn("Using jewel.release.version: $rawVersion") - rawVersion - } - else -> "1.0.0-SNAPSHOT" -} + else -> "1.0.0-SNAPSHOT" + } val jdkLevel = project.property("jdk.level") as String + kotlin { - jvmToolchain { - languageVersion = JavaLanguageVersion.of(jdkLevel) - } + jvmToolchain { languageVersion = JavaLanguageVersion.of(jdkLevel) } target { compilations.all { kotlinOptions { freeCompilerArgs += "-Xcontext-receivers" } } @@ -58,8 +57,7 @@ detekt { buildUponDefaultConfig = true } -val sarifReport: Provider = - layout.buildDirectory.file("reports/ktlint-${project.name}.sarif") +val sarifReport: Provider = layout.buildDirectory.file("reports/ktlint-${project.name}.sarif") tasks { detektMain { @@ -71,9 +69,7 @@ tasks { } } - formatKotlinMain { - exclude { it.file.absolutePath.replace('\\', '/').contains("build/generated") } - } + formatKotlinMain { exclude { it.file.absolutePath.replace('\\', '/').contains("build/generated") } } lintKotlinMain { exclude { it.file.absolutePath.replace('\\', '/').contains("build/generated") } @@ -82,7 +78,7 @@ tasks { mapOf( "plain" to layout.buildDirectory.file("reports/ktlint-${project.name}.txt").get().asFile, "html" to layout.buildDirectory.file("reports/ktlint-${project.name}.html").get().asFile, - "sarif" to sarifReport.get().asFile + "sarif" to sarifReport.get().asFile, ) } } @@ -93,4 +89,4 @@ configurations.named("sarif") { artifact(tasks.detektMain.flatMap { it.sarifReportFile }) { builtBy(tasks.detektMain) } artifact(sarifReport) { builtBy(tasks.lintKotlinMain) } } -} +} \ No newline at end of file diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/DecoratedWindow.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/DecoratedWindow.kt index 47f5479c6..6cf62700b 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/DecoratedWindow.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/DecoratedWindow.kt @@ -32,16 +32,16 @@ import androidx.compose.ui.window.WindowPlacement import androidx.compose.ui.window.WindowState import androidx.compose.ui.window.rememberWindowState import com.jetbrains.JBR +import java.awt.event.ComponentEvent +import java.awt.event.ComponentListener +import java.awt.event.WindowAdapter +import java.awt.event.WindowEvent import org.jetbrains.jewel.foundation.Stroke import org.jetbrains.jewel.foundation.modifier.border import org.jetbrains.jewel.foundation.modifier.trackWindowActivation import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.window.styling.DecoratedWindowStyle import org.jetbrains.jewel.window.utils.DesktopPlatform -import java.awt.event.ComponentEvent -import java.awt.event.ComponentListener -import java.awt.event.WindowAdapter -import java.awt.event.WindowEvent @Composable public fun DecoratedWindow( @@ -63,7 +63,7 @@ public fun DecoratedWindow( if (!JBR.isAvailable()) { error( "DecoratedWindow can only be used on JetBrainsRuntime(JBR) platform, " + - "please check the document https://github.com/JetBrains/jewel#int-ui-standalone-theme", + "please check the document https://github.com/JetBrains/jewel#int-ui-standalone-theme" ) } } @@ -142,18 +142,17 @@ public fun DecoratedWindow( val undecoratedWindowBorder = if (undecorated && !decoratedWindowState.isMaximized) { Modifier.border( - Stroke.Alignment.Inside, - style.metrics.borderWidth, - style.colors.borderFor(decoratedWindowState).value, - RectangleShape, - ).padding(style.metrics.borderWidth) + Stroke.Alignment.Inside, + style.metrics.borderWidth, + style.colors.borderFor(decoratedWindowState).value, + RectangleShape, + ) + .padding(style.metrics.borderWidth) } else { Modifier } - CompositionLocalProvider( - LocalTitleBarInfo provides TitleBarInfo(title, icon), - ) { + CompositionLocalProvider(LocalTitleBarInfo provides TitleBarInfo(title, icon)) { Layout( content = { val scope = @@ -181,10 +180,7 @@ public interface DecoratedWindowScope : FrameWindowScope { } private object DecoratedWindowMeasurePolicy : MeasurePolicy { - override fun MeasureScope.measure( - measurables: List, - constraints: Constraints, - ): MeasureResult { + override fun MeasureScope.measure(measurables: List, constraints: Constraints): MeasureResult { if (measurables.isEmpty()) { return layout(width = constraints.minWidth, height = constraints.minHeight) {} } @@ -242,13 +238,7 @@ public value class DecoratedWindowState(public val state: ULong) { minimized: Boolean = isMinimized, maximized: Boolean = isMaximized, active: Boolean = isActive, - ): DecoratedWindowState = - of( - fullscreen = fullscreen, - minimized = minimized, - maximized = maximized, - active = active, - ) + ): DecoratedWindowState = of(fullscreen = fullscreen, minimized = minimized, maximized = maximized, active = active) override fun toString(): String = "${javaClass.simpleName}(isFullscreen=$isFullscreen, isActive=$isActive)" @@ -268,7 +258,7 @@ public value class DecoratedWindowState(public val state: ULong) { (if (fullscreen) Fullscreen else 0UL) or (if (minimized) Minimize else 0UL) or (if (maximized) Maximize else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) public fun of(window: ComposeWindow): DecoratedWindowState = @@ -283,7 +273,6 @@ public value class DecoratedWindowState(public val state: ULong) { internal data class TitleBarInfo(val title: String, val icon: Painter?) -internal val LocalTitleBarInfo: ProvidableCompositionLocal = - compositionLocalOf { - error("LocalTitleBarInfo not provided, TitleBar must be used in DecoratedWindow") - } +internal val LocalTitleBarInfo: ProvidableCompositionLocal = compositionLocalOf { + error("LocalTitleBarInfo not provided, TitleBar must be used in DecoratedWindow") +} diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/Theme.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/Theme.kt index 93d672e51..cc0dd7db7 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/Theme.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/Theme.kt @@ -9,9 +9,7 @@ import org.jetbrains.jewel.window.styling.LocalTitleBarStyle import org.jetbrains.jewel.window.styling.TitleBarStyle public val JewelTheme.Companion.defaultTitleBarStyle: TitleBarStyle - @Composable @ReadOnlyComposable - get() = LocalTitleBarStyle.current + @Composable @ReadOnlyComposable get() = LocalTitleBarStyle.current public val JewelTheme.Companion.defaultDecoratedWindowStyle: DecoratedWindowStyle - @Composable @ReadOnlyComposable - get() = LocalDecoratedWindowStyle.current + @Composable @ReadOnlyComposable get() = LocalDecoratedWindowStyle.current diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.Linux.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.Linux.kt index 255604bab..3c86cde9d 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.Linux.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.Linux.kt @@ -14,6 +14,9 @@ import androidx.compose.ui.input.pointer.onPointerEvent import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.unit.dp import com.jetbrains.JBR +import java.awt.Frame +import java.awt.event.MouseEvent +import java.awt.event.WindowEvent import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.ui.component.Icon import org.jetbrains.jewel.ui.component.IconButton @@ -23,9 +26,6 @@ import org.jetbrains.jewel.ui.painter.PainterProvider import org.jetbrains.jewel.ui.painter.PainterProviderScope import org.jetbrains.jewel.ui.painter.PainterSuffixHint import org.jetbrains.jewel.window.styling.TitleBarStyle -import java.awt.Frame -import java.awt.event.MouseEvent -import java.awt.event.WindowEvent @Composable internal fun DecoratedWindowScope.TitleBarOnLinux( @@ -38,12 +38,14 @@ internal fun DecoratedWindowScope.TitleBarOnLinux( val viewConfig = LocalViewConfiguration.current TitleBarImpl( modifier.onPointerEvent(PointerEventType.Press, PointerEventPass.Main) { - if (this.currentEvent.button == PointerButton.Primary && - this.currentEvent.changes.any { changed -> !changed.isConsumed } + if ( + this.currentEvent.button == PointerButton.Primary && + this.currentEvent.changes.any { changed -> !changed.isConsumed } ) { JBR.getWindowMove()?.startMovingTogetherWithMouse(window, MouseEvent.BUTTON1) - if (System.currentTimeMillis() - lastPress in - viewConfig.doubleTapMinTimeMillis..viewConfig.doubleTapTimeoutMillis + if ( + System.currentTimeMillis() - lastPress in + viewConfig.doubleTapMinTimeMillis..viewConfig.doubleTapTimeoutMillis ) { if (state.isMaximized) { window.extendedState = Frame.NORMAL @@ -58,19 +60,10 @@ internal fun DecoratedWindowScope.TitleBarOnLinux( style, { _, _ -> PaddingValues(0.dp) }, ) { state -> - CloseButton( - { window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) }, - state, - style, - ) + CloseButton({ window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) }, state, style) if (state.isMaximized) { - ControlButton( - { window.extendedState = Frame.NORMAL }, - state, - style.icons.restoreButton, - "Restore", - ) + ControlButton({ window.extendedState = Frame.NORMAL }, state, style.icons.restoreButton, "Restore") } else { ControlButton( { window.extendedState = Frame.MAXIMIZED_BOTH }, @@ -79,12 +72,7 @@ internal fun DecoratedWindowScope.TitleBarOnLinux( "Maximize", ) } - ControlButton( - { window.extendedState = Frame.ICONIFIED }, - state, - style.icons.minimizeButton, - "Minimize", - ) + ControlButton({ window.extendedState = Frame.ICONIFIED }, state, style.icons.minimizeButton, "Minimize") content(state) } } @@ -95,14 +83,7 @@ private fun TitleBarScope.CloseButton( state: DecoratedWindowState, style: TitleBarStyle = JewelTheme.defaultTitleBarStyle, ) { - ControlButton( - onClick, - state, - style.icons.closeButton, - "Close", - style, - style.paneCloseButtonStyle, - ) + ControlButton(onClick, state, style.icons.closeButton, "Close", style, style.paneCloseButtonStyle) } @Composable @@ -119,10 +100,7 @@ private fun TitleBarScope.ControlButton( Modifier.align(Alignment.End).focusable(false).size(style.metrics.titlePaneButtonSize), style = iconButtonStyle, ) { - Icon( - painterProvider.getPainter(if (state.isActive) PainterHint else Inactive).value, - description, - ) + Icon(painterProvider.getPainter(if (state.isActive) PainterHint else Inactive).value, description) } } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.MacOS.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.MacOS.kt index d59208df4..4d46f32b1 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.MacOS.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.MacOS.kt @@ -25,17 +25,13 @@ public fun Modifier.newFullscreenControls(newControls: Boolean = true): Modifier }, ) -private class NewFullscreenControlsElement( - val newControls: Boolean, - val inspectorInfo: InspectorInfo.() -> Unit, -) : ModifierNodeElement() { +private class NewFullscreenControlsElement(val newControls: Boolean, val inspectorInfo: InspectorInfo.() -> Unit) : + ModifierNodeElement() { override fun create(): NewFullscreenControlsNode = NewFullscreenControlsNode(newControls) override fun equals(other: Any?): Boolean { if (this === other) return true - val otherModifier = - other as? NewFullscreenControlsElement - ?: return false + val otherModifier = other as? NewFullscreenControlsElement ?: return false return newControls == otherModifier.newControls } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.kt index 6916288c8..8a84e264c 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/TitleBar.kt @@ -38,6 +38,8 @@ import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.offset +import java.awt.Window +import kotlin.math.max import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.foundation.theme.LocalContentColor import org.jetbrains.jewel.foundation.theme.OverrideDarkMode @@ -47,8 +49,6 @@ import org.jetbrains.jewel.ui.util.isDark import org.jetbrains.jewel.window.styling.TitleBarStyle import org.jetbrains.jewel.window.utils.DesktopPlatform import org.jetbrains.jewel.window.utils.macos.MacUtil -import java.awt.Window -import kotlin.math.max internal const val TITLE_BAR_COMPONENT_LAYOUT_ID_PREFIX = "__TITLE_BAR_" @@ -116,26 +116,17 @@ internal fun DecoratedWindowScope.TitleBarImpl( } }, modifier = - modifier.background(backgroundBrush) + modifier + .background(backgroundBrush) .focusProperties { canFocus = false } .layoutId(TITLE_BAR_LAYOUT_ID) .height(style.metrics.height) .onSizeChanged { with(density) { applyTitleBar(it.height.toDp(), state) } } .fillMaxWidth(), - measurePolicy = - rememberTitleBarMeasurePolicy( - window, - state, - applyTitleBar, - ), + measurePolicy = rememberTitleBarMeasurePolicy(window, state, applyTitleBar), ) - Spacer( - Modifier.layoutId(TITLE_BAR_BORDER_LAYOUT_ID) - .height(1.dp) - .fillMaxWidth() - .background(style.colors.border), - ) + Spacer(Modifier.layoutId(TITLE_BAR_BORDER_LAYOUT_ID).height(1.dp).fillMaxWidth().background(style.colors.border)) } internal class TitleBarMeasurePolicy( @@ -143,10 +134,7 @@ internal class TitleBarMeasurePolicy( private val state: DecoratedWindowState, private val applyTitleBar: (Dp, DecoratedWindowState) -> PaddingValues, ) : MeasurePolicy { - override fun MeasureScope.measure( - measurables: List, - constraints: Constraints, - ): MeasureResult { + override fun MeasureScope.measure(measurables: List, constraints: Constraints): MeasureResult { if (measurables.isEmpty()) { return layout(width = constraints.minWidth, height = constraints.minHeight) {} } @@ -236,24 +224,17 @@ internal fun rememberTitleBarMeasurePolicy( window: Window, state: DecoratedWindowState, applyTitleBar: (Dp, DecoratedWindowState) -> PaddingValues, -): MeasurePolicy = - remember(window, state, applyTitleBar) { - TitleBarMeasurePolicy(window, state, applyTitleBar) - } +): MeasurePolicy = remember(window, state, applyTitleBar) { TitleBarMeasurePolicy(window, state, applyTitleBar) } public interface TitleBarScope { public val title: String public val icon: Painter? - @Stable - public fun Modifier.align(alignment: Alignment.Horizontal): Modifier + @Stable public fun Modifier.align(alignment: Alignment.Horizontal): Modifier } -private class TitleBarScopeImpl( - override val title: String, - override val icon: Painter?, -) : TitleBarScope { +private class TitleBarScopeImpl(override val title: String, override val icon: Painter?) : TitleBarScope { override fun Modifier.align(alignment: Alignment.Horizontal): Modifier = this then TitleBarChildDataElement( @@ -288,8 +269,7 @@ private class TitleBarChildDataElement( } } -private class TitleBarChildDataNode( - var horizontalAlignment: Alignment.Horizontal, -) : ParentDataModifierNode, Modifier.Node() { +private class TitleBarChildDataNode(var horizontalAlignment: Alignment.Horizontal) : + ParentDataModifierNode, Modifier.Node() { override fun Density.modifyParentData(parentData: Any?) = this@TitleBarChildDataNode } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/DecoratedWindowStyling.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/DecoratedWindowStyling.kt index 46424ed41..0a17856ab 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/DecoratedWindowStyling.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/DecoratedWindowStyling.kt @@ -22,17 +22,14 @@ public class DecoratedWindowStyle( @Immutable @GenerateDataFunctions -public class DecoratedWindowColors( - public val border: Color, - public val borderInactive: Color, -) { +public class DecoratedWindowColors(public val border: Color, public val borderInactive: Color) { @Composable public fun borderFor(state: DecoratedWindowState): State = rememberUpdatedState( when { !state.isActive -> borderInactive else -> border - }, + } ) public companion object @@ -44,7 +41,6 @@ public class DecoratedWindowMetrics(public val borderWidth: Dp) { public companion object } -public val LocalDecoratedWindowStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No DecoratedWindowStyle provided. Have you forgotten the theme?") - } +public val LocalDecoratedWindowStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No DecoratedWindowStyle provided. Have you forgotten the theme?") +} diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/TitleBarStyling.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/TitleBarStyling.kt index 07f5cf172..a7fd2ae4e 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/TitleBarStyling.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/styling/TitleBarStyling.kt @@ -59,7 +59,7 @@ public class TitleBarColors( when { !state.isActive -> inactiveBackground else -> background - }, + } ) public companion object @@ -87,7 +87,6 @@ public class TitleBarIcons( public companion object } -public val LocalTitleBarStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No TitleBarStyle provided. Have you forgotten the theme?") - } +public val LocalTitleBarStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No TitleBarStyle provided. Have you forgotten the theme?") +} diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/DesktopPlatform.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/DesktopPlatform.kt index a67e83c7f..d135294db 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/DesktopPlatform.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/DesktopPlatform.kt @@ -4,8 +4,7 @@ public enum class DesktopPlatform { Linux, Windows, MacOS, - Unknown, - ; + Unknown; public companion object { public val Current: DesktopPlatform by lazy { diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/JnaLoader.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/JnaLoader.kt index 57f0c6adc..0d8f16e2e 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/JnaLoader.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/JnaLoader.kt @@ -17,9 +17,7 @@ internal object JnaLoader { val time = measureTimeMillis { Native.POINTER_SIZE } logger.info("JNA library (${Native.POINTER_SIZE shl 3}-bit) loaded in $time ms") loaded = true - } catch ( - @Suppress("TooGenericExceptionCaught") t: Throwable, - ) { + } catch (@Suppress("TooGenericExceptionCaught") t: Throwable) { logger.log( Level.WARNING, "Unable to load JNA library(os=${ diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/UnsafeAccessing.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/UnsafeAccessing.kt index b85ac873e..1799e2060 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/UnsafeAccessing.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/UnsafeAccessing.kt @@ -1,9 +1,9 @@ package org.jetbrains.jewel.window.utils -import sun.misc.Unsafe import java.lang.reflect.AccessibleObject import java.util.logging.Level import java.util.logging.Logger +import sun.misc.Unsafe internal object UnsafeAccessing { private val logger = Logger.getLogger(UnsafeAccessing::class.java.simpleName) @@ -13,9 +13,7 @@ internal object UnsafeAccessing { val theUnsafe = Unsafe::class.java.getDeclaredField("theUnsafe") theUnsafe.isAccessible = true theUnsafe.get(null) as Unsafe - } catch ( - @Suppress("TooGenericExceptionCaught") error: Throwable, - ) { + } catch (@Suppress("TooGenericExceptionCaught") error: Throwable) { logger.log(Level.WARNING, "Unsafe accessing initializing failed.", error) null } @@ -35,9 +33,7 @@ internal object UnsafeAccessing { private val implAddOpens by lazy { try { - Module::class.java - .getDeclaredMethod("implAddOpens", String::class.java, Module::class.java) - .accessible() + Module::class.java.getDeclaredMethod("implAddOpens", String::class.java, Module::class.java).accessible() } catch (_: Throwable) { null } @@ -53,10 +49,7 @@ internal object UnsafeAccessing { } } - fun assignAccessibility( - module: Module, - packages: List, - ) { + fun assignAccessibility(module: Module, packages: List) { try { packages.forEach { implAddOpens?.invoke(module, it, ownerModule) } } catch (_: Throwable) { @@ -67,8 +60,7 @@ internal object UnsafeAccessing { private class Parent { var first = false - @Volatile - var second: Any? = null + @Volatile var second: Any? = null } } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/Foundation.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/Foundation.kt index 61e6e8719..8b6952ce5 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/Foundation.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/Foundation.kt @@ -4,12 +4,12 @@ import com.sun.jna.Function import com.sun.jna.Library import com.sun.jna.Native import com.sun.jna.Pointer -import org.jetbrains.jewel.window.utils.JnaLoader import java.lang.reflect.Proxy import java.util.Arrays import java.util.Collections import java.util.logging.Level import java.util.logging.Logger +import org.jetbrains.jewel.window.utils.JnaLoader internal object Foundation { private val logger = Logger.getLogger(Foundation::class.java.simpleName) @@ -22,11 +22,7 @@ internal object Foundation { private val myFoundationLibrary: FoundationLibrary? by lazy { try { - Native.load( - "Foundation", - FoundationLibrary::class.java, - Collections.singletonMap("jna.encoding", "UTF8"), - ) + Native.load("Foundation", FoundationLibrary::class.java, Collections.singletonMap("jna.encoding", "UTF8")) } catch (_: Throwable) { null } @@ -34,26 +30,22 @@ internal object Foundation { private val myObjcMsgSend: Function? by lazy { try { - (Proxy.getInvocationHandler(myFoundationLibrary) as Library.Handler).nativeLibrary.getFunction("objc_msgSend") + (Proxy.getInvocationHandler(myFoundationLibrary) as Library.Handler) + .nativeLibrary + .getFunction("objc_msgSend") } catch (_: Throwable) { null } } - /** - * Get the ID of the NSClass with className - */ + /** Get the ID of the NSClass with className */ fun getObjcClass(className: String?): ID? = myFoundationLibrary?.objc_getClass(className) fun getProtocol(name: String?): ID? = myFoundationLibrary?.objc_getProtocol(name) fun createSelector(s: String?): Pointer? = myFoundationLibrary?.sel_registerName(s) - private fun prepInvoke( - id: ID?, - selector: Pointer?, - args: Array, - ): Array { + private fun prepInvoke(id: ID?, selector: Pointer?, args: Array): Array { val invokArgs = arrayOfNulls(args.size + 2) invokArgs[0] = id invokArgs[1] = selector @@ -62,49 +54,30 @@ internal object Foundation { } // objc_msgSend is called with the calling convention of the target method - // on x86_64 this does not make a difference, but arm64 uses a different calling convention for varargs + // on x86_64 this does not make a difference, but arm64 uses a different calling convention for + // varargs // it is therefore important to not call objc_msgSend as a vararg function - operator fun invoke( - id: ID?, - selector: Pointer?, - vararg args: Any?, - ): ID = ID(myObjcMsgSend?.invokeLong(prepInvoke(id, selector, args)) ?: 0) + operator fun invoke(id: ID?, selector: Pointer?, vararg args: Any?): ID = + ID(myObjcMsgSend?.invokeLong(prepInvoke(id, selector, args)) ?: 0) /** - * Invokes the given vararg selector. - * Expects `NSArray arrayWithObjects:(id), ...` like signature, i.e. exactly one fixed argument, followed by varargs. + * Invokes the given vararg selector. Expects `NSArray arrayWithObjects:(id), ...` like signature, i.e. exactly one + * fixed argument, followed by varargs. */ - fun invokeVarArg( - id: ID?, - selector: Pointer?, - vararg args: Any?, - ): ID { - // c functions and objc methods have at least 1 fixed argument, we therefore need to separate out the first argument - return myFoundationLibrary?.objc_msgSend( - id, - selector, - args[0], - *Arrays.copyOfRange(args, 1, args.size), - ) ?: ID.NIL + fun invokeVarArg(id: ID?, selector: Pointer?, vararg args: Any?): ID { + // c functions and objc methods have at least 1 fixed argument, we therefore need to + // separate out the first argument + return myFoundationLibrary?.objc_msgSend(id, selector, args[0], *Arrays.copyOfRange(args, 1, args.size)) + ?: ID.NIL } - operator fun invoke( - cls: String?, - selector: String?, - vararg args: Any?, - ): ID = invoke(getObjcClass(cls), createSelector(selector), *args) + operator fun invoke(cls: String?, selector: String?, vararg args: Any?): ID = + invoke(getObjcClass(cls), createSelector(selector), *args) - fun invokeVarArg( - cls: String?, - selector: String?, - vararg args: Any?, - ): ID = invokeVarArg(getObjcClass(cls), createSelector(selector), *args) + fun invokeVarArg(cls: String?, selector: String?, vararg args: Any?): ID = + invokeVarArg(getObjcClass(cls), createSelector(selector), *args) - fun safeInvoke( - stringCls: String?, - stringSelector: String?, - vararg args: Any?, - ): ID { + fun safeInvoke(stringCls: String?, stringSelector: String?, vararg args: Any?): ID { val cls = getObjcClass(stringCls) val selector = createSelector(stringSelector) if (!invoke(cls, "respondsToSelector:", selector).booleanValue()) { @@ -113,9 +86,5 @@ internal object Foundation { return invoke(cls, selector, *args) } - operator fun invoke( - id: ID?, - selector: String?, - vararg args: Any?, - ): ID = invoke(id, createSelector(selector), *args) + operator fun invoke(id: ID?, selector: String?, vararg args: Any?): ID = invoke(id, createSelector(selector), *args) } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/FoundationLibrary.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/FoundationLibrary.kt index 316e912b1..3462505fc 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/FoundationLibrary.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/FoundationLibrary.kt @@ -12,18 +12,11 @@ import com.sun.jna.Pointer "ConstPropertyName", ) // Borrowed code internal interface FoundationLibrary : Library { - fun NSLog( - pString: Pointer?, - thing: Any?, - ) + fun NSLog(pString: Pointer?, thing: Any?) fun NSFullUserName(): ID? - fun objc_allocateClassPair( - supercls: ID?, - name: String?, - extraBytes: Int, - ): ID? + fun objc_allocateClassPair(supercls: ID?, name: String?, extraBytes: Int): ID? fun objc_registerClassPair(cls: ID?) @@ -35,12 +28,7 @@ internal interface FoundationLibrary : Library { isExternalRepresentation: Byte, ): ID? - fun CFStringGetCString( - theString: ID?, - buffer: ByteArray?, - bufferSize: Int, - encoding: Int, - ): Byte + fun CFStringGetCString(theString: ID?, buffer: ByteArray?, bufferSize: Int, encoding: Int): Byte fun CFStringGetLength(theString: ID?): Int @@ -62,56 +50,26 @@ internal interface FoundationLibrary : Library { fun objc_getProtocol(name: String?): ID? - fun class_createInstance( - pClass: ID?, - extraBytes: Int, - ): ID? + fun class_createInstance(pClass: ID?, extraBytes: Int): ID? fun sel_registerName(selectorName: String?): Pointer? - fun class_replaceMethod( - cls: ID?, - selName: Pointer?, - impl: Callback?, - types: String?, - ): ID? + fun class_replaceMethod(cls: ID?, selName: Pointer?, impl: Callback?, types: String?): ID? fun objc_getMetaClass(name: String?): ID? /** - * Note: Vararg version. Should only be used only for selectors with a - * single fixed argument followed by varargs. + * Note: Vararg version. Should only be used only for selectors with a single fixed argument followed by varargs. */ - fun objc_msgSend( - receiver: ID?, - selector: Pointer?, - firstArg: Any?, - vararg args: Any?, - ): ID? + fun objc_msgSend(receiver: ID?, selector: Pointer?, firstArg: Any?, vararg args: Any?): ID? + + fun class_respondsToSelector(cls: ID?, selName: Pointer?): Boolean + + fun class_addMethod(cls: ID?, selName: Pointer?, imp: Callback?, types: String?): Boolean + + fun class_addMethod(cls: ID?, selName: Pointer?, imp: ID?, types: String?): Boolean - fun class_respondsToSelector( - cls: ID?, - selName: Pointer?, - ): Boolean - - fun class_addMethod( - cls: ID?, - selName: Pointer?, - imp: Callback?, - types: String?, - ): Boolean - - fun class_addMethod( - cls: ID?, - selName: Pointer?, - imp: ID?, - types: String?, - ): Boolean - - fun class_addProtocol( - aClass: ID?, - protocol: ID?, - ): Boolean + fun class_addProtocol(aClass: ID?, protocol: ID?): Boolean fun class_isMetaClass(cls: ID?): Boolean diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/ID.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/ID.kt index 80ebd59c3..a47c01699 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/ID.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/ID.kt @@ -2,13 +2,11 @@ package org.jetbrains.jewel.window.utils.macos import com.sun.jna.NativeLong -/** - * Could be an address in memory (if pointer to a class or method) or a - * value (like 0 or 1) - */ +/** Could be an address in memory (if pointer to a class or method) or a value (like 0 or 1) */ @Suppress("OVERRIDE_DEPRECATION") // Copied code internal class ID : NativeLong { constructor() + constructor(peer: Long) : super(peer) fun booleanValue(): Boolean = toInt() != 0 @@ -23,7 +21,6 @@ internal class ID : NativeLong { override fun toInt(): Int = super.toInt() companion object { - @JvmField - val NIL = ID(0L) + @JvmField val NIL = ID(0L) } } diff --git a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/MacUtil.kt b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/MacUtil.kt index 7ac2ec8f7..b4beaf296 100644 --- a/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/MacUtil.kt +++ b/decorated-window/src/main/kotlin/org/jetbrains/jewel/window/utils/macos/MacUtil.kt @@ -1,13 +1,13 @@ package org.jetbrains.jewel.window.utils.macos -import org.jetbrains.jewel.window.utils.UnsafeAccessing -import org.jetbrains.jewel.window.utils.accessible import java.awt.Component import java.awt.Window import java.lang.reflect.InvocationTargetException import java.util.logging.Level import java.util.logging.Logger import javax.swing.SwingUtilities +import org.jetbrains.jewel.window.utils.UnsafeAccessing +import org.jetbrains.jewel.window.utils.accessible internal object MacUtil { private val logger = Logger.getLogger(MacUtil::class.java.simpleName) @@ -18,9 +18,7 @@ internal object MacUtil { UnsafeAccessing.desktopModule, listOf("sun.awt", "sun.lwawt", "sun.lwawt.macosx"), ) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Exception, - ) { + } catch (@Suppress("TooGenericExceptionCaught") e: Exception) { logger.log(Level.WARNING, "Assign access for jdk.desktop failed.", e) } } @@ -74,7 +72,8 @@ internal object MacUtil { SwingUtilities.invokeLater { val window = getWindowFromJavaWindow(w) val delegate = Foundation.invoke(window, "delegate") - if (Foundation.invoke(delegate, "respondsToSelector:", Foundation.createSelector("updateColors")) + if ( + Foundation.invoke(delegate, "respondsToSelector:", Foundation.createSelector("updateColors")) .booleanValue() ) { Foundation.invoke(delegate, "updateColors") diff --git a/foundation/build.gradle.kts b/foundation/build.gradle.kts index c2c90b3fb..5f8420d15 100644 --- a/foundation/build.gradle.kts +++ b/foundation/build.gradle.kts @@ -14,7 +14,5 @@ dependencies { api("org.jetbrains.compose.foundation:foundation-desktop:$composeVersion") testImplementation(compose.desktop.uiTestJUnit4) - testImplementation(compose.desktop.currentOs) { - exclude(group = "org.jetbrains.compose.material") - } -} + testImplementation(compose.desktop.currentOs) { exclude(group = "org.jetbrains.compose.material") } +} \ No newline at end of file diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Compatibility.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Compatibility.kt index 18fe0c6ba..336a8840e 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Compatibility.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Compatibility.kt @@ -1,13 +1,12 @@ package org.jetbrains.jewel.foundation /** - * Enables the new compositing strategy for rendering directly into Swing Graphics. This fixes - * z-order problems and artifacts on resizing, but has a performance penalty when using infinitely - * repeating animations. + * Enables the new compositing strategy for rendering directly into Swing Graphics. This fixes z-order problems and + * artifacts on resizing, but has a performance penalty when using infinitely repeating animations. * - * We assume the majority of our users will want this flag to be on, so this convenience function is - * provided to that end. Make sure you call it **before** you initialize any Compose content. The - * function is idempotent and extremely cheap, so you can call it on any entry point. + * We assume the majority of our users will want this flag to be on, so this convenience function is provided to that + * end. Make sure you call it **before** you initialize any Compose content. The function is idempotent and extremely + * cheap, so you can call it on any entry point. */ @ExperimentalJewelApi public fun enableNewSwingCompositing() { diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GenerateDataFunctions.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GenerateDataFunctions.kt index d7f1be727..149e5b042 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GenerateDataFunctions.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GenerateDataFunctions.kt @@ -1,11 +1,9 @@ package org.jetbrains.jewel.foundation /** - * Instructs the Poko compiler plugin to generate equals, hashcode, and - * toString functions for the class it's attached to. + * Instructs the Poko compiler plugin to generate equals, hashcode, and toString functions for the class it's attached + * to. * - * See [this issue](https://github.com/JetBrains/jewel/issues/83) for - * details. + * See [this issue](https://github.com/JetBrains/jewel/issues/83) for details. */ -@Target(AnnotationTarget.CLASS) -public annotation class GenerateDataFunctions +@Target(AnnotationTarget.CLASS) public annotation class GenerateDataFunctions diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalColors.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalColors.kt index 6fb22a4ba..d0f8dc41d 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalColors.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalColors.kt @@ -30,11 +30,7 @@ public class TextColors( @Immutable @GenerateDataFunctions -public class BorderColors( - public val normal: Color, - public val focused: Color, - public val disabled: Color, -) { +public class BorderColors(public val normal: Color, public val focused: Color, public val disabled: Color) { public companion object } @@ -50,7 +46,6 @@ public class OutlineColors( public companion object } -public val LocalGlobalColors: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No GlobalColors provided. Have you forgotten the theme?") - } +public val LocalGlobalColors: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No GlobalColors provided. Have you forgotten the theme?") +} diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalMetrics.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalMetrics.kt index cd3f1942b..3f72ea23d 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalMetrics.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/GlobalMetrics.kt @@ -7,14 +7,10 @@ import androidx.compose.ui.unit.Dp @Immutable @GenerateDataFunctions -public class GlobalMetrics( - public val outlineWidth: Dp, - public val rowHeight: Dp, -) { +public class GlobalMetrics(public val outlineWidth: Dp, public val rowHeight: Dp) { public companion object } -public val LocalGlobalMetrics: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No GlobalMetrics provided. Have you forgotten the theme?") - } +public val LocalGlobalMetrics: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No GlobalMetrics provided. Have you forgotten the theme?") +} diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Stroke.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Stroke.kt index 448c29ac6..1c25f918e 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Stroke.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/Stroke.kt @@ -15,7 +15,8 @@ public sealed class Stroke { @Immutable @GenerateDataFunctions - public class Solid internal constructor( + public class Solid + internal constructor( public val width: Dp, public val color: Color, public val alignment: Alignment, @@ -24,7 +25,8 @@ public sealed class Stroke { @Immutable @GenerateDataFunctions - public class Brush internal constructor( + public class Brush + internal constructor( public val width: Dp, public val brush: androidx.compose.ui.graphics.Brush, public val alignment: Alignment, @@ -38,24 +40,14 @@ public sealed class Stroke { } } -public fun Stroke( - width: Dp, - color: Color, - alignment: Stroke.Alignment, - expand: Dp = Dp.Unspecified, -): Stroke { +public fun Stroke(width: Dp, color: Color, alignment: Stroke.Alignment, expand: Dp = Dp.Unspecified): Stroke { if (width.value == 0f) return Stroke.None if (color.isUnspecified) return Stroke.None return Stroke.Solid(width, color, alignment, expand) } -public fun Stroke( - width: Dp, - brush: Brush, - alignment: Stroke.Alignment, - expand: Dp = Dp.Unspecified, -): Stroke { +public fun Stroke(width: Dp, brush: Brush, alignment: Stroke.Alignment, expand: Dp = Dp.Unspecified): Stroke { if (width.value == 0f) return Stroke.None return when (brush) { is SolidColor -> { diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderContext.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderContext.kt index eee78011e..1f6428cfe 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderContext.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderContext.kt @@ -1,13 +1,7 @@ package org.jetbrains.jewel.foundation.actionSystem public interface DataProviderContext { - public fun set( - key: String, - value: TValue?, - ) + public fun set(key: String, value: TValue?) - public fun lazy( - key: String, - initializer: () -> TValue?, - ) + public fun lazy(key: String, initializer: () -> TValue?) } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderElement.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderElement.kt index ce1794dc6..2f58a8ad9 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderElement.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderElement.kt @@ -2,9 +2,8 @@ package org.jetbrains.jewel.foundation.actionSystem import androidx.compose.ui.node.ModifierNodeElement -internal class DataProviderElement( - val dataProvider: DataProviderContext.() -> Unit, -) : ModifierNodeElement() { +internal class DataProviderElement(val dataProvider: DataProviderContext.() -> Unit) : + ModifierNodeElement() { override fun create(): DataProviderNode = DataProviderNode(dataProvider) override fun update(node: DataProviderNode) { diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderNode.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderNode.kt index 159bab71b..6711c80c1 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderNode.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/DataProviderNode.kt @@ -5,9 +5,8 @@ import androidx.compose.ui.focus.FocusEventModifierNode import androidx.compose.ui.focus.FocusState import androidx.compose.ui.node.TraversableNode -public class DataProviderNode( - public var dataProvider: DataProviderContext.() -> Unit, -) : Modifier.Node(), FocusEventModifierNode, TraversableNode { +public class DataProviderNode(public var dataProvider: DataProviderContext.() -> Unit) : + Modifier.Node(), FocusEventModifierNode, TraversableNode { public var hasFocus: Boolean = false override fun onFocusEvent(focusState: FocusState) { diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/ProvideData.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/ProvideData.kt index 9c9b19604..389d06f4f 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/ProvideData.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/actionSystem/ProvideData.kt @@ -7,15 +7,14 @@ import androidx.compose.ui.focus.FocusEventModifierNode /** * Configure component to provide data for IntelliJ Actions system. * - * Use this modifier to provide context related data that can be used by - * IntelliJ Actions functionality such as Search Everywhere, Action Popups - * etc. + * Use this modifier to provide context related data that can be used by IntelliJ Actions functionality such as Search + * Everywhere, Action Popups etc. * - * Important note: modifiers order is important, so be careful with order - * of [focusable] and [provideData] (see [FocusEventModifierNode]). + * Important note: modifiers order is important, so be careful with order of [focusable] and [provideData] (see + * [FocusEventModifierNode]). * * This can be traversed from Modifier.Node() using Compose traversal API using DataProviderNode as a TraverseKey - * */ @Suppress("unused") -public fun Modifier.provideData(dataProvider: DataProviderContext.() -> Unit): Modifier = this then DataProviderElement(dataProvider) +public fun Modifier.provideData(dataProvider: DataProviderContext.() -> Unit): Modifier = + this then DataProviderElement(dataProvider) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/Keybindings.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/Keybindings.kt index 5123332dd..9c2806239 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/Keybindings.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/Keybindings.kt @@ -20,78 +20,46 @@ public interface SelectableColumnKeybindings { public val PointerKeyboardModifiers.isMultiSelectionKeyPressed: Boolean - /** - * Select First Node. - */ + /** Select First Node. */ public val KeyEvent.isSelectFirstItem: Boolean - /** - * Extend Selection to First Node inherited from Move Caret to Text Start - * with Selection. - */ + /** Extend Selection to First Node inherited from Move Caret to Text Start with Selection. */ public val KeyEvent.isExtendSelectionToFirstItem: Boolean - /** - * Select Last Node inherited from Move Caret to Text End. - */ + /** Select Last Node inherited from Move Caret to Text End. */ public val KeyEvent.isSelectLastItem: Boolean - /** - * Extend Selection to Last Node inherited from Move Caret to Text End with - * Selection. - */ + /** Extend Selection to Last Node inherited from Move Caret to Text End with Selection. */ public val KeyEvent.isExtendSelectionToLastItem: Boolean - /** - * Select Previous Node inherited from Up. - */ + /** Select Previous Node inherited from Up. */ public val KeyEvent.isSelectPreviousItem: Boolean - /** - * Extend Selection with Previous Node inherited from Up with Selection. - */ + /** Extend Selection with Previous Node inherited from Up with Selection. */ public val KeyEvent.isExtendSelectionWithPreviousItem: Boolean - /** - * Select Next Node inherited from Down. - */ + /** Select Next Node inherited from Down. */ public val KeyEvent.isSelectNextItem: Boolean - /** - * Extend Selection with Next Node inherited from Down with Selection. - */ + /** Extend Selection with Next Node inherited from Down with Selection. */ public val KeyEvent.isExtendSelectionWithNextItem: Boolean - /** - * Scroll Page Up and Select Node inherited from Page Up. - */ + /** Scroll Page Up and Select Node inherited from Page Up. */ public val KeyEvent.isScrollPageUpAndSelectItem: Boolean - /** - * Scroll Page Up and Extend Selection inherited from Page Up with - * Selection. - */ + /** Scroll Page Up and Extend Selection inherited from Page Up with Selection. */ public val KeyEvent.isScrollPageUpAndExtendSelection: Boolean - /** - * Scroll Page Down and Select Node inherited from Page Down. - */ + /** Scroll Page Down and Select Node inherited from Page Down. */ public val KeyEvent.isScrollPageDownAndSelectItem: Boolean - /** - * Scroll Page Down and Extend Selection inherited from Page Down with - * Selection. - */ + /** Scroll Page Down and Extend Selection inherited from Page Down with Selection. */ public val KeyEvent.isScrollPageDownAndExtendSelection: Boolean - /** - * Edit item. - */ + /** Edit item. */ public val KeyEvent.isEdit: Boolean - /** - * Select all items. - */ + /** Select all items. */ public val KeyEvent.isSelectAll: Boolean } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableColumnOnKeyEvent.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableColumnOnKeyEvent.kt index 28f77b4f1..542b7a96a 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableColumnOnKeyEvent.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableColumnOnKeyEvent.kt @@ -1,19 +1,14 @@ package org.jetbrains.jewel.foundation.lazy -import org.jetbrains.jewel.foundation.lazy.SelectableLazyListKey.Selectable import kotlin.math.max import kotlin.math.min +import org.jetbrains.jewel.foundation.lazy.SelectableLazyListKey.Selectable public interface SelectableColumnOnKeyEvent { public val keybindings: SelectableColumnKeybindings - /** - * Select First Node. - */ - public fun onSelectFirstItem( - allKeys: List, - state: SelectableLazyListState, - ) { + /** Select First Node. */ + public fun onSelectFirstItem(allKeys: List, state: SelectableLazyListState) { for (index in allKeys.indices) { val key = allKeys[index] if (key is Selectable) { @@ -24,19 +19,10 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Extend Selection to First Node inherited from Move Caret to Text Start - * with Selection. - */ - public fun onExtendSelectionToFirst( - keys: List, - state: SelectableLazyListState, - ) { + /** Extend Selection to First Node inherited from Move Caret to Text Start with Selection. */ + public fun onExtendSelectionToFirst(keys: List, state: SelectableLazyListState) { val initialIndex = state.lastActiveItemIndex ?: return - val newSelection = - HashSet(max(initialIndex, state.selectedKeys.size)).apply { - addAll(state.selectedKeys) - } + val newSelection = HashSet(max(initialIndex, state.selectedKeys.size)).apply { addAll(state.selectedKeys) } var lastActiveItemIndex = initialIndex for (index in initialIndex - 1 downTo 0) { val key = keys[index] @@ -49,13 +35,8 @@ public interface SelectableColumnOnKeyEvent { state.selectedKeys = newSelection } - /** - * Select Last Node inherited from Move Caret to Text End. - */ - public fun onSelectLastItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Select Last Node inherited from Move Caret to Text End. */ + public fun onSelectLastItem(keys: List, state: SelectableLazyListState) { for (index in keys.lastIndex downTo 0) { val key = keys[index] if (key is Selectable) { @@ -66,19 +47,11 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Extend Selection to Last Node inherited from Move Caret to Text End with - * Selection. - */ - public fun onExtendSelectionToLastItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Extend Selection to Last Node inherited from Move Caret to Text End with Selection. */ + public fun onExtendSelectionToLastItem(keys: List, state: SelectableLazyListState) { val initialIndex = state.lastActiveItemIndex ?: return val newSelection = - HashSet(max(keys.size - initialIndex, state.selectedKeys.size)).apply { - addAll(state.selectedKeys) - } + HashSet(max(keys.size - initialIndex, state.selectedKeys.size)).apply { addAll(state.selectedKeys) } var lastActiveItemIndex = initialIndex for (index in initialIndex + 1..keys.lastIndex) { val key = keys[index] @@ -91,13 +64,8 @@ public interface SelectableColumnOnKeyEvent { state.selectedKeys = newSelection } - /** - * Select Previous Node inherited from Up. - */ - public fun onSelectPreviousItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Select Previous Node inherited from Up. */ + public fun onSelectPreviousItem(keys: List, state: SelectableLazyListState) { val initialIndex = state.lastActiveItemIndex ?: return for (index in initialIndex - 1 downTo 0) { val key = keys[index] @@ -109,13 +77,8 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Extend Selection with Previous Node inherited from Up with Selection. - */ - public fun onExtendSelectionWithPreviousItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Extend Selection with Previous Node inherited from Up with Selection. */ + public fun onExtendSelectionWithPreviousItem(keys: List, state: SelectableLazyListState) { // todo we need deselect if we are changing direction val initialIndex = state.lastActiveItemIndex ?: return for (index in initialIndex - 1 downTo 0) { @@ -128,13 +91,8 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Select Next Node inherited from Down. - */ - public fun onSelectNextItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Select Next Node inherited from Down. */ + public fun onSelectNextItem(keys: List, state: SelectableLazyListState) { val initialIndex = state.lastActiveItemIndex ?: return for (index in initialIndex + 1..keys.lastIndex) { val key = keys[index] @@ -146,13 +104,8 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Extend Selection with Next Node inherited from Down with Selection. - */ - public fun onExtendSelectionWithNextItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Extend Selection with Next Node inherited from Down with Selection. */ + public fun onExtendSelectionWithNextItem(keys: List, state: SelectableLazyListState) { // todo we need deselect if we are changing direction val initialIndex = state.lastActiveItemIndex ?: return for (index in initialIndex + 1..keys.lastIndex) { @@ -165,27 +118,16 @@ public interface SelectableColumnOnKeyEvent { } } - /** - * Scroll Page Up and Select Node inherited from Page Up. - */ - public fun onScrollPageUpAndSelectItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Scroll Page Up and Select Node inherited from Page Up. */ + public fun onScrollPageUpAndSelectItem(keys: List, state: SelectableLazyListState) { val visibleSize = state.layoutInfo.visibleItemsInfo.size val targetIndex = max((state.lastActiveItemIndex ?: 0) - visibleSize, 0) state.selectedKeys = setOf(keys[targetIndex].key) state.lastActiveItemIndex = targetIndex } - /** - * Scroll Page Up and Extend Selection inherited from Page Up with - * Selection. - */ - public fun onScrollPageUpAndExtendSelection( - keys: List, - state: SelectableLazyListState, - ) { + /** Scroll Page Up and Extend Selection inherited from Page Up with Selection. */ + public fun onScrollPageUpAndExtendSelection(keys: List, state: SelectableLazyListState) { val visibleSize = state.layoutInfo.visibleItemsInfo.size val targetIndex = max((state.lastActiveItemIndex ?: 0) - visibleSize, 0) val newSelectionList = @@ -198,58 +140,39 @@ public interface SelectableColumnOnKeyEvent { state.lastActiveItemIndex = targetIndex } - /** - * Scroll Page Down and Select Node inherited from Page Down. - */ - public fun onScrollPageDownAndSelectItem( - keys: List, - state: SelectableLazyListState, - ) { + /** Scroll Page Down and Select Node inherited from Page Down. */ + public fun onScrollPageDownAndSelectItem(keys: List, state: SelectableLazyListState) { val visibleSize = state.layoutInfo.visibleItemsInfo.size val targetIndex = min((state.lastActiveItemIndex ?: 0) + visibleSize, keys.lastIndex) state.selectedKeys = setOf(keys[targetIndex].key) state.lastActiveItemIndex = targetIndex } - /** - * Scroll Page Down and Extend Selection inherited from Page Down with - * Selection. - */ - public fun onScrollPageDownAndExtendSelection( - keys: List, - state: SelectableLazyListState, - ) { + /** Scroll Page Down and Extend Selection inherited from Page Down with Selection. */ + public fun onScrollPageDownAndExtendSelection(keys: List, state: SelectableLazyListState) { val visibleSize = state.layoutInfo.visibleItemsInfo.size val targetIndex = min((state.lastActiveItemIndex ?: 0) + visibleSize, keys.lastIndex) val newSelectionList = - keys.subList(state.lastActiveItemIndex ?: 0, targetIndex) - .filterIsInstance() - .let { state.selectedKeys + it.map { selectableKey -> selectableKey.key } } + keys.subList(state.lastActiveItemIndex ?: 0, targetIndex).filterIsInstance().let { + state.selectedKeys + it.map { selectableKey -> selectableKey.key } + } state.selectedKeys = newSelectionList state.lastActiveItemIndex = targetIndex } - /** - * Edit Item. - */ + /** Edit Item. */ public fun onEdit() { // IntelliJ focuses the first element with an issue when this is pressed. // It is thus unavailable here. } - /** - * Select All. - */ - public fun onSelectAll( - keys: List, - state: SelectableLazyListState, - ) { + /** Select All. */ + public fun onSelectAll(keys: List, state: SelectableLazyListState) { state.selectedKeys = keys.filterIsInstance().map { it.key }.toSet() } } -public open class DefaultSelectableOnKeyEvent( - override val keybindings: SelectableColumnKeybindings, -) : SelectableColumnOnKeyEvent { +public open class DefaultSelectableOnKeyEvent(override val keybindings: SelectableColumnKeybindings) : + SelectableColumnOnKeyEvent { public companion object : DefaultSelectableOnKeyEvent(DefaultSelectableColumnKeybindings) } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumn.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumn.kt index 4fb325bf2..d3f4e74d5 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumn.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumn.kt @@ -41,10 +41,7 @@ import org.jetbrains.jewel.foundation.lazy.tree.DefaultSelectableLazyColumnKeyAc import org.jetbrains.jewel.foundation.lazy.tree.KeyActions import org.jetbrains.jewel.foundation.lazy.tree.PointerEventActions -/** - * A composable that displays a scrollable and selectable list of items in - * a column arrangement. - */ +/** A composable that displays a scrollable and selectable list of items in a column arrangement. */ @Composable public fun SelectableLazyColumn( modifier: Modifier = Modifier, @@ -69,10 +66,11 @@ public fun SelectableLazyColumn( val latestOnSelectedIndexesChanged = rememberUpdatedState(onSelectedIndexesChanged) LaunchedEffect(state, container) { - snapshotFlow { state.selectedKeys }.collect { selectedKeys -> - val indices = selectedKeys.mapNotNull { key -> container.getKeyIndex(key) } - latestOnSelectedIndexesChanged.value.invoke(indices) - } + snapshotFlow { state.selectedKeys } + .collect { selectedKeys -> + val indices = selectedKeys.mapNotNull { key -> container.getKeyIndex(key) } + latestOnSelectedIndexesChanged.value.invoke(indices) + } } val focusManager = LocalFocusManager.current val focusRequester = remember { FocusRequester() } @@ -97,9 +95,7 @@ public fun SelectableLazyColumn( return@onPreviewKeyEvent true } if (state.lastActiveItemIndex != null) { - val actionHandled = - keyActions.handleOnKeyEvent(event, keys, state, selectionMode) - .invoke(event) + val actionHandled = keyActions.handleOnKeyEvent(event, keys, state, selectionMode).invoke(event) if (actionHandled) { scope.launch { state.lastActiveItemIndex?.let { state.scrollToItem(it) } } } @@ -144,10 +140,7 @@ private fun LazyListScope.appendEntry( is Entry.Item -> item(entry.key, entry.contentType) { val itemScope = - SelectableLazyItemScope( - isSelected = entry.key in state.selectedKeys, - isActive = isFocused, - ) + SelectableLazyItemScope(isSelected = entry.key in state.selectedKeys, isActive = isFocused) if (isKeySelectable(entry.key)) { Box( modifier = @@ -159,7 +152,7 @@ private fun LazyListScope.appendEntry( selectableState = state, allKeys = keys, itemKey = entry.key, - ), + ) ) { entry.content.invoke(itemScope) } @@ -169,11 +162,7 @@ private fun LazyListScope.appendEntry( } is Entry.Items -> - items( - count = entry.count, - key = { entry.key(it) }, - contentType = { entry.contentType(it) }, - ) { index -> + items(count = entry.count, key = { entry.key(it) }, contentType = { entry.contentType(it) }) { index -> val key = remember(entry, index) { entry.key(index) } val itemScope = SelectableLazyItemScope(key in state.selectedKeys, isFocused) if (isKeySelectable(key)) { @@ -187,7 +176,7 @@ private fun LazyListScope.appendEntry( selectableState = state, allKeys = keys, itemKey = entry.key(index), - ), + ) ) { entry.itemContent.invoke(itemScope, index) } @@ -210,13 +199,14 @@ private fun LazyListScope.appendEntry( selectableState = state, allKeys = keys, itemKey = entry.key, - ), + ) ) { entry.content.invoke(itemScope) } } else { - SelectableLazyItemScope(entry.key in state.selectedKeys, isFocused) - .apply { entry.content.invoke(itemScope) } + SelectableLazyItemScope(entry.key in state.selectedKeys, isFocused).apply { + entry.content.invoke(itemScope) + } } } } @@ -230,23 +220,24 @@ private fun Modifier.selectable( selectableState: SelectableLazyListState, allKeys: List, itemKey: Any, -) = pointerInput(allKeys, itemKey) { - awaitPointerEventScope { - while (true) { - val event = awaitPointerEvent() - when (event.type) { - PointerEventType.Press -> { - requester?.requestFocus() - actionHandler.handlePointerEventPress( - pointerEvent = event, - keybindings = keybindings, - selectableLazyListState = selectableState, - selectionMode = selectionMode, - allKeys = allKeys, - key = itemKey, - ) +) = + pointerInput(allKeys, itemKey) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent() + when (event.type) { + PointerEventType.Press -> { + requester?.requestFocus() + actionHandler.handlePointerEventPress( + pointerEvent = event, + keybindings = keybindings, + selectableLazyListState = selectableState, + selectionMode = selectionMode, + allKeys = allKeys, + key = itemKey, + ) + } } } } } -} diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListScope.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListScope.kt index 205c35be8..30d22550a 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListScope.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListScope.kt @@ -6,17 +6,14 @@ import androidx.compose.runtime.Composable import org.jetbrains.jewel.foundation.lazy.SelectableLazyListKey.NotSelectable import org.jetbrains.jewel.foundation.lazy.SelectableLazyListKey.Selectable -/** - * Interface defining the scope for building a selectable lazy list. - */ +/** Interface defining the scope for building a selectable lazy list. */ public interface SelectableLazyListScope { /** * Represents an item in a selectable lazy list. * * @param key The unique identifier for the item. * @param contentType The type of content displayed in the item. - * @param selectable Determines if the item is selectable. Default is - * `true`. + * @param selectable Determines if the item is selectable. Default is `true`. * @param content The content of the item as a composable function. */ public fun item( @@ -30,14 +27,11 @@ public interface SelectableLazyListScope { * Represents a list of items based on the provided parameters. * * @param count The number of items in the list. - * @param key A function that generates a unique key for each item based on - * its index. - * @param contentType A function that returns the content type of an item - * based on its index. Defaults to `null`. - * @param selectable A function that determines if an item is selectable - * based on its index. Defaults to `true`. - * @param itemContent The content of each individual item, specified as a - * composable function that takes the item's index as a parameter. + * @param key A function that generates a unique key for each item based on its index. + * @param contentType A function that returns the content type of an item based on its index. Defaults to `null`. + * @param selectable A function that determines if an item is selectable based on its index. Defaults to `true`. + * @param itemContent The content of each individual item, specified as a composable function that takes the item's + * index as a parameter. */ public fun items( count: Int, @@ -53,8 +47,7 @@ public interface SelectableLazyListScope { * @param key The unique identifier for the sticky header. * @param contentType The type of content in the sticky header. * @param selectable Specifies whether the sticky header is selectable. - * @param content The content to be displayed in the sticky header, - * provided as a composable function + * @param content The content to be displayed in the sticky header, provided as a composable function */ public fun stickyHeader( key: Any, @@ -66,9 +59,8 @@ public interface SelectableLazyListScope { internal class SelectableLazyListScopeContainer : SelectableLazyListScope { /** - * Provides a set of keys that cannot be selected. - * Here we use an assumption that amount of selectable items >> amount of non-selectable items. - * So, for optimization we will keep only this set. + * Provides a set of keys that cannot be selected. Here we use an assumption that amount of selectable items >> + * amount of non-selectable items. So, for optimization we will keep only this set. * * @see [isKeySelectable] */ @@ -130,7 +122,8 @@ internal class SelectableLazyListScopeContainer : SelectableLazyListScope { selectable: (index: Int) -> Boolean, itemContent: @Composable (SelectableLazyItemScope.(index: Int) -> Unit), ) { - // TODO: [performance] now the implementation requires O(count) operations but should be done in ~ O(1) + // TODO: [performance] now the implementation requires O(count) operations but should be + // done in ~ O(1) for (index in 0 until count) { val isSelectable = selectable(index) val currentKey = key(index) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListState.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListState.kt index 0fe6559ad..ae80b1574 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListState.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyListState.kt @@ -24,14 +24,12 @@ public interface SelectableScope { } /** - * State object for a selectable lazy list, which extends - * [ScrollableState]. + * State object for a selectable lazy list, which extends [ScrollableState]. * * @param lazyListState The state object for the underlying lazy list. */ -public class SelectableLazyListState( - public val lazyListState: LazyListState, -) : ScrollableState by lazyListState, SelectableScope { +public class SelectableLazyListState(public val lazyListState: LazyListState) : + ScrollableState by lazyListState, SelectableScope { internal var lastKeyEventUsedMouse: Boolean = false override var selectedKeys: Set by mutableStateOf(emptySet()) @@ -43,20 +41,12 @@ public class SelectableLazyListState( * @param animateScroll Whether to animate the scroll to the focused item. * @param scrollOffset The scroll offset for the focused item. */ - public suspend fun scrollToItem( - itemIndex: Int, - animateScroll: Boolean = false, - scrollOffset: Int = 0, - ) { + public suspend fun scrollToItem(itemIndex: Int, animateScroll: Boolean = false, scrollOffset: Int = 0) { val visibleRange = visibleItemsRange.drop(2).dropLast(4) if (itemIndex !in visibleRange && visibleRange.isNotEmpty()) { when { itemIndex < visibleRange.first() -> - lazyListState.scrollToItem( - max(0, itemIndex - 2), - animateScroll, - scrollOffset, - ) + lazyListState.scrollToItem(max(0, itemIndex - 2), animateScroll, scrollOffset) itemIndex > visibleRange.last() -> lazyListState.scrollToItem( @@ -72,34 +62,27 @@ public class SelectableLazyListState( public val layoutInfo: LazyListLayoutInfo get() = lazyListState.layoutInfo - /** - * The index of the first item that is visible. - */ + /** The index of the first item that is visible. */ public val firstVisibleItemIndex: Int get() = lazyListState.firstVisibleItemIndex /** - * The scroll offset of the first visible item. Scrolling forward is - * positive - i.e., the amount that the item is offset backwards. + * The scroll offset of the first visible item. Scrolling forward is positive - i.e., the amount that the item is + * offset backwards. */ @Suppress("unused") public val firstVisibleItemScrollOffset: Int get() = lazyListState.firstVisibleItemScrollOffset /** - * [InteractionSource] that will be used to dispatch drag events when - * this list is being dragged. If you want to know whether the fling - * (or animated scroll) is in progress, use [isScrollInProgress]. + * [InteractionSource] that will be used to dispatch drag events when this list is being dragged. If you want to + * know whether the fling (or animated scroll) is in progress, use [isScrollInProgress]. */ public val interactionSource: InteractionSource get() = lazyListState.interactionSource } -private suspend fun LazyListState.scrollToItem( - index: Int, - animate: Boolean, - scrollOffset: Int = 0, -) { +private suspend fun LazyListState.scrollToItem(index: Int, animate: Boolean, scrollOffset: Int = 0) { if (animate) { animateScrollToItem(index, scrollOffset) } else { @@ -107,13 +90,9 @@ private suspend fun LazyListState.scrollToItem( } } -/** - * Represents a selectable key used in a selectable lazy list. - */ +/** Represents a selectable key used in a selectable lazy list. */ public sealed class SelectableLazyListKey { - /** - * The key associated with the item. - */ + /** The key associated with the item. */ public abstract val key: Any /** @@ -121,18 +100,14 @@ public sealed class SelectableLazyListKey { * * @param key The key associated with the item. */ - public class Selectable( - override val key: Any, - ) : SelectableLazyListKey() + public class Selectable(override val key: Any) : SelectableLazyListKey() /** * Represents a non-selectable item key. * * @param key The key associated with the item. */ - public class NotSelectable( - override val key: Any, - ) : SelectableLazyListKey() + public class NotSelectable(override val key: Any) : SelectableLazyListKey() override fun equals(other: Any?): Boolean { if (this === other) return true @@ -151,23 +126,15 @@ public interface SelectableLazyItemScope : LazyItemScope { public val isActive: Boolean } -/** - * Specifies the selection mode for a selectable lazy list. - */ +/** Specifies the selection mode for a selectable lazy list. */ public enum class SelectionMode { - /** - * No selection is allowed. - */ + /** No selection is allowed. */ None, - /** - * Only a single item can be selected. - */ + /** Only a single item can be selected. */ Single, - /** - * Multiple items can be selected. - */ + /** Multiple items can be selected. */ Multiple, } @@ -175,17 +142,13 @@ public enum class SelectionMode { * Remembers the state of a selectable lazy list. * * @param firstVisibleItemIndex The index of the first visible item. - * @param firstVisibleItemScrollOffset The scroll offset of the first - * visible item. + * @param firstVisibleItemScrollOffset The scroll offset of the first visible item. * @return The remembered state of the selectable lazy list. */ @Composable public fun rememberSelectableLazyListState( firstVisibleItemIndex: Int = 0, firstVisibleItemScrollOffset: Int = 0, -): SelectableLazyListState = - remember { - SelectableLazyListState( - LazyListState(firstVisibleItemIndex, firstVisibleItemScrollOffset), - ) - } +): SelectableLazyListState = remember { + SelectableLazyListState(LazyListState(firstVisibleItemIndex, firstVisibleItemScrollOffset)) +} diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BasicLazyTree.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BasicLazyTree.kt index 32c446433..28f81cc39 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BasicLazyTree.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BasicLazyTree.kt @@ -24,6 +24,8 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.foundation.lazy.SelectableLazyColumn import org.jetbrains.jewel.foundation.lazy.SelectableLazyItemScope import org.jetbrains.jewel.foundation.lazy.SelectionMode @@ -37,48 +39,31 @@ import org.jetbrains.jewel.foundation.state.CommonStateBitMask.Pressed import org.jetbrains.jewel.foundation.state.CommonStateBitMask.Selected import org.jetbrains.jewel.foundation.state.FocusableComponentState import org.jetbrains.jewel.foundation.state.SelectableComponentState -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds /** * Renders a lazy tree view based on the provided tree data structure. * * @param tree The tree structure to be rendered. * @param selectionMode The selection mode for the tree nodes. - * @param onElementClick Callback function triggered when a tree node is - * clicked. - * @param elementBackgroundFocused The background color of a tree node when - * focused. - * @param elementBackgroundSelectedFocused The background color of a - * selected tree node when focused. - * @param elementBackgroundSelected The background color of a selected tree - * node. - * @param indentSize The size of the indent for each level of the tree - * node. - * @param elementBackgroundCornerSize The corner size of the background - * shape of a tree node. + * @param onElementClick Callback function triggered when a tree node is clicked. + * @param elementBackgroundFocused The background color of a tree node when focused. + * @param elementBackgroundSelectedFocused The background color of a selected tree node when focused. + * @param elementBackgroundSelected The background color of a selected tree node. + * @param indentSize The size of the indent for each level of the tree node. + * @param elementBackgroundCornerSize The corner size of the background shape of a tree node. * @param elementPadding The padding for the entire tree node. - * @param elementContentPadding The padding for the content within a tree - * node. + * @param elementContentPadding The padding for the content within a tree node. * @param elementMinHeight The minimum height of a tree node. - * @param chevronContentGap The gap between the chevron icon and the node - * content. + * @param chevronContentGap The gap between the chevron icon and the node content. * @param treeState The state object for managing the tree view state. - * @param modifier Optional modifier for styling or positioning the tree - * view. - * @param onElementDoubleClick Callback function triggered when a tree node - * is double-clicked. - * @param onSelectionChange Callback function triggered when the selected - * tree nodes change. - * @param platformDoubleClickDelay The duration between two consecutive - * clicks to be considered a double-click. + * @param modifier Optional modifier for styling or positioning the tree view. + * @param onElementDoubleClick Callback function triggered when a tree node is double-clicked. + * @param onSelectionChange Callback function triggered when the selected tree nodes change. + * @param platformDoubleClickDelay The duration between two consecutive clicks to be considered a double-click. * @param keyActions The key binding actions for the tree view. - * @param pointerEventScopedActions The pointer event actions for the tree - * view. - * @param chevronContent The composable function responsible for rendering - * the chevron icon. - * @param nodeContent The composable function responsible for rendering the - * content of a tree node. + * @param pointerEventScopedActions The pointer event actions for the tree view. + * @param chevronContent The composable function responsible for rendering the chevron icon. + * @param nodeContent The composable function responsible for rendering the content of a tree node. * * @suppress("UNCHECKED_CAST") * @@ -112,16 +97,15 @@ public fun BasicLazyTree( val scope = rememberCoroutineScope() val flattenedTree = - remember(tree, treeState.openNodes, treeState.allNodes) { - tree.roots.flatMap { it.flattenTree(treeState) } - } + remember(tree, treeState.openNodes, treeState.allNodes) { tree.roots.flatMap { it.flattenTree(treeState) } } remember(tree) { // if tree changes we need to update selection changes onSelectionChange( - flattenedTree.asSequence() + flattenedTree + .asSequence() .filter { it.id in treeState.delegate.selectedKeys } .map { element -> element as Tree.Element } - .toList(), + .toList() ) } @@ -136,30 +120,21 @@ public fun BasicLazyTree( }, interactionSource = remember { MutableInteractionSource() }, ) { - itemsIndexed( - items = flattenedTree, - key = { _, item -> item.id }, - contentType = { _, item -> item.data }, - ) { index, element -> + itemsIndexed(items = flattenedTree, key = { _, item -> item.id }, contentType = { _, item -> item.data }) { + index, + element -> val elementState = TreeElementState.of( active = isActive, selected = isSelected, - expanded = - (element as? Tree.Element.Node) - ?.let { it.id in treeState.openNodes } - ?: false, + expanded = (element as? Tree.Element.Node)?.let { it.id in treeState.openNodes } ?: false, ) val backgroundShape by derivedStateOf { val hasRoundedTopCorners = - flattenedTree.getOrNull(index - 1)?.id?.let { - it !in treeState.delegate.selectedKeys - } ?: true + flattenedTree.getOrNull(index - 1)?.id?.let { it !in treeState.delegate.selectedKeys } ?: true val hasRoundedBottomCorners = - flattenedTree.getOrNull(index + 1)?.id?.let { - it !in treeState.delegate.selectedKeys - } ?: true + flattenedTree.getOrNull(index + 1)?.id?.let { it !in treeState.delegate.selectedKeys } ?: true val topCornerSize = computerCornerSize(hasRoundedTopCorners, elementBackgroundCornerSize) val bottomCornerSize = computerCornerSize(hasRoundedBottomCorners, elementBackgroundCornerSize) RoundedCornerShape( @@ -183,18 +158,14 @@ public fun BasicLazyTree( ) .padding(elementContentPadding) .padding(start = (element.depth * indentSize.value).dp) - .clickable( - interactionSource = remember { MutableInteractionSource() }, - indication = null, - ) { - (pointerEventScopedActions as? DefaultTreeViewPointerEventAction) - ?.notifyItemClicked( - item = flattenedTree[index] as Tree.Element, - scope = scope, - doubleClickTimeDelayMillis = platformDoubleClickDelay.inWholeMilliseconds, - onElementClick = onElementClick, - onElementDoubleClick = onElementDoubleClick, - ) + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { + (pointerEventScopedActions as? DefaultTreeViewPointerEventAction)?.notifyItemClicked( + item = flattenedTree[index] as Tree.Element, + scope = scope, + doubleClickTimeDelayMillis = platformDoubleClickDelay.inWholeMilliseconds, + onElementClick = onElementClick, + onElementDoubleClick = onElementDoubleClick, + ) treeState.delegate.lastActiveItemIndex = index }, ) { @@ -207,7 +178,7 @@ public fun BasicLazyTree( ) { treeState.toggleNode(element.id) onElementDoubleClick(element as Tree.Element) - }, + } ) { chevronContent(elementState) } @@ -219,10 +190,8 @@ public fun BasicLazyTree( } } -private fun computerCornerSize( - isRounded: Boolean, - cornerSize: CornerSize, -) = if (isRounded) cornerSize else CornerSize(0.dp) +private fun computerCornerSize(isRounded: Boolean, cornerSize: CornerSize) = + if (isRounded) cornerSize else CornerSize(0.dp) private fun Modifier.elementBackground( state: TreeElementState, @@ -230,21 +199,21 @@ private fun Modifier.elementBackground( focused: Color, selected: Color, backgroundShape: RoundedCornerShape, -) = background( - color = - when { - state.isActive && state.isSelected -> selectedFocused - state.isActive && !state.isSelected -> focused - state.isSelected && !state.isActive -> selected - else -> Color.Unspecified - }, - shape = backgroundShape, -) +) = + background( + color = + when { + state.isActive && state.isSelected -> selectedFocused + state.isActive && !state.isSelected -> focused + state.isSelected && !state.isActive -> selected + else -> Color.Unspecified + }, + shape = backgroundShape, + ) @Immutable @JvmInline -public value class TreeElementState(public val state: ULong) : - FocusableComponentState, SelectableComponentState { +public value class TreeElementState(public val state: ULong) : FocusableComponentState, SelectableComponentState { @Stable override val isActive: Boolean get() = state and Active != 0UL @@ -317,7 +286,7 @@ public value class TreeElementState(public val state: ULong) : (if (pressed) Pressed else 0UL) or (if (hovered) Hovered else 0UL) or (if (selected) Selected else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } @@ -347,10 +316,8 @@ private fun Tree.Element<*>.flattenTree(state: TreeState): MutableList.getAllSubNodes(node: Tree.Element.Node<*>) { - node.children - ?.filterIsInstance>() - ?.forEach { - add(it.id) - this@getAllSubNodes getAllSubNodes (it) - } + node.children?.filterIsInstance>()?.forEach { + add(it.id) + this@getAllSubNodes getAllSubNodes (it) + } } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BuildTree.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BuildTree.kt index b8cb83070..8963c72c1 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BuildTree.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/BuildTree.kt @@ -1,8 +1,8 @@ package org.jetbrains.jewel.foundation.lazy.tree -import org.jetbrains.jewel.foundation.GenerateDataFunctions import java.io.File import java.nio.file.Path +import org.jetbrains.jewel.foundation.GenerateDataFunctions public fun buildTree(builder: TreeBuilder.() -> Unit): Tree = TreeBuilder().apply(builder).build() @@ -10,8 +10,7 @@ public class TreeBuilder : TreeGeneratorScope { public sealed class Element { public abstract val id: Any? - @GenerateDataFunctions - public class Leaf(public val data: T, override val id: Any?) : Element() + @GenerateDataFunctions public class Leaf(public val data: T, override val id: Any?) : Element() @GenerateDataFunctions public class Node( @@ -23,18 +22,11 @@ public class TreeBuilder : TreeGeneratorScope { private val heads = mutableListOf>() - override fun addLeaf( - data: T, - id: Any?, - ) { + override fun addLeaf(data: T, id: Any?) { heads.add(Element.Leaf(data, id)) } - override fun addNode( - data: T, - id: Any?, - childrenGenerator: ChildrenGeneratorScope.() -> Unit, - ) { + override fun addNode(data: T, id: Any?, childrenGenerator: ChildrenGeneratorScope.() -> Unit) { heads.add(Element.Node(data, id, childrenGenerator)) } @@ -45,9 +37,7 @@ public class TreeBuilder : TreeGeneratorScope { public fun build(): Tree { val elements = mutableListOf>() for (index in heads.indices) { - val previous: Tree.Element? = - elements.getOrNull(index - 1) - ?.let { evaluatePrevious(it) } + val previous: Tree.Element? = elements.getOrNull(index - 1)?.let { evaluatePrevious(it) } val current = getCurrentTreeElement(index, previous) elements.add(current) @@ -56,33 +46,31 @@ public class TreeBuilder : TreeGeneratorScope { return Tree(elements) } - private fun getCurrentTreeElement( - index: Int, - previous: Tree.Element?, - ) = when (val elementBuilder = heads[index]) { - is Element.Leaf -> - Tree.Element.Leaf( - data = elementBuilder.data, - depth = 0, - childIndex = index, - parent = null, - previous = previous, - next = null, - id = elementBuilder.id ?: "$index", - ) - - is Element.Node -> - Tree.Element.Node( - data = elementBuilder.data, - depth = 0, - childIndex = index, - parent = null, - childrenGenerator = { parent -> generateElements(parent, elementBuilder) }, - previous = previous, - next = null, - id = elementBuilder.id ?: "$index", - ) - } + private fun getCurrentTreeElement(index: Int, previous: Tree.Element?) = + when (val elementBuilder = heads[index]) { + is Element.Leaf -> + Tree.Element.Leaf( + data = elementBuilder.data, + depth = 0, + childIndex = index, + parent = null, + previous = previous, + next = null, + id = elementBuilder.id ?: "$index", + ) + + is Element.Node -> + Tree.Element.Node( + data = elementBuilder.data, + depth = 0, + childIndex = index, + parent = null, + childrenGenerator = { parent -> generateElements(parent, elementBuilder) }, + previous = previous, + next = null, + id = elementBuilder.id ?: "$index", + ) + } } private fun generateElements( @@ -136,23 +124,15 @@ private fun evaluatePrevious(element: Tree.Element): Tree.Element = } public interface TreeGeneratorScope { - public fun addNode( - data: T, - id: Any? = null, - childrenGenerator: ChildrenGeneratorScope.() -> Unit = {}, - ) + public fun addNode(data: T, id: Any? = null, childrenGenerator: ChildrenGeneratorScope.() -> Unit = {}) - public fun addLeaf( - data: T, - id: Any? = null, - ) + public fun addLeaf(data: T, id: Any? = null) public fun add(element: TreeBuilder.Element) } public class ChildrenGeneratorScope(private val parentElement: Tree.Element.Node) : TreeGeneratorScope { - @GenerateDataFunctions - public class ParentInfo(public val data: T, public val depth: Int, public val index: Int) + @GenerateDataFunctions public class ParentInfo(public val data: T, public val depth: Int, public val index: Int) public val parent: ParentInfo by lazy { ParentInfo(parentElement.data, parentElement.depth, parentElement.childIndex) @@ -160,18 +140,11 @@ public class ChildrenGeneratorScope(private val parentElement: Tree.Element.N internal val elements = mutableListOf>() - override fun addLeaf( - data: T, - id: Any?, - ) { + override fun addLeaf(data: T, id: Any?) { elements.add(TreeBuilder.Element.Leaf(data, id)) } - override fun addNode( - data: T, - id: Any?, - childrenGenerator: ChildrenGeneratorScope.() -> Unit, - ) { + override fun addNode(data: T, id: Any?, childrenGenerator: ChildrenGeneratorScope.() -> Unit) { elements.add(TreeBuilder.Element.Node(data, id, childrenGenerator)) } @@ -182,16 +155,14 @@ public class ChildrenGeneratorScope(private val parentElement: Tree.Element.N public fun Path.asTree(isOpen: (File) -> Boolean = { false }): Tree = toFile().asTree(isOpen) -public fun File.asTree(isOpen: (File) -> Boolean = { false }): Tree = - buildTree { - addNode(this@asTree, isOpen(this@asTree)) { - generateFileNodes(isOpen) - } - } +public fun File.asTree(isOpen: (File) -> Boolean = { false }): Tree = buildTree { + addNode(this@asTree, isOpen(this@asTree)) { generateFileNodes(isOpen) } +} private fun ChildrenGeneratorScope.generateFileNodes(isOpen: (File) -> Boolean) { val files = parent.data.listFiles() ?: return - files.sortedBy { if (it.isDirectory) "a" else "b" } + files + .sortedBy { if (it.isDirectory) "a" else "b" } .forEach { file -> when { file.isFile -> addLeaf(file, file.absolutePath) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewKeybindings.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewKeybindings.kt index 7e9c50914..b1a8a8f80 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewKeybindings.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewKeybindings.kt @@ -37,34 +37,22 @@ public open class DefaultTreeViewKeybindings : DefaultSelectableColumnKeybinding } public interface TreeViewKeybindings : SelectableColumnKeybindings { - /** - * Select Parent Node. - */ + /** Select Parent Node. */ public val KeyEvent.isSelectParent: Boolean - /** - * Extend Selection to Parent Node inherited from Left with Selection. - */ + /** Extend Selection to Parent Node inherited from Left with Selection. */ public val KeyEvent.isExtendSelectionToParent: Boolean - /** - * Select Child Node inherited from Right. - */ + /** Select Child Node inherited from Right. */ public val KeyEvent.isSelectChild: Boolean - /** - * Extend Selection to Child Node inherited from Right with Selection. - */ + /** Extend Selection to Child Node inherited from Right with Selection. */ public val KeyEvent.isExtendSelectionToChild: Boolean - /** - * Select Next Sibling Node. - */ + /** Select Next Sibling Node. */ public val KeyEvent.isSelectNextSibling: Boolean - /** - * Select Previous Sibling Node. - */ + /** Select Previous Sibling Node. */ public val KeyEvent.isSelectPreviousSibling: Boolean } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewOnKeyEvent.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewOnKeyEvent.kt index 36003b79f..2a9dd3b9f 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewOnKeyEvent.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/DefaultTreeViewOnKeyEvent.kt @@ -7,10 +7,7 @@ public open class DefaultTreeViewOnKeyEvent( override val keybindings: TreeViewKeybindings, private val treeState: TreeState, ) : TreeViewOnKeyEvent { - override fun onSelectParent( - keys: List, - state: SelectableLazyListState, - ) { + override fun onSelectParent(keys: List, state: SelectableLazyListState) { val currentKey = keys[state.lastActiveItemIndex ?: 0].key val keyNodeList = treeState.allNodes.map { it.first } @@ -21,11 +18,7 @@ public open class DefaultTreeViewOnKeyEvent( } } - private fun handleNodeCase( - currentKey: Any, - keys: List, - state: SelectableLazyListState, - ) { + private fun handleNodeCase(currentKey: Any, keys: List, state: SelectableLazyListState) { if (treeState.openNodes.contains(currentKey)) { treeState.toggleNode(currentKey) return @@ -38,7 +31,8 @@ public open class DefaultTreeViewOnKeyEvent( .reversed() .firstOrNull { it.second < currentNode.second } ?.let { (parentNodeKey, _) -> - keys.first { it.key == parentNodeKey } + keys + .first { it.key == parentNodeKey } .takeIf { it is SelectableLazyListKey.Selectable } ?.let { state.lastActiveItemIndex = @@ -68,15 +62,9 @@ public open class DefaultTreeViewOnKeyEvent( } } - override fun onSelectChild( - keys: List, - state: SelectableLazyListState, - ) { + override fun onSelectChild(keys: List, state: SelectableLazyListState) { val currentKey = keys[state.lastActiveItemIndex ?: 0].key - if ( - currentKey in treeState.allNodes.map { it.first } && - currentKey !in treeState.openNodes - ) { + if (currentKey in treeState.allNodes.map { it.first } && currentKey !in treeState.openNodes) { treeState.toggleNode(currentKey) } else { super.onSelectNextItem(keys, state) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/KeyActions.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/KeyActions.kt index cc2a177b7..89b417320 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/KeyActions.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/KeyActions.kt @@ -125,27 +125,24 @@ public open class DefaultSelectableLazyColumnEventAction : PointerEventActions { } else { lastFocussed downTo currentIndex } - val keys = - buildList { - for (i in indexInterval) { - val currentKey = allKeys[i] - if ( - currentKey is SelectableLazyListKey.Selectable && - !state.selectedKeys.contains(allKeys[i].key) - ) { - add(currentKey.key) - } + val keys = buildList { + for (i in indexInterval) { + val currentKey = allKeys[i] + if ( + currentKey is SelectableLazyListKey.Selectable && !state.selectedKeys.contains(allKeys[i].key) + ) { + add(currentKey.key) } } + } state.selectedKeys += keys state.lastActiveItemIndex = allKeys.indexOfFirst { it.key == key } } } } -public class DefaultTreeViewPointerEventAction( - private val treeState: TreeState, -) : DefaultSelectableLazyColumnEventAction() { +public class DefaultTreeViewPointerEventAction(private val treeState: TreeState) : + DefaultSelectableLazyColumnEventAction() { override fun handlePointerEventPress( pointerEvent: PointerEvent, keybindings: SelectableColumnKeybindings, @@ -157,8 +154,7 @@ public class DefaultTreeViewPointerEventAction( with(keybindings) { when { pointerEvent.keyboardModifiers.isContiguousSelectionKeyPressed && - pointerEvent.keyboardModifiers.isCtrlPressed -> { - } + pointerEvent.keyboardModifiers.isCtrlPressed -> {} pointerEvent.keyboardModifiers.isContiguousSelectionKeyPressed -> { super.onExtendSelectionToKey(key, allKeys, selectableLazyListState, selectionMode) @@ -224,48 +220,46 @@ public class DefaultTreeViewKeyActions( keys: List, state: SelectableLazyListState, selectionMode: SelectionMode, - ): KeyEvent.() -> Boolean = - lambda@{ - if (type == KeyEventType.KeyUp) return@lambda false - val keyEvent = this - with(keybindings) { - with(actions) { - if (selectionMode == SelectionMode.None) return@lambda false - when { - isSelectParent -> onSelectParent(keys, state) - isSelectChild -> onSelectChild(keys, state) - super.handleOnKeyEvent(event, keys, state, selectionMode).invoke(keyEvent) -> - return@lambda true + ): KeyEvent.() -> Boolean = lambda@{ + if (type == KeyEventType.KeyUp) return@lambda false + val keyEvent = this + with(keybindings) { + with(actions) { + if (selectionMode == SelectionMode.None) return@lambda false + when { + isSelectParent -> onSelectParent(keys, state) + isSelectChild -> onSelectChild(keys, state) + super.handleOnKeyEvent(event, keys, state, selectionMode).invoke(keyEvent) -> return@lambda true - else -> return@lambda false - } + else -> return@lambda false } } - return@lambda true } + return@lambda true + } } public open class DefaultSelectableLazyColumnKeyActions( override val keybindings: SelectableColumnKeybindings, override val actions: SelectableColumnOnKeyEvent = DefaultSelectableOnKeyEvent(keybindings), ) : KeyActions { - public companion object : DefaultSelectableLazyColumnKeyActions( - when { - hostOs.isMacOS -> DefaultMacOsSelectableColumnKeybindings - else -> DefaultSelectableColumnKeybindings - }, - ) + public companion object : + DefaultSelectableLazyColumnKeyActions( + when { + hostOs.isMacOS -> DefaultMacOsSelectableColumnKeybindings + else -> DefaultSelectableColumnKeybindings + } + ) override fun handleOnKeyEvent( event: KeyEvent, keys: List, state: SelectableLazyListState, selectionMode: SelectionMode, - ): KeyEvent.() -> Boolean = - lambda@{ - if (type == KeyEventType.KeyUp || selectionMode == SelectionMode.None) return@lambda false - with(keybindings) { with(actions) { execute(keys, state, selectionMode) } } - } + ): KeyEvent.() -> Boolean = lambda@{ + if (type == KeyEventType.KeyUp || selectionMode == SelectionMode.None) return@lambda false + with(keybindings) { with(actions) { execute(keys, state, selectionMode) } } + } context(SelectableColumnKeybindings, SelectableColumnOnKeyEvent) private fun KeyEvent.execute( diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/Tree.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/Tree.kt index 020d8fe27..7325c20da 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/Tree.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/Tree.kt @@ -2,8 +2,7 @@ package org.jetbrains.jewel.foundation.lazy.tree import org.jetbrains.jewel.foundation.lazy.tree.Tree.Element.Node -@Suppress("UNCHECKED_CAST") -public fun emptyTree(): Tree = Tree.EMPTY as Tree +@Suppress("UNCHECKED_CAST") public fun emptyTree(): Tree = Tree.EMPTY as Tree public class Tree internal constructor(public val roots: List>) { public companion object { @@ -12,22 +11,21 @@ public class Tree internal constructor(public val roots: List>) { public fun isEmpty(): Boolean = roots.isEmpty() - private fun walk(breathFirst: Boolean) = - sequence { - val queue = roots.toMutableList() - while (queue.isNotEmpty()) { - val next = queue.removeFirst() - yield(next) - if (next is Node) { - next.open() - if (breathFirst) { - queue.addAll(next.children.orEmpty()) - } else { - queue.addAll(0, next.children.orEmpty()) - } + private fun walk(breathFirst: Boolean) = sequence { + val queue = roots.toMutableList() + while (queue.isNotEmpty()) { + val next = queue.removeFirst() + yield(next) + if (next is Node) { + next.open() + if (breathFirst) { + queue.addAll(next.children.orEmpty()) + } else { + queue.addAll(0, next.children.orEmpty()) } } } + } public fun walkBreadthFirst(): Sequence> = walk(true) @@ -44,23 +42,19 @@ public class Tree internal constructor(public val roots: List>) { public fun path(): List> = buildList { - var next: Element? = this@Element - while (next != null) { - add(next) - next = next.parent + var next: Element? = this@Element + while (next != null) { + add(next) + next = next.parent + } } - } .reversed() - public fun previousElementsIterable(): Iterable> = - Iterable { - elementIterator(previous) { it.previous } - } + public fun previousElementsIterable(): Iterable> = Iterable { + elementIterator(previous) { it.previous } + } - public fun nextElementsIterable(): Iterable> = - Iterable { - elementIterator(next) { it.next } - } + public fun nextElementsIterable(): Iterable> = Iterable { elementIterator(next) { it.next } } public class Leaf( override val data: T, @@ -116,9 +110,7 @@ public class Tree internal constructor(public val roots: List>) { public fun close() { detachChildren() - children?.asSequence() - ?.filterIsInstance>() - ?.forEach { it.closeRecursively() } + children?.asSequence()?.filterIsInstance>()?.forEach { it.closeRecursively() } } private fun closeRecursively() { @@ -128,10 +120,7 @@ public class Tree internal constructor(public val roots: List>) { } } -private fun elementIterator( - initial: Tree.Element?, - next: (Tree.Element) -> Tree.Element?, -) = iterator { +private fun elementIterator(initial: Tree.Element?, next: (Tree.Element) -> Tree.Element?) = iterator { var current = initial ?: return@iterator yield(current) while (true) { diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeState.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeState.kt index 608fb2fe5..002c9b0a1 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeState.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeState.kt @@ -17,9 +17,8 @@ public fun rememberTreeState( selectableLazyListState: SelectableLazyListState = SelectableLazyListState(lazyListState), ): TreeState = remember { TreeState(selectableLazyListState) } -public class TreeState( - internal val delegate: SelectableLazyListState, -) : SelectableScope by delegate, ScrollableState by delegate { +public class TreeState(internal val delegate: SelectableLazyListState) : + SelectableScope by delegate, ScrollableState by delegate { internal val allNodes = mutableStateListOf>() public var openNodes: Set by mutableStateOf>(emptySet()) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeViewOnKeyEvent.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeViewOnKeyEvent.kt index 3e6d3c46f..264a462ba 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeViewOnKeyEvent.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/lazy/tree/TreeViewOnKeyEvent.kt @@ -5,19 +5,9 @@ import org.jetbrains.jewel.foundation.lazy.SelectableLazyListKey import org.jetbrains.jewel.foundation.lazy.SelectableLazyListState public interface TreeViewOnKeyEvent : SelectableColumnOnKeyEvent { - /** - * Select Parent Node. - */ - public fun onSelectParent( - keys: List, - state: SelectableLazyListState, - ) + /** Select Parent Node. */ + public fun onSelectParent(keys: List, state: SelectableLazyListState) - /** - * Select Child Node inherited from Right. - */ - public fun onSelectChild( - keys: List, - state: SelectableLazyListState, - ) + /** Select Child Node inherited from Right. */ + public fun onSelectChild(keys: List, state: SelectableLazyListState) } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Activation.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Activation.kt index 64533c770..2da36ec2e 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Activation.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Activation.kt @@ -33,7 +33,7 @@ public fun Modifier.trackWindowActivation(window: Window): Modifier = debugInspectorInfo { name = "activateRoot" properties["window"] = window - }, + } ) { var parentActivated by remember { mutableStateOf(false) } @@ -59,7 +59,7 @@ public fun Modifier.trackComponentActivation(awtParent: Component): Modifier = debugInspectorInfo { name = "activateRoot" properties["parent"] = awtParent - }, + } ) { var parentActivated by remember { mutableStateOf(false) } @@ -83,9 +83,7 @@ public fun Modifier.trackComponentActivation(awtParent: Component): Modifier = @Stable public fun Modifier.trackActivation(): Modifier = - composed( - debugInspectorInfo { name = "trackActivation" }, - ) { + composed(debugInspectorInfo { name = "trackActivation" }) { val activatedModifierLocal = remember { ActivatedModifierLocal() } Modifier.focusGroup() .onFocusChanged { @@ -108,9 +106,7 @@ private class ActivatedModifierLocal : ModifierLocalProvider, ModifierL } override val key: ProvidableModifierLocal = ModifierLocalActivated - override val value: Boolean by derivedStateOf(structuralEqualityPolicy()) { - parentActivated && hasFocus - } + override val value: Boolean by derivedStateOf(structuralEqualityPolicy()) { parentActivated && hasFocus } fun childLostFocus() { hasFocus = false @@ -123,10 +119,7 @@ private class ActivatedModifierLocal : ModifierLocalProvider, ModifierL public val ModifierLocalActivated: ProvidableModifierLocal = modifierLocalOf { false } -public fun Modifier.onActivated( - enabled: Boolean = true, - onChanged: (Boolean) -> Unit, -): Modifier = +public fun Modifier.onActivated(enabled: Boolean = true, onChanged: (Boolean) -> Unit): Modifier = this then if (enabled) { ActivateChangedModifierElement( diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Border.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Border.kt index 9fb556e3a..b3a0f9093 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Border.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/modifier/Border.kt @@ -36,19 +36,16 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.isUnspecified import androidx.compose.ui.unit.takeOrElse import androidx.compose.ui.unit.toSize +import kotlin.math.ceil +import kotlin.math.min import org.jetbrains.jewel.foundation.Stroke import org.jetbrains.jewel.foundation.grow import org.jetbrains.jewel.foundation.hasAtLeastOneNonRoundedCorner import org.jetbrains.jewel.foundation.shrink -import kotlin.math.ceil -import kotlin.math.min public typealias DrawScopeStroke = androidx.compose.ui.graphics.drawscope.Stroke -public fun Modifier.border( - stroke: Stroke, - shape: Shape, -): Modifier = +public fun Modifier.border(stroke: Stroke, shape: Shape): Modifier = when (stroke) { is Stroke.None -> this is Stroke.Solid -> border(stroke.alignment, stroke.width, stroke.color, shape, stroke.expand) @@ -102,8 +99,7 @@ private fun Modifier.drawBorderWithAlignment( drawContent() val strokeWidthPx = - min(if (width == Dp.Hairline) 1f else width.toPx(), size.minDimension / 2) - .coerceAtLeast(1f) + min(if (width == Dp.Hairline) 1f else width.toPx(), size.minDimension / 2).coerceAtLeast(1f) val expandWidthPx = expand.takeOrElse { 0.dp }.toPx() @@ -157,37 +153,14 @@ private fun ContentDrawScope.drawBorderInner( expandWidthPx = expandWidthPx, ) - else -> - drawRectBorder( - borderCacheRef, - alignment, - outline, - brush, - strokeWidthPx, - expandWidthPx, - ) + else -> drawRectBorder(borderCacheRef, alignment, outline, brush, strokeWidthPx, expandWidthPx) } } - is Outline.Rounded -> - drawRoundedBorder( - borderCacheRef, - alignment, - outline, - brush, - strokeWidthPx, - expandWidthPx, - ) + is Outline.Rounded -> drawRoundedBorder(borderCacheRef, alignment, outline, brush, strokeWidthPx, expandWidthPx) is Outline.Generic -> - cacheDrawScope.drawGenericBorder( - borderCacheRef, - alignment, - outline, - brush, - strokeWidthPx, - expandWidthPx, - ) + cacheDrawScope.drawGenericBorder(borderCacheRef, alignment, outline, brush, strokeWidthPx, expandWidthPx) } } @@ -205,19 +178,18 @@ private class BorderCache( var targetImageBitmap = imageBitmap var targetCanvas = canvas val compatibleConfig = - targetImageBitmap?.config == ImageBitmapConfig.Argb8888 || - config == targetImageBitmap?.config + targetImageBitmap?.config == ImageBitmapConfig.Argb8888 || config == targetImageBitmap?.config @Suppress("ComplexCondition") - if (targetImageBitmap == null || - targetCanvas == null || - size.width > targetImageBitmap.width || - size.height > targetImageBitmap.height || - !compatibleConfig + if ( + targetImageBitmap == null || + targetCanvas == null || + size.width > targetImageBitmap.width || + size.height > targetImageBitmap.height || + !compatibleConfig ) { targetImageBitmap = - ImageBitmap(borderSize.width, borderSize.height, config = config) - .also { imageBitmap = it } + ImageBitmap(borderSize.width, borderSize.height, config = config).also { imageBitmap = it } targetCanvas = Canvas(targetImageBitmap).also { canvas = it } } @@ -274,13 +246,12 @@ private fun ContentDrawScope.drawRoundedBorder( // Note: why do we need this? The Outline API can handle it just fine val cache = borderCacheRef.obtain() val borderPath = - cache.obtainPath() - .apply { - reset() - fillType = PathFillType.EvenOdd - addRoundRect(roundRect.shrink(strokeWidthPx / 2f)) - addRoundRect(roundRect.grow(strokeWidthPx / 2f)) - } + cache.obtainPath().apply { + reset() + fillType = PathFillType.EvenOdd + addRoundRect(roundRect.shrink(strokeWidthPx / 2f)) + addRoundRect(roundRect.grow(strokeWidthPx / 2f)) + } drawPath(borderPath, brush) } else { drawOutline(Outline.Rounded(roundRect), brush, style = DrawScopeStroke(strokeWidthPx)) @@ -294,100 +265,92 @@ private fun CacheDrawScope.drawGenericBorder( brush: Brush, strokeWidth: Float, expandWidthPx: Float, -): DrawResult = - onDrawWithContent { - drawContent() - - // Get the outer border and inner border inflate delta, - // the part between inner and outer is the border that - // needs to be drawn - val (outer, inner) = - when (alignment) { - // Inside border means the outer border inflate delta is 0 - Stroke.Alignment.Inside -> 0f + expandWidthPx to -strokeWidth + expandWidthPx - Stroke.Alignment.Center -> strokeWidth / 2f + expandWidthPx to -strokeWidth / 2f + expandWidthPx - Stroke.Alignment.Outside -> strokeWidth + expandWidthPx to 0f + expandWidthPx - } - - when (outer) { - inner -> return@onDrawWithContent - // Simply draw the outline when abs(outer) and abs(inner) are the same - -inner -> drawOutline(outline, brush, style = DrawScopeStroke(outer * 2f)) - else -> { - val config: ImageBitmapConfig - val colorFilter: ColorFilter? - if (brush is SolidColor) { - config = ImageBitmapConfig.Alpha8 - colorFilter = ColorFilter.tint(brush.value) - } else { - config = ImageBitmapConfig.Argb8888 - colorFilter = null - } - val pathBounds = outline.path.getBounds().inflate(outer) - val borderCache = borderCacheRef.obtain() - val outerMaskPath = - borderCache.obtainPath().apply { - reset() - addRect(pathBounds) - op(this, outline.path, PathOperation.Difference) - } - val cacheImageBitmap: ImageBitmap - val pathBoundsSize = - IntSize( - ceil(pathBounds.width).toInt(), - ceil(pathBounds.height).toInt(), - ) +): DrawResult = onDrawWithContent { + drawContent() - with(borderCache) { - cacheImageBitmap = - drawBorderCache( - pathBoundsSize, - config, - ) { - translate(-pathBounds.left, -pathBounds.top) { - if (inner < 0f && outer > 0f) { - TODO("Not implemented for generic border") - } + // Get the outer border and inner border inflate delta, + // the part between inner and outer is the border that + // needs to be drawn + val (outer, inner) = + when (alignment) { + // Inside border means the outer border inflate delta is 0 + Stroke.Alignment.Inside -> 0f + expandWidthPx to -strokeWidth + expandWidthPx + Stroke.Alignment.Center -> strokeWidth / 2f + expandWidthPx to -strokeWidth / 2f + expandWidthPx + Stroke.Alignment.Outside -> strokeWidth + expandWidthPx to 0f + expandWidthPx + } - if (outer > 0f && inner >= 0f) { - drawPath(outline.path, brush, style = DrawScopeStroke(outer * 2f)) + when (outer) { + inner -> return@onDrawWithContent + // Simply draw the outline when abs(outer) and abs(inner) are the same + -inner -> drawOutline(outline, brush, style = DrawScopeStroke(outer * 2f)) + else -> { + val config: ImageBitmapConfig + val colorFilter: ColorFilter? + if (brush is SolidColor) { + config = ImageBitmapConfig.Alpha8 + colorFilter = ColorFilter.tint(brush.value) + } else { + config = ImageBitmapConfig.Argb8888 + colorFilter = null + } + val pathBounds = outline.path.getBounds().inflate(outer) + val borderCache = borderCacheRef.obtain() + val outerMaskPath = + borderCache.obtainPath().apply { + reset() + addRect(pathBounds) + op(this, outline.path, PathOperation.Difference) + } + val cacheImageBitmap: ImageBitmap + val pathBoundsSize = IntSize(ceil(pathBounds.width).toInt(), ceil(pathBounds.height).toInt()) + + with(borderCache) { + cacheImageBitmap = + drawBorderCache(pathBoundsSize, config) { + translate(-pathBounds.left, -pathBounds.top) { + if (inner < 0f && outer > 0f) { + TODO("Not implemented for generic border") + } - if (inner > 0f) { - drawPath( - path = outline.path, - brush = brush, - blendMode = BlendMode.Clear, - style = DrawScopeStroke(inner * 2f), - ) - } + if (outer > 0f && inner >= 0f) { + drawPath(outline.path, brush, style = DrawScopeStroke(outer * 2f)) - drawPath(path = outline.path, brush = brush, blendMode = BlendMode.Clear) + if (inner > 0f) { + drawPath( + path = outline.path, + brush = brush, + blendMode = BlendMode.Clear, + style = DrawScopeStroke(inner * 2f), + ) } - if (outer <= 0f && inner < 0f) { - drawPath(path = outline.path, brush = brush, style = DrawScopeStroke(-inner * 2f)) + drawPath(path = outline.path, brush = brush, blendMode = BlendMode.Clear) + } - if (outer < 0f) { - drawPath( - path = outline.path, - brush = brush, - blendMode = BlendMode.Clear, - style = DrawScopeStroke(-outer * 2f), - ) - } + if (outer <= 0f && inner < 0f) { + drawPath(path = outline.path, brush = brush, style = DrawScopeStroke(-inner * 2f)) - drawPath(path = outerMaskPath, brush = brush, blendMode = BlendMode.Clear) + if (outer < 0f) { + drawPath( + path = outline.path, + brush = brush, + blendMode = BlendMode.Clear, + style = DrawScopeStroke(-outer * 2f), + ) } + + drawPath(path = outerMaskPath, brush = brush, blendMode = BlendMode.Clear) } } - } - - onDrawWithContent { - drawContent() - translate(pathBounds.left, pathBounds.top) { - drawImage(cacheImageBitmap, srcSize = pathBoundsSize, colorFilter = colorFilter) } + } + + onDrawWithContent { + drawContent() + translate(pathBounds.left, pathBounds.top) { + drawImage(cacheImageBitmap, srcSize = pathBoundsSize, colorFilter = colorFilter) } } } } +} diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/state/FocusableComponentState.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/state/FocusableComponentState.kt index bd10dd7b7..0a0d75d23 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/state/FocusableComponentState.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/state/FocusableComponentState.kt @@ -7,14 +7,7 @@ public interface FocusableComponentState : InteractiveComponentState { public val isFocused: Boolean @Composable - public fun chooseValue( - normal: T, - disabled: T, - focused: T, - pressed: T, - hovered: T, - active: T, - ): T = + public fun chooseValue(normal: T, disabled: T, focused: T, pressed: T, hovered: T, active: T): T = when { !isEnabled -> disabled isPressed && !JewelTheme.isSwingCompatMode -> pressed diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/JewelTheme.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/JewelTheme.kt index 5435675e0..f129f994a 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/JewelTheme.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/JewelTheme.kt @@ -15,74 +15,45 @@ import org.jetbrains.jewel.foundation.LocalGlobalMetrics public interface JewelTheme { public companion object { public val name: String - @Composable - @ReadOnlyComposable - get() = LocalThemeName.current + @Composable @ReadOnlyComposable get() = LocalThemeName.current public val globalColors: GlobalColors - @Composable - @ReadOnlyComposable - get() = LocalGlobalColors.current + @Composable @ReadOnlyComposable get() = LocalGlobalColors.current public val globalMetrics: GlobalMetrics - @Composable - @ReadOnlyComposable - get() = LocalGlobalMetrics.current + @Composable @ReadOnlyComposable get() = LocalGlobalMetrics.current @Deprecated("Use defaultTextStyle instead", ReplaceWith("JewelTheme.defaultTextStyle"), DeprecationLevel.ERROR) public val textStyle: TextStyle - @Composable - @ReadOnlyComposable - get() = defaultTextStyle + @Composable @ReadOnlyComposable get() = defaultTextStyle public val defaultTextStyle: TextStyle - @Composable - @ReadOnlyComposable - get() = LocalTextStyle.current + @Composable @ReadOnlyComposable get() = LocalTextStyle.current public val editorTextStyle: TextStyle - @Composable - @ReadOnlyComposable - get() = LocalEditorTextStyle.current + @Composable @ReadOnlyComposable get() = LocalEditorTextStyle.current public val consoleTextStyle: TextStyle - @Composable - @ReadOnlyComposable - get() = LocalConsoleTextStyle.current + @Composable @ReadOnlyComposable get() = LocalConsoleTextStyle.current public val contentColor: Color - @Composable - @ReadOnlyComposable - get() = LocalContentColor.current + @Composable @ReadOnlyComposable get() = LocalContentColor.current public val isDark: Boolean - @Composable - @ReadOnlyComposable - get() = LocalIsDarkTheme.current + @Composable @ReadOnlyComposable get() = LocalIsDarkTheme.current public val isSwingCompatMode: Boolean - @Composable - @ReadOnlyComposable - get() = LocalSwingCompatMode.current + @Composable @ReadOnlyComposable get() = LocalSwingCompatMode.current } } @Composable -public fun JewelTheme( - theme: ThemeDefinition, - swingCompatMode: Boolean, - content: @Composable () -> Unit, -) { - CompositionLocalProvider(LocalSwingCompatMode provides swingCompatMode) { - JewelTheme(theme, content) - } +public fun JewelTheme(theme: ThemeDefinition, swingCompatMode: Boolean, content: @Composable () -> Unit) { + CompositionLocalProvider(LocalSwingCompatMode provides swingCompatMode) { JewelTheme(theme, content) } } @Composable -public fun JewelTheme( - theme: ThemeDefinition, - content: @Composable () -> Unit, -) { +public fun JewelTheme(theme: ThemeDefinition, content: @Composable () -> Unit) { CompositionLocalProvider( LocalThemeName provides theme.name, LocalIsDarkTheme provides theme.isDark, @@ -96,58 +67,46 @@ public fun JewelTheme( ) } -public val LocalThemeName: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No ThemeName provided") - } +public val LocalThemeName: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No ThemeName provided") +} -public val LocalContentColor: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No ContentColor provided. Have you forgotten the theme?") - } +public val LocalContentColor: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No ContentColor provided. Have you forgotten the theme?") +} -internal val LocalIsDarkTheme: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No IsDarkTheme provided. Have you forgotten the theme?") - } +internal val LocalIsDarkTheme: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No IsDarkTheme provided. Have you forgotten the theme?") +} -internal val LocalSwingCompatMode: ProvidableCompositionLocal = - staticCompositionLocalOf { - // By default, Swing compat is not enabled - false - } +internal val LocalSwingCompatMode: ProvidableCompositionLocal = staticCompositionLocalOf { + // By default, Swing compat is not enabled + false +} -public val LocalColorPalette: ProvidableCompositionLocal = - staticCompositionLocalOf { - ThemeColorPalette.Empty - } +public val LocalColorPalette: ProvidableCompositionLocal = staticCompositionLocalOf { + ThemeColorPalette.Empty +} -public val LocalIconData: ProvidableCompositionLocal = - staticCompositionLocalOf { - ThemeIconData.Empty - } +public val LocalIconData: ProvidableCompositionLocal = staticCompositionLocalOf { ThemeIconData.Empty } -public val LocalTextStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No TextStyle provided. Have you forgotten the theme?") - } +public val LocalTextStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No TextStyle provided. Have you forgotten the theme?") +} -public val LocalEditorTextStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No EditorTextStyle provided. Have you forgotten the theme?") - } +public val LocalEditorTextStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No EditorTextStyle provided. Have you forgotten the theme?") +} -public val LocalConsoleTextStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No ConsoleTextStyle provided. Have you forgotten the theme?") - } +public val LocalConsoleTextStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No ConsoleTextStyle provided. Have you forgotten the theme?") +} /** - * Overrides the [isDark] value for the [content]. It is used to inject a - * different dark mode style in a sub-tree. + * Overrides the [isDark] value for the [content]. It is used to inject a different dark mode style in a sub-tree. * - * Note: this does _not_ change the theme. If you want to change the theme, - * you need to do it by yourself. For example, in standalone: + * Note: this does _not_ change the theme. If you want to change the theme, you need to do it by yourself. For example, + * in standalone: * ```kotlin * IntUiTheme(isDark = false) { * Text("I am light") @@ -159,9 +118,6 @@ public val LocalConsoleTextStyle: ProvidableCompositionLocal = * ``` */ @Composable -public fun OverrideDarkMode( - isDark: Boolean, - content: @Composable () -> Unit, -) { +public fun OverrideDarkMode(isDark: Boolean, content: @Composable () -> Unit) { CompositionLocalProvider(LocalIsDarkTheme provides isDark, content = content) } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeColorPalette.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeColorPalette.kt index fa923e056..0c632a749 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeColorPalette.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeColorPalette.kt @@ -21,8 +21,7 @@ public class ThemeColorPalette( public val teal: List, public val rawMap: Map, ) { - @Deprecated("Use gray() instead", ReplaceWith("gray(index)")) - public fun grey(index: Int): Color = gray(index) + @Deprecated("Use gray() instead", ReplaceWith("gray(index)")) public fun grey(index: Int): Color = gray(index) @Deprecated("Use grayOrNull() instead", ReplaceWith("grayOrNull(index)")) public fun greyOrNull(index: Int): Color? = grayOrNull(index) @@ -69,7 +68,8 @@ public class ThemeColorPalette( } return when (colorGroup) { - "grey", "gray" -> gray(colorIndex) + "grey", + "gray" -> gray(colorIndex) "blue" -> blue(colorIndex) "green" -> green(colorIndex) "red" -> red(colorIndex) diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeIconData.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeIconData.kt index 1f7bc81e3..f6532bb90 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeIconData.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/theme/ThemeIconData.kt @@ -20,11 +20,7 @@ public class ThemeIconData( public companion object { public val Empty: ThemeIconData = - ThemeIconData( - iconOverrides = emptyMap(), - colorPalette = emptyMap(), - selectionColorPalette = emptyMap(), - ) + ThemeIconData(iconOverrides = emptyMap(), colorPalette = emptyMap(), selectionColorPalette = emptyMap()) } } diff --git a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/util/JewelLogger.kt b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/util/JewelLogger.kt index 01fb8b44f..c5af9398b 100644 --- a/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/util/JewelLogger.kt +++ b/foundation/src/main/kotlin/org/jetbrains/jewel/foundation/util/JewelLogger.kt @@ -1,16 +1,14 @@ package org.jetbrains.jewel.foundation.util -import org.jetbrains.annotations.ApiStatus import java.lang.reflect.Method import java.util.logging.ConsoleHandler import java.util.logging.Level import java.util.logging.Logger +import org.jetbrains.annotations.ApiStatus public inline fun T.myLogger(): JewelLogger = JewelLogger.getInstance(T::class.java) -/** - * A wrapper which uses either IDE logging subsystem (if available) or java.util.logging. - */ +/** A wrapper which uses either IDE logging subsystem (if available) or java.util.logging. */ @ApiStatus.NonExtendable @Suppress("OptionalUnit") public abstract class JewelLogger { @@ -38,30 +36,15 @@ public abstract class JewelLogger { public fun error(t: Throwable): Unit = error(t.message, t) - public abstract fun trace( - message: String?, - t: Throwable?, - ) + public abstract fun trace(message: String?, t: Throwable?) - public abstract fun debug( - message: String?, - t: Throwable?, - ) + public abstract fun debug(message: String?, t: Throwable?) - public abstract fun info( - message: String?, - t: Throwable?, - ) + public abstract fun info(message: String?, t: Throwable?) - public abstract fun warn( - message: String?, - t: Throwable?, - ) + public abstract fun warn(message: String?, t: Throwable?) - public abstract fun error( - message: String?, - t: Throwable?, - ) + public abstract fun error(message: String?, t: Throwable?) private class JavaFactory : Factory { override fun getInstance(category: String?): JewelLogger { @@ -84,38 +67,23 @@ public abstract class JewelLogger { l } return object : JewelLogger() { - override fun trace( - message: String?, - t: Throwable?, - ) { + override fun trace(message: String?, t: Throwable?) { logger.log(Level.FINER, message, t) } - override fun debug( - message: String?, - t: Throwable?, - ) { + override fun debug(message: String?, t: Throwable?) { logger.log(Level.FINE, message, t) } - override fun info( - message: String?, - t: Throwable?, - ) { + override fun info(message: String?, t: Throwable?) { logger.log(Level.INFO, message, t) } - override fun warn( - message: String?, - t: Throwable?, - ) { + override fun warn(message: String?, t: Throwable?) { logger.log(Level.WARNING, message, t) } - override fun error( - message: String?, - t: Throwable?, - ) { + override fun error(message: String?, t: Throwable?) { logger.log(Level.SEVERE, message, t) } } @@ -130,54 +98,34 @@ public abstract class JewelLogger { val logger = getLogger(category) return object : JewelLogger() { - override fun trace( - message: String?, - t: Throwable?, - ) { + override fun trace(message: String?, t: Throwable?) { try { this@ReflectionBasedFactory.trace(message, t, logger) - } catch (ignored: Exception) { - } + } catch (ignored: Exception) {} } - override fun debug( - message: String?, - t: Throwable?, - ) { + override fun debug(message: String?, t: Throwable?) { try { this@ReflectionBasedFactory.debug(message, t, logger) - } catch (ignored: Exception) { - } + } catch (ignored: Exception) {} } - override fun info( - message: String?, - t: Throwable?, - ) { + override fun info(message: String?, t: Throwable?) { try { this@ReflectionBasedFactory.info(message, t, logger) - } catch (ignored: Exception) { - } + } catch (ignored: Exception) {} } - override fun warn( - message: String?, - t: Throwable?, - ) { + override fun warn(message: String?, t: Throwable?) { try { this@ReflectionBasedFactory.warn(message, t, logger) - } catch (ignored: Exception) { - } + } catch (ignored: Exception) {} } - override fun error( - message: String?, - t: Throwable?, - ) { + override fun error(message: String?, t: Throwable?) { try { this@ReflectionBasedFactory.error(message, t, logger) - } catch (ignored: Exception) { - } + } catch (ignored: Exception) {} } } } catch (e: Exception) { @@ -185,43 +133,17 @@ public abstract class JewelLogger { } } - @Throws(Exception::class) - protected abstract fun trace( - message: String?, - t: Throwable?, - logger: Any?, - ) + @Throws(Exception::class) protected abstract fun trace(message: String?, t: Throwable?, logger: Any?) - @Throws(Exception::class) - protected abstract fun debug( - message: String?, - t: Throwable?, - logger: Any?, - ) + @Throws(Exception::class) protected abstract fun debug(message: String?, t: Throwable?, logger: Any?) - @Throws(Exception::class) - protected abstract fun error( - message: String?, - t: Throwable?, - logger: Any?, - ) + @Throws(Exception::class) protected abstract fun error(message: String?, t: Throwable?, logger: Any?) - @Throws(Exception::class) - protected abstract fun warn( - message: String?, - t: Throwable?, - logger: Any?, - ) + @Throws(Exception::class) protected abstract fun warn(message: String?, t: Throwable?, logger: Any?) - @Throws(Exception::class) - protected abstract fun info( - message: String?, - t: Throwable?, - logger: Any?, - ) + @Throws(Exception::class) protected abstract fun info(message: String?, t: Throwable?, logger: Any?) - @Throws(Exception::class) - protected abstract fun getLogger(category: String?): Any + @Throws(Exception::class) protected abstract fun getLogger(category: String?): Any } private class IdeaFactory : ReflectionBasedFactory() { @@ -249,52 +171,31 @@ public abstract class JewelLogger { } @Throws(Exception::class) - override fun trace( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun trace(message: String?, t: Throwable?, logger: Any?) { ideaTrace.invoke(logger, t) } @Throws(Exception::class) - override fun debug( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun debug(message: String?, t: Throwable?, logger: Any?) { ideaDebug.invoke(logger, message, t) } @Throws(Exception::class) - override fun error( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun error(message: String?, t: Throwable?, logger: Any?) { ideaError.invoke(logger, message, t) } @Throws(Exception::class) - override fun warn( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun warn(message: String?, t: Throwable?, logger: Any?) { ideaWarn.invoke(logger, message, t) } @Throws(Exception::class) - override fun info( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun info(message: String?, t: Throwable?, logger: Any?) { ideaInfo.invoke(logger, message, t) } - @Throws(Exception::class) - override fun getLogger(category: String?): Any = myGetInstance.invoke(null, category) + @Throws(Exception::class) override fun getLogger(category: String?): Any = myGetInstance.invoke(null, category) } private class Slf4JFactory : ReflectionBasedFactory() { @@ -324,57 +225,35 @@ public abstract class JewelLogger { } @Throws(Exception::class) - override fun trace( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun trace(message: String?, t: Throwable?, logger: Any?) { myTrace.invoke(logger, message, t) } @Throws(Exception::class) - override fun debug( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun debug(message: String?, t: Throwable?, logger: Any?) { myDebug.invoke(logger, message, t) } @Throws(Exception::class) - override fun error( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun error(message: String?, t: Throwable?, logger: Any?) { myError.invoke(logger, message, t) } @Throws(Exception::class) - override fun warn( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun warn(message: String?, t: Throwable?, logger: Any?) { myWarn.invoke(logger, message, t) } @Throws(Exception::class) - override fun info( - message: String?, - t: Throwable?, - logger: Any?, - ) { + override fun info(message: String?, t: Throwable?, logger: Any?) { myInfo.invoke(logger, message, t) } - @Throws(Exception::class) - override fun getLogger(category: String?): Any = myGetLogger.invoke(null, category) + @Throws(Exception::class) override fun getLogger(category: String?): Any = myGetLogger.invoke(null, category) } public companion object { - @get:Synchronized - private val factory: Factory = createFactory() + @get:Synchronized private val factory: Factory = createFactory() @Suppress("SwallowedException", "TooGenericExceptionCaught") private fun createFactory(): Factory = diff --git a/foundation/src/test/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumnTest.kt b/foundation/src/test/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumnTest.kt index 075aff4c5..d48790a39 100644 --- a/foundation/src/test/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumnTest.kt +++ b/foundation/src/test/kotlin/org/jetbrains/jewel/foundation/lazy/SelectableLazyColumnTest.kt @@ -23,8 +23,7 @@ import org.junit.Rule import org.junit.Test internal class SelectableLazyColumnTest { - @get:Rule - val composeRule = createComposeRule() + @get:Rule val composeRule = createComposeRule() @Test fun `column with multiple items`() = @@ -35,22 +34,12 @@ internal class SelectableLazyColumnTest { composeRule.setContent { Box(modifier = Modifier.requiredHeight(100.dp)) { SelectableLazyColumn(state = scrollState) { - items( - items1.size, - key = { - items1[it] - }, - ) { + items(items1.size, key = { items1[it] }) { val itemText = "Item ${items1[it]}" BasicText(itemText, modifier = Modifier.testTag(itemText)) } - items( - items2.size, - key = { - items2[it] - }, - ) { + items(items2.size, key = { items2[it] }) { val itemText = "Item ${items2[it]}" BasicText(itemText, modifier = Modifier.testTag(itemText)) } @@ -65,244 +54,206 @@ internal class SelectableLazyColumnTest { @OptIn(ExperimentalTestApi::class) @Test - fun `selection with arrow keys`() = - runBlocking { - val items = (0..10).toList() - val state = SelectableLazyListState(LazyListState()) - composeRule.setContent { - Box(modifier = Modifier.requiredHeight(300.dp)) { - SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { - items( - items.size, - key = { - items[it] - }, - ) { - val itemText = "Item ${items[it]}" - BasicText(itemText, modifier = Modifier.testTag(itemText)) - } + fun `selection with arrow keys`() = runBlocking { + val items = (0..10).toList() + val state = SelectableLazyListState(LazyListState()) + composeRule.setContent { + Box(modifier = Modifier.requiredHeight(300.dp)) { + SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { + items(items.size, key = { items[it] }) { + val itemText = "Item ${items[it]}" + BasicText(itemText, modifier = Modifier.testTag(itemText)) } } } - composeRule.awaitIdle() - // select item 5 by click - composeRule.onNodeWithTag("Item 5").assertExists() - composeRule.onNodeWithTag("Item 5").performClick() - - // check that 5th element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(items[5], state.selectedKeys.single()) - - // press arrow up and check that selected key is changed - repeat(20) { step -> - composeRule.onNodeWithTag("list").performKeyInput { - pressKey(Key.DirectionUp) - } + } + composeRule.awaitIdle() + // select item 5 by click + composeRule.onNodeWithTag("Item 5").assertExists() + composeRule.onNodeWithTag("Item 5").performClick() - // check that previous element is selected - // when started from 5th element - assertTrue(state.selectedKeys.size == 1) - val expectedSelectedIndex = (5 - step - 1).takeIf { it >= 0 } ?: 0 - assertEquals(items[expectedSelectedIndex], state.selectedKeys.single()) - } + // check that 5th element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(items[5], state.selectedKeys.single()) - // since amount of arrow up is bigger than amount of items -> first element should be selected + // press arrow up and check that selected key is changed + repeat(20) { step -> + composeRule.onNodeWithTag("list").performKeyInput { pressKey(Key.DirectionUp) } + + // check that previous element is selected + // when started from 5th element assertTrue(state.selectedKeys.size == 1) - assertEquals(items[0], state.selectedKeys.single()) + val expectedSelectedIndex = (5 - step - 1).takeIf { it >= 0 } ?: 0 + assertEquals(items[expectedSelectedIndex], state.selectedKeys.single()) + } - // press arrow down and check that selected key is changed - repeat(40) { step -> - composeRule.onNodeWithTag("list").performKeyInput { - pressKey(Key.DirectionDown) - } + // since amount of arrow up is bigger than amount of items -> first element should be + // selected + assertTrue(state.selectedKeys.size == 1) + assertEquals(items[0], state.selectedKeys.single()) - // check that next element is selected - assertTrue(state.selectedKeys.size == 1) - val expectedSelectedIndex = (step + 1).takeIf { it in items.indices } ?: items.lastIndex - assertEquals(items[expectedSelectedIndex], state.selectedKeys.single()) - } + // press arrow down and check that selected key is changed + repeat(40) { step -> + composeRule.onNodeWithTag("list").performKeyInput { pressKey(Key.DirectionDown) } - // since amount of arrow down is bigger than amount of items -> last element should be selected + // check that next element is selected assertTrue(state.selectedKeys.size == 1) - assertEquals(items.last(), state.selectedKeys.single()) + val expectedSelectedIndex = (step + 1).takeIf { it in items.indices } ?: items.lastIndex + assertEquals(items[expectedSelectedIndex], state.selectedKeys.single()) } + // since amount of arrow down is bigger than amount of items -> last element should be + // selected + assertTrue(state.selectedKeys.size == 1) + assertEquals(items.last(), state.selectedKeys.single()) + } + @OptIn(ExperimentalTestApi::class) @Test - fun `multiple items selection`() = - runBlocking { - val items = (0..10).toList() - val state = SelectableLazyListState(LazyListState()) - composeRule.setContent { - Box(modifier = Modifier.requiredHeight(300.dp)) { - SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { - items( - items.size, - key = { - items[it] - }, - ) { - val itemText = "Item ${items[it]}" - BasicText(itemText, modifier = Modifier.testTag(itemText)) - } - } - } - } - composeRule.awaitIdle() - // select item 5 by click - composeRule.onNodeWithTag("Item 5").assertExists() - composeRule.onNodeWithTag("Item 5").performClick() - - // check that 5th element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(items[5], state.selectedKeys.single()) - - // press arrow up with pressed Shift and check that selected keys are changed - repeat(20) { step -> - composeRule.onNodeWithTag("list").performKeyInput { - withKeyDown(Key.ShiftLeft) { - pressKey(Key.DirectionUp) + fun `multiple items selection`() = runBlocking { + val items = (0..10).toList() + val state = SelectableLazyListState(LazyListState()) + composeRule.setContent { + Box(modifier = Modifier.requiredHeight(300.dp)) { + SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { + items(items.size, key = { items[it] }) { + val itemText = "Item ${items[it]}" + BasicText(itemText, modifier = Modifier.testTag(itemText)) } } - - // check that previous element is added to selection - // when started from 5th element - val expectedFirstSelectedIndex = (5 - step - 1).takeIf { it >= 0 } ?: 0 - val elements = items.subList(expectedFirstSelectedIndex, 6) - assertEquals(elements.size, state.selectedKeys.size) - assertEquals(elements.toSet(), state.selectedKeys.toSet()) } + } + composeRule.awaitIdle() + // select item 5 by click + composeRule.onNodeWithTag("Item 5").assertExists() + composeRule.onNodeWithTag("Item 5").performClick() - // select first item by click - composeRule.onNodeWithTag("Item 0").assertExists() - composeRule.onNodeWithTag("Item 0").performClick() - - // check that first element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(items[0], state.selectedKeys.single()) - - // press arrow down with pressed Shift and check that selected keys are changed - repeat(20) { step -> - composeRule.onNodeWithTag("list").performKeyInput { - withKeyDown(Key.ShiftLeft) { - pressKey(Key.DirectionDown) - } - } + // check that 5th element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(items[5], state.selectedKeys.single()) - // check that next element is added to selection - val expectedFirstSelectedIndex = (step + 1).takeIf { it in items.indices } ?: items.lastIndex - val elements = items.subList(0, expectedFirstSelectedIndex + 1) - assertEquals(elements.size, state.selectedKeys.size) - assertEquals(elements.toSet(), state.selectedKeys.toSet()) + // press arrow up with pressed Shift and check that selected keys are changed + repeat(20) { step -> + composeRule.onNodeWithTag("list").performKeyInput { + withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionUp) } } - // all elements should be selected in the end - assertEquals(items.size, state.selectedKeys.size) - assertEquals(items.toSet(), state.selectedKeys.toSet()) + // check that previous element is added to selection + // when started from 5th element + val expectedFirstSelectedIndex = (5 - step - 1).takeIf { it >= 0 } ?: 0 + val elements = items.subList(expectedFirstSelectedIndex, 6) + assertEquals(elements.size, state.selectedKeys.size) + assertEquals(elements.toSet(), state.selectedKeys.toSet()) } - @OptIn(ExperimentalTestApi::class) - @Test - fun `select to first and last`() = - runBlocking { - val items = (0..50).toList() - val state = SelectableLazyListState(LazyListState()) - composeRule.setContent { - Box(modifier = Modifier.requiredHeight(300.dp)) { - SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { - items( - items.size, - key = { - items[it] - }, - ) { - val itemText = "Item ${items[it]}" - BasicText(itemText, modifier = Modifier.testTag(itemText)) - } - } - } - } - composeRule.awaitIdle() - // select item 5 by click - composeRule.onNodeWithTag("Item 5").assertExists() - composeRule.onNodeWithTag("Item 5").performClick() + // select first item by click + composeRule.onNodeWithTag("Item 0").assertExists() + composeRule.onNodeWithTag("Item 0").performClick() - // check that 5th element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(items[5], state.selectedKeys.single()) + // check that first element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(items[0], state.selectedKeys.single()) - // perform home with shift, so all items until 5th should be selected + // press arrow down with pressed Shift and check that selected keys are changed + repeat(20) { step -> composeRule.onNodeWithTag("list").performKeyInput { - withKeyDown(Key.ShiftLeft) { - pressKey(Key.MoveHome) - } + withKeyDown(Key.ShiftLeft) { pressKey(Key.DirectionDown) } } - val expectedElementsAfterPageUp = items.subList(0, 6) - assertEquals(expectedElementsAfterPageUp.size, state.selectedKeys.size) - assertEquals(expectedElementsAfterPageUp.toSet(), state.selectedKeys.toSet()) - // select item 5 by click - composeRule.onNodeWithTag("Item 5").assertExists() - composeRule.onNodeWithTag("Item 5").performClick() + // check that next element is added to selection + val expectedFirstSelectedIndex = (step + 1).takeIf { it in items.indices } ?: items.lastIndex + val elements = items.subList(0, expectedFirstSelectedIndex + 1) + assertEquals(elements.size, state.selectedKeys.size) + assertEquals(elements.toSet(), state.selectedKeys.toSet()) + } - // check that 5th element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(items[5], state.selectedKeys.single()) + // all elements should be selected in the end + assertEquals(items.size, state.selectedKeys.size) + assertEquals(items.toSet(), state.selectedKeys.toSet()) + } - // perform end with shift, so all items after 5th should be selected - composeRule.onNodeWithTag("list").performKeyInput { - withKeyDown(Key.ShiftLeft) { - pressKey(Key.MoveEnd) + @OptIn(ExperimentalTestApi::class) + @Test + fun `select to first and last`() = runBlocking { + val items = (0..50).toList() + val state = SelectableLazyListState(LazyListState()) + composeRule.setContent { + Box(modifier = Modifier.requiredHeight(300.dp)) { + SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { + items(items.size, key = { items[it] }) { + val itemText = "Item ${items[it]}" + BasicText(itemText, modifier = Modifier.testTag(itemText)) + } } } - val expectedElementsAfterPageDown = items.subList(5, items.lastIndex + 1) - assertEquals(expectedElementsAfterPageDown.size, state.selectedKeys.size) - assertEquals(expectedElementsAfterPageDown.toSet(), state.selectedKeys.toSet()) } + composeRule.awaitIdle() + // select item 5 by click + composeRule.onNodeWithTag("Item 5").assertExists() + composeRule.onNodeWithTag("Item 5").performClick() + + // check that 5th element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(items[5], state.selectedKeys.single()) + + // perform home with shift, so all items until 5th should be selected + composeRule.onNodeWithTag("list").performKeyInput { withKeyDown(Key.ShiftLeft) { pressKey(Key.MoveHome) } } + val expectedElementsAfterPageUp = items.subList(0, 6) + assertEquals(expectedElementsAfterPageUp.size, state.selectedKeys.size) + assertEquals(expectedElementsAfterPageUp.toSet(), state.selectedKeys.toSet()) + + // select item 5 by click + composeRule.onNodeWithTag("Item 5").assertExists() + composeRule.onNodeWithTag("Item 5").performClick() + + // check that 5th element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(items[5], state.selectedKeys.single()) + + // perform end with shift, so all items after 5th should be selected + composeRule.onNodeWithTag("list").performKeyInput { withKeyDown(Key.ShiftLeft) { pressKey(Key.MoveEnd) } } + val expectedElementsAfterPageDown = items.subList(5, items.lastIndex + 1) + assertEquals(expectedElementsAfterPageDown.size, state.selectedKeys.size) + assertEquals(expectedElementsAfterPageDown.toSet(), state.selectedKeys.toSet()) + } @Test - fun `changing items model with selection shouldn't fail`() = - runBlocking { - val items1 = (0..50).toList() - val items2 = (70..80).toList() - val currentItems = mutableStateOf(items1) - val state = SelectableLazyListState(LazyListState()) - composeRule.setContent { - Box(modifier = Modifier.requiredHeight(300.dp)) { - val items = currentItems.value - SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { - items( - items.size, - key = { - items[it] - }, - ) { - val itemText = "Item ${items[it]}" - BasicText(itemText, modifier = Modifier.testTag(itemText)) - } + fun `changing items model with selection shouldn't fail`() = runBlocking { + val items1 = (0..50).toList() + val items2 = (70..80).toList() + val currentItems = mutableStateOf(items1) + val state = SelectableLazyListState(LazyListState()) + composeRule.setContent { + Box(modifier = Modifier.requiredHeight(300.dp)) { + val items = currentItems.value + SelectableLazyColumn(state = state, modifier = Modifier.testTag("list")) { + items(items.size, key = { items[it] }) { + val itemText = "Item ${items[it]}" + BasicText(itemText, modifier = Modifier.testTag(itemText)) } } } - composeRule.awaitIdle() - // select item 5 by click - composeRule.onNodeWithTag("Item 5").assertExists() - composeRule.onNodeWithTag("Item 5").performClick() - - // check that 5th element is selected - assertEquals(1, state.selectedKeys.size) - assertEquals(currentItems.value[5], state.selectedKeys.single()) - - // change items from 0..50 to 70..80, so "Item 5" doesn't exist - currentItems.value = items2 - composeRule.awaitIdle() - // TODO: should the selectedKeys be cleared when items are changed - // https://github.com/JetBrains/jewel/issues/242 - // assertEquals(0, state.selectedKeys.size) - - composeRule.onNodeWithTag("Item 75").assertExists() - composeRule.onNodeWithTag("Item 75").performClick() - - assertEquals(1, state.selectedKeys.size) - assertEquals(currentItems.value[5], state.selectedKeys.single()) } + composeRule.awaitIdle() + // select item 5 by click + composeRule.onNodeWithTag("Item 5").assertExists() + composeRule.onNodeWithTag("Item 5").performClick() + + // check that 5th element is selected + assertEquals(1, state.selectedKeys.size) + assertEquals(currentItems.value[5], state.selectedKeys.single()) + + // change items from 0..50 to 70..80, so "Item 5" doesn't exist + currentItems.value = items2 + composeRule.awaitIdle() + // TODO: should the selectedKeys be cleared when items are changed + // https://github.com/JetBrains/jewel/issues/242 + // assertEquals(0, state.selectedKeys.size) + + composeRule.onNodeWithTag("Item 75").assertExists() + composeRule.onNodeWithTag("Item 75").performClick() + + assertEquals(1, state.selectedKeys.size) + assertEquals(currentItems.value[5], state.selectedKeys.single()) + } } diff --git a/ide-laf-bridge/build.gradle.kts b/ide-laf-bridge/build.gradle.kts index d2fc3ab3c..21d013d43 100644 --- a/ide-laf-bridge/build.gradle.kts +++ b/ide-laf-bridge/build.gradle.kts @@ -7,14 +7,10 @@ plugins { } dependencies { - api(projects.ui) { - exclude(group = "org.jetbrains.kotlinx") - } + api(projects.ui) { exclude(group = "org.jetbrains.kotlinx") } compileOnly(libs.bundles.idea) testImplementation(compose.desktop.uiTestJUnit4) - testImplementation(compose.desktop.currentOs) { - exclude(group = "org.jetbrains.compose.material") - } -} + testImplementation(compose.desktop.currentOs) { exclude(group = "org.jetbrains.compose.material") } +} \ No newline at end of file diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Bridge.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Bridge.kt index 1ecf36e87..a2e8f5332 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Bridge.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Bridge.kt @@ -24,17 +24,14 @@ private fun Application.lookAndFeelFlow(scope: CoroutineScope): Flow = internal fun Application.lookAndFeelChangedFlow( scope: CoroutineScope, sharingStarted: SharingStarted = SharingStarted.Eagerly, -): Flow = - lookAndFeelFlow(scope).onStart { emit(Unit) } - .shareIn(scope, sharingStarted, replay = 1) +): Flow = lookAndFeelFlow(scope).onStart { emit(Unit) }.shareIn(scope, sharingStarted, replay = 1) internal fun MessageBus.flow( topic: Topic, parentScope: CoroutineScope, listener: ProducerScope.() -> L, -): Flow = - callbackFlow { - val connection: SimpleMessageBusConnection = connect(parentScope) - connection.subscribe(topic, listener()) - awaitClose { connection.disconnect() } - } +): Flow = callbackFlow { + val connection: SimpleMessageBusConnection = connect(parentScope) + connection.subscribe(topic, listener()) + awaitClose { connection.disconnect() } +} diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeOverride.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeOverride.kt index 02bd7d959..c066de352 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeOverride.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeOverride.kt @@ -9,8 +9,8 @@ import org.jetbrains.jewel.ui.painter.ResourcePainterProviderScope /** * A [PainterPathHint] that implements the - * [New UI Icon Mapping](https://plugins.jetbrains.com/docs/intellij/icons.html#mapping-entries) - * by delegating to the IntelliJ Platform. + * [New UI Icon Mapping](https://plugins.jetbrains.com/docs/intellij/icons.html#mapping-entries) by delegating to the + * IntelliJ Platform. */ internal object BridgeOverride : PainterPathHint { private val dirProvider = DirProvider() @@ -51,7 +51,8 @@ internal object BridgeOverride : PainterPathHint { return buildString { append("expui/") - iconPath.split('.') + iconPath + .split('.') .map { it.trim() } .filter { it.isNotEmpty() } .forEach { @@ -66,7 +67,7 @@ internal object BridgeOverride : PainterPathHint { Logger.getInstance("IconsPathPatching") .warn( "IntelliJ returned a reflective path: $patchedPath for $iconPath." + - " We reverted that to a plausible-looking resource path: ${toString()}", + " We reverted that to a plausible-looking resource path: ${toString()}" ) } } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgePainterHintsProvider.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgePainterHintsProvider.kt index a18ff1fa8..ad8f76625 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgePainterHintsProvider.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgePainterHintsProvider.kt @@ -19,7 +19,8 @@ import org.jetbrains.jewel.ui.util.toRgbaHexString * This is an internal Jewel API and should not be used directly. */ @InternalJewelApi -public class BridgePainterHintsProvider private constructor( +public class BridgePainterHintsProvider +private constructor( isDark: Boolean, intellijIconPalette: Map = emptyMap(), themeIconPalette: Map = emptyMap(), @@ -47,11 +48,7 @@ public class BridgePainterHintsProvider private constructor( uiPaletteHint = ColorBasedPaletteReplacement(ui) } - private fun registerColorBasedReplacement( - map: MutableMap, - key: String, - value: String, - ) { + private fun registerColorBasedReplacement(map: MutableMap, key: String, value: String) { // If either the key or the resolved value aren't valid colors, ignore the entry val keyAsColor = resolveKeyColor(key, intellijIconPalette, isDark) ?: return val resolvedColor = resolveColor(value) ?: return @@ -61,13 +58,12 @@ public class BridgePainterHintsProvider private constructor( } @Composable - override fun hints(path: String): List = - buildList { - add(BridgeOverride) - add(getPaletteHint(path)) - add(HiDpi()) - add(Dark(JewelTheme.isDark)) - } + override fun hints(path: String): List = buildList { + add(BridgeOverride) + add(getPaletteHint(path)) + add(HiDpi()) + add(Dark(JewelTheme.isDark)) + } public companion object { private val logger = thisLogger() diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeResourceResolver.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeResourceResolver.kt index d960f6d4e..6f32344d0 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeResourceResolver.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeResourceResolver.kt @@ -4,17 +4,11 @@ import com.intellij.util.ui.DirProvider import org.jetbrains.jewel.ui.icon.IconKey import org.jetbrains.jewel.ui.painter.ResourcePainterProvider -/** - * [ResourcePainterProvider] to resolve resources in Intellij Module and - * Bridge module. - */ +/** [ResourcePainterProvider] to resolve resources in Intellij Module and Bridge module. */ public fun bridgePainterProvider(path: String): ResourcePainterProvider = ResourcePainterProvider(path, DirProvider::class.java.classLoader, SwingBridgeService::class.java.classLoader) -/** - * [ResourcePainterProvider] to resolve resources in Intellij Module and - * Bridge module. - */ +/** [ResourcePainterProvider] to resolve resources in Intellij Module and Bridge module. */ public fun bridgePainterProvider(iconKey: IconKey): ResourcePainterProvider { val isNewUi = isNewUiTheme() return ResourcePainterProvider( diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeUtils.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeUtils.kt index 26dab1ce7..937aa9bfb 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeUtils.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/BridgeUtils.kt @@ -44,17 +44,10 @@ public fun java.awt.Color.toComposeColor(): Color = Color(red = red, green = gre public fun java.awt.Color?.toComposeColorOrUnspecified(): Color = this?.toComposeColor() ?: Color.Unspecified -public fun retrieveColor( - key: String, - default: Color, -): Color = retrieveColorOrNull(key) ?: default +public fun retrieveColor(key: String, default: Color): Color = retrieveColorOrNull(key) ?: default -public fun retrieveColor( - key: String, - isDark: Boolean, - default: Color, - defaultDark: Color, -): Color = retrieveColorOrNull(key) ?: if (isDark) defaultDark else default +public fun retrieveColor(key: String, isDark: Boolean, default: Color, defaultDark: Color): Color = + retrieveColorOrNull(key) ?: if (isDark) defaultDark else default public fun retrieveColorOrNull(key: String): Color? = try { @@ -90,10 +83,7 @@ public fun List.createVerticalBrush( return Brush.verticalGradient(this, startY, endY, tileMode) } -public fun retrieveIntAsDp( - key: String, - default: Dp? = null, -): Dp { +public fun retrieveIntAsDp(key: String, default: Dp? = null): Dp { val rawValue = UIManager.get(key) if (rawValue is Int) return rawValue.dp if (default != null) return default @@ -108,10 +98,8 @@ public fun retrieveIntAsDpOrUnspecified(key: String): Dp = Dp.Unspecified } -public fun retrieveInsetsAsPaddingValues( - key: String, - default: PaddingValues? = null, -): PaddingValues = UIManager.getInsets(key)?.toPaddingValues() ?: default ?: keyNotFound(key, "Insets") +public fun retrieveInsetsAsPaddingValues(key: String, default: PaddingValues? = null): PaddingValues = + UIManager.getInsets(key)?.toPaddingValues() ?: default ?: keyNotFound(key, "Insets") /** * Converts a [Insets] to [PaddingValues]. If the receiver is a [JBInsets] instance, this function delegates to the @@ -149,10 +137,7 @@ public fun JBDimension.toDpSize(): DpSize { public fun retrieveArcAsCornerSize(key: String): CornerSize = CornerSize(retrieveIntAsDp(key) / 2) -public fun retrieveArcAsCornerSizeOrDefault( - key: String, - default: CornerSize, -): CornerSize { +public fun retrieveArcAsCornerSizeOrDefault(key: String, default: CornerSize): CornerSize { val intValue = retrieveIntAsDpOrUnspecified(key) if (intValue.isUnspecified) return default return CornerSize(intValue / 2) @@ -172,10 +157,7 @@ public fun retrieveArcAsCornerSizeWithFallbacks(vararg keys: String): CornerSize keysNotFound(keys.toList(), "Int") } -public fun retrieveTextStyle( - fontKey: String, - colorKey: String? = null, -): TextStyle { +public fun retrieveTextStyle(fontKey: String, colorKey: String? = null): TextStyle { val baseColor = colorKey?.let { retrieveColorOrUnspecified(colorKey) } ?: Color.Unspecified return retrieveTextStyle(fontKey, color = baseColor) } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelBridgeException.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelBridgeException.kt index 96cf6e42d..93893436d 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelBridgeException.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelBridgeException.kt @@ -7,7 +7,7 @@ public sealed class JewelBridgeException(override val message: String?) : Runtim public class KeysNotFoundException(keys: List, type: String) : JewelBridgeException( "Keys ${keys.joinToString(", ") { "'$it'" }} not found in Swing LaF, " + - "was expecting a value of type $type", + "was expecting a value of type $type" ) } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelComposePanel.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelComposePanel.kt index 378f1dee0..d4a25d755 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelComposePanel.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/JewelComposePanel.kt @@ -11,31 +11,29 @@ import androidx.compose.ui.awt.ComposePanel import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.unit.toSize -import org.jetbrains.jewel.bridge.theme.SwingBridgeTheme -import org.jetbrains.jewel.foundation.ExperimentalJewelApi -import org.jetbrains.jewel.foundation.InternalJewelApi import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel +import org.jetbrains.jewel.bridge.theme.SwingBridgeTheme +import org.jetbrains.jewel.foundation.ExperimentalJewelApi +import org.jetbrains.jewel.foundation.InternalJewelApi @Suppress("ktlint:standard:function-naming", "FunctionName") // Swing to Compose bridge API -public fun JewelComposePanel(content: @Composable () -> Unit): JComponent = - createJewelComposePanel { - setContent { - SwingBridgeTheme { CompositionLocalProvider(LocalComponent provides this@createJewelComposePanel, content) } - } +public fun JewelComposePanel(content: @Composable () -> Unit): JComponent = createJewelComposePanel { + setContent { + SwingBridgeTheme { CompositionLocalProvider(LocalComponent provides this@createJewelComposePanel, content) } } +} @InternalJewelApi @Suppress("ktlint:standard:function-naming", "FunctionName") // Swing to Compose bridge API -public fun JewelToolWindowComposePanel(content: @Composable () -> Unit): JComponent = - createJewelComposePanel { - setContent { - Compose17IJSizeBugWorkaround { - SwingBridgeTheme { CompositionLocalProvider(LocalComponent provides this@createJewelComposePanel, content) } - } +public fun JewelToolWindowComposePanel(content: @Composable () -> Unit): JComponent = createJewelComposePanel { + setContent { + Compose17IJSizeBugWorkaround { + SwingBridgeTheme { CompositionLocalProvider(LocalComponent provides this@createJewelComposePanel, content) } } } +} private fun createJewelComposePanel(config: ComposePanel.(JPanel) -> Unit): JPanel { val jewelPanel = JPanel() @@ -47,10 +45,9 @@ private fun createJewelComposePanel(config: ComposePanel.(JPanel) -> Unit): JPan } @ExperimentalJewelApi -public val LocalComponent: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("CompositionLocal LocalComponent not provided") - } +public val LocalComponent: ProvidableCompositionLocal = staticCompositionLocalOf { + error("CompositionLocal LocalComponent not provided") +} /** * Workaround until the issue with Compose 1.7 + fillMax__ + IntelliJ Panels is fixed: diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/ScrollbarHelper.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/ScrollbarHelper.kt index faaa5b181..30e143668 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/ScrollbarHelper.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/ScrollbarHelper.kt @@ -11,8 +11,7 @@ internal interface ScrollbarHelper { val trackClickBehaviorFlow: StateFlow companion object { - @JvmStatic - fun getInstance(): ScrollbarHelper = DummyScrollbarHelper + @JvmStatic fun getInstance(): ScrollbarHelper = DummyScrollbarHelper } } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/SwingBridgeService.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/SwingBridgeService.kt index 53e99aacc..b46775578 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/SwingBridgeService.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/SwingBridgeService.kt @@ -5,6 +5,7 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.sp import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service.Level +import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.SharingStarted @@ -15,7 +16,6 @@ import org.jetbrains.jewel.bridge.theme.createBridgeComponentStyling import org.jetbrains.jewel.bridge.theme.createBridgeThemeDefinition import org.jetbrains.jewel.foundation.theme.ThemeDefinition import org.jetbrains.jewel.ui.ComponentStyling -import kotlin.time.Duration.Companion.milliseconds @Service(Level.APP) internal class SwingBridgeService(scope: CoroutineScope) { @@ -23,12 +23,12 @@ internal class SwingBridgeService(scope: CoroutineScope) { internal val currentBridgeThemeData: StateFlow = combine( - IntelliJApplication.lookAndFeelChangedFlow(scope), - scrollbarHelper.scrollbarVisibilityStyleFlow, - scrollbarHelper.trackClickBehaviorFlow, - ) { _, _, _ -> - tryGettingThemeData() - } + IntelliJApplication.lookAndFeelChangedFlow(scope), + scrollbarHelper.scrollbarVisibilityStyleFlow, + scrollbarHelper.trackClickBehaviorFlow, + ) { _, _, _ -> + tryGettingThemeData() + } .stateIn(scope, SharingStarted.Eagerly, BridgeThemeData.DEFAULT) private suspend fun tryGettingThemeData(): BridgeThemeData { @@ -46,24 +46,29 @@ internal class SwingBridgeService(scope: CoroutineScope) { private fun readThemeData(): BridgeThemeData { val themeDefinition = createBridgeThemeDefinition() - return BridgeThemeData(themeDefinition = createBridgeThemeDefinition(), componentStyling = createBridgeComponentStyling(themeDefinition)) + return BridgeThemeData( + themeDefinition = createBridgeThemeDefinition(), + componentStyling = createBridgeComponentStyling(themeDefinition), + ) } internal data class BridgeThemeData(val themeDefinition: ThemeDefinition, val componentStyling: ComponentStyling) { companion object { - val DEFAULT = - run { - val textStyle = TextStyle.Default.copy(fontSize = 13.sp) - val monospaceTextStyle = textStyle.copy(fontFamily = FontFamily.Monospace) - val themeDefinition = - createBridgeThemeDefinition( - textStyle = textStyle, - editorTextStyle = monospaceTextStyle, - consoleTextStyle = monospaceTextStyle, - ) + val DEFAULT = run { + val textStyle = TextStyle.Default.copy(fontSize = 13.sp) + val monospaceTextStyle = textStyle.copy(fontFamily = FontFamily.Monospace) + val themeDefinition = + createBridgeThemeDefinition( + textStyle = textStyle, + editorTextStyle = monospaceTextStyle, + consoleTextStyle = monospaceTextStyle, + ) - BridgeThemeData(themeDefinition = themeDefinition, componentStyling = createBridgeComponentStyling(themeDefinition)) - } + BridgeThemeData( + themeDefinition = themeDefinition, + componentStyling = createBridgeComponentStyling(themeDefinition), + ) + } } } } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Typography.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Typography.kt index 5e81abc92..a1565742e 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Typography.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/Typography.kt @@ -10,22 +10,19 @@ import org.jetbrains.jewel.ui.component.Typography import org.jetbrains.jewel.ui.component.minus /** - * The text style to use for regular text. Identical to - * [JewelTheme.defaultTextStyle]. + * The text style to use for regular text. Identical to [JewelTheme.defaultTextStyle]. * * Only available when running in the IntelliJ Platform. */ -@Composable -public fun Typography.regular(): TextStyle = labelTextStyle() +@Composable public fun Typography.regular(): TextStyle = labelTextStyle() /** * The text style to use for medium text. Smaller than [regular]. * * Only available when running in the IntelliJ Platform. * - * **Note:** when using the Classic UI on Windows, this returns the same - * value as [regular] (the default TextStyle from the theme). This is the - * same behavior implemented by [com.intellij.util.ui.JBFont]. + * **Note:** when using the Classic UI on Windows, this returns the same value as [regular] (the default TextStyle from + * the theme). This is the same behavior implemented by [com.intellij.util.ui.JBFont]. */ @Composable public fun Typography.medium(): TextStyle = @@ -36,15 +33,13 @@ public fun Typography.medium(): TextStyle = } /** - * The text style to use for small text. Smaller than [medium]. Should be - * avoided when running in the New UI, in favor of [medium], unless it's - * absolutely necessary. + * The text style to use for small text. Smaller than [medium]. Should be avoided when running in the New UI, in favor + * of [medium], unless it's absolutely necessary. * * Only available when running in the IntelliJ Platform. * - * **Note:** when using the Classic UI on Windows, this returns the same - * value as [regular] (the default TextStyle from the theme). This is the - * same behavior implemented by [com.intellij.util.ui.JBFont]. + * **Note:** when using the Classic UI on Windows, this returns the same value as [regular] (the default TextStyle from + * the theme). This is the same behavior implemented by [com.intellij.util.ui.JBFont]. */ @Composable public fun Typography.small(): TextStyle = diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/UiThemeExtensions.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/UiThemeExtensions.kt index 4084f36e4..81a6cd6da 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/UiThemeExtensions.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/UiThemeExtensions.kt @@ -4,4 +4,5 @@ import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.laf.UIThemeLookAndFeelInfo @Suppress("UnstableApiUsage") -internal fun currentUiThemeOrNull(): UIThemeLookAndFeelInfo? = LafManager.getInstance().currentUIThemeLookAndFeel?.takeIf { it.isInitialized } +internal fun currentUiThemeOrNull(): UIThemeLookAndFeelInfo? = + LafManager.getInstance().currentUIThemeLookAndFeel?.takeIf { it.isInitialized } diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeSliderStyling.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeSliderStyling.kt index 748a23a4a..24e9648b9 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeSliderStyling.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeSliderStyling.kt @@ -86,4 +86,5 @@ public fun SliderMetrics.Companion.defaults( stepLineHeight: Dp = 8.dp, stepLineWidth: Dp = 1.dp, trackToStepSpacing: Dp = thumbSize.height / 2 + 4.dp, -): SliderMetrics = SliderMetrics(trackHeight, thumbSize, thumbBorderWidth, stepLineHeight, stepLineWidth, trackToStepSpacing) +): SliderMetrics = + SliderMetrics(trackHeight, thumbSize, thumbBorderWidth, stepLineHeight, stepLineWidth, trackToStepSpacing) diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeThemeColorPalette.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeThemeColorPalette.kt index 0f66cfd73..6cfc4e8a0 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeThemeColorPalette.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/BridgeThemeColorPalette.kt @@ -3,9 +3,9 @@ package org.jetbrains.jewel.bridge.theme import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.isSpecified import com.intellij.openapi.diagnostic.Logger +import java.util.TreeMap import org.jetbrains.jewel.bridge.toComposeColor import org.jetbrains.jewel.foundation.theme.ThemeColorPalette -import java.util.TreeMap private val logger = Logger.getInstance("BridgeThemeColorPalette") @@ -23,18 +23,17 @@ public fun ThemeColorPalette.Companion.readFromLaF(): ThemeColorPalette { val teal = readPaletteColors("Teal") val windowsPopupBorder = readPaletteColor("windowsPopupBorder") - val rawMap = - buildMap { - putAll(gray) - putAll(blue) - putAll(green) - putAll(red) - putAll(yellow) - putAll(orange) - putAll(purple) - putAll(teal) - if (windowsPopupBorder.isSpecified) put("windowsPopupBorder", windowsPopupBorder) - } + val rawMap = buildMap { + putAll(gray) + putAll(blue) + putAll(green) + putAll(red) + putAll(yellow) + putAll(orange) + putAll(purple) + putAll(teal) + if (windowsPopupBorder.isSpecified) put("windowsPopupBorder", windowsPopupBorder) + } return ThemeColorPalette( gray = gray.values.toList(), diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/IntUiBridge.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/IntUiBridge.kt index 0faffc1f5..b429eb317 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/IntUiBridge.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/IntUiBridge.kt @@ -25,6 +25,8 @@ import com.intellij.ui.JBColor import com.intellij.util.ui.DirProvider import com.intellij.util.ui.JBUI import com.intellij.util.ui.NamedColorUtil +import javax.swing.UIManager +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.bridge.createVerticalBrush import org.jetbrains.jewel.bridge.dp import org.jetbrains.jewel.bridge.isNewUiTheme @@ -121,8 +123,6 @@ import org.jetbrains.jewel.ui.component.styling.TooltipMetrics import org.jetbrains.jewel.ui.component.styling.TooltipStyle import org.jetbrains.jewel.ui.icon.PathIconKey import org.jetbrains.jewel.ui.icons.AllIconsKeys -import javax.swing.UIManager -import kotlin.time.Duration.Companion.milliseconds private val logger = JewelLogger.getInstance("JewelIntUiBridge") @@ -237,18 +237,18 @@ internal fun createBridgeComponentStyling(theme: ThemeDefinition): ComponentStyl private fun readDefaultButtonStyle(): ButtonStyle { val normalBackground = listOf( - JBUI.CurrentTheme.Button.defaultButtonColorStart().toComposeColor(), - JBUI.CurrentTheme.Button.defaultButtonColorEnd().toComposeColor(), - ) + JBUI.CurrentTheme.Button.defaultButtonColorStart().toComposeColor(), + JBUI.CurrentTheme.Button.defaultButtonColorEnd().toComposeColor(), + ) .createVerticalBrush() val normalContent = retrieveColorOrUnspecified("Button.default.foreground") val normalBorder = listOf( - JBUI.CurrentTheme.Button.buttonOutlineColorStart(true).toComposeColor(), - JBUI.CurrentTheme.Button.buttonOutlineColorEnd(true).toComposeColor(), - ) + JBUI.CurrentTheme.Button.buttonOutlineColorStart(true).toComposeColor(), + JBUI.CurrentTheme.Button.buttonOutlineColorEnd(true).toComposeColor(), + ) .createVerticalBrush() val colors = @@ -287,18 +287,18 @@ private fun readDefaultButtonStyle(): ButtonStyle { private fun readOutlinedButtonStyle(): ButtonStyle { val normalBackground = listOf( - JBUI.CurrentTheme.Button.buttonColorStart().toComposeColor(), - JBUI.CurrentTheme.Button.buttonColorEnd().toComposeColor(), - ) + JBUI.CurrentTheme.Button.buttonColorStart().toComposeColor(), + JBUI.CurrentTheme.Button.buttonColorEnd().toComposeColor(), + ) .createVerticalBrush() val normalContent = retrieveColorOrUnspecified("Button.foreground") val normalBorder = listOf( - JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), - JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), - ) + JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), + JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), + ) .createVerticalBrush() val colors = @@ -417,7 +417,8 @@ private fun readChipStyle(): ChipStyle { ) } -private fun readDividerStyle() = DividerStyle(color = JBColor.border().toComposeColorOrUnspecified(), metrics = DividerMetrics.defaults()) +private fun readDividerStyle() = + DividerStyle(color = JBColor.border().toComposeColorOrUnspecified(), metrics = DividerMetrics.defaults()) private fun readDefaultDropdownStyle(menuStyle: MenuStyle): DropdownStyle { val normalBackground = retrieveColorOrUnspecified("ComboBox.nonEditableBackground") @@ -695,16 +696,16 @@ private fun readSegmentedControlButtonStyle(): SegmentedControlButtonStyle { val normalBorder = listOf( - JBUI.CurrentTheme.SegmentedButton.SELECTED_START_BORDER_COLOR.toComposeColor(), - JBUI.CurrentTheme.SegmentedButton.SELECTED_END_BORDER_COLOR.toComposeColor(), - ) + JBUI.CurrentTheme.SegmentedButton.SELECTED_START_BORDER_COLOR.toComposeColor(), + JBUI.CurrentTheme.SegmentedButton.SELECTED_END_BORDER_COLOR.toComposeColor(), + ) .createVerticalBrush() val selectedDisabledBorder = listOf( - JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), - JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), - ) + JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), + JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), + ) .createVerticalBrush() val colors = @@ -738,9 +739,9 @@ private fun readSegmentedControlButtonStyle(): SegmentedControlButtonStyle { private fun readSegmentedControlStyle(): SegmentedControlStyle { val normalBorder = listOf( - JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), - JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), - ) + JBUI.CurrentTheme.Button.buttonOutlineColorStart(false).toComposeColor(), + JBUI.CurrentTheme.Button.buttonOutlineColorEnd(false).toComposeColor(), + ) .createVerticalBrush() val colors = diff --git a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/ScrollbarBridge.kt b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/ScrollbarBridge.kt index ee3742921..5892bc5d4 100644 --- a/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/ScrollbarBridge.kt +++ b/ide-laf-bridge/src/main/kotlin/org/jetbrains/jewel/bridge/theme/ScrollbarBridge.kt @@ -5,6 +5,8 @@ import androidx.compose.foundation.shape.CornerSize import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.bridge.ScrollbarHelper import org.jetbrains.jewel.bridge.retrieveColor import org.jetbrains.jewel.ui.component.styling.ScrollbarColors @@ -13,8 +15,6 @@ import org.jetbrains.jewel.ui.component.styling.ScrollbarStyle import org.jetbrains.jewel.ui.component.styling.ScrollbarVisibility import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior import org.jetbrains.skiko.hostOs -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds internal fun readScrollbarStyle(isDark: Boolean): ScrollbarStyle = ScrollbarStyle( diff --git a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiDecoratedWindowResourceResolver.kt b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiDecoratedWindowResourceResolver.kt index 359dd64c5..20a356970 100644 --- a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiDecoratedWindowResourceResolver.kt +++ b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiDecoratedWindowResourceResolver.kt @@ -5,8 +5,8 @@ import org.jetbrains.jewel.ui.painter.ResourcePainterProvider import org.jetbrains.jewel.window.styling.DecoratedWindowStyle /** - * Create a [PainterProvider][org.jetbrains.jewel.painter.PainterProvider] - * for loading a decorated window module resource. + * Create a [PainterProvider][org.jetbrains.jewel.painter.PainterProvider] for loading a decorated window module + * resource. */ public fun decoratedWindowPainterProvider(path: String): ResourcePainterProvider = ResourcePainterProvider(path, DecoratedWindowStyle::class.java.classLoader, JewelTheme::class.java.classLoader) diff --git a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiTheme.kt b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiTheme.kt index 4a6c059c7..5ca966e8f 100644 --- a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiTheme.kt +++ b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/IntUiTheme.kt @@ -12,19 +12,11 @@ import org.jetbrains.jewel.window.styling.TitleBarStyle public fun ComponentStyling.decoratedWindow( windowStyle: DecoratedWindowStyle? = null, titleBarStyle: TitleBarStyle? = null, -): ComponentStyling = - provide { - val isDark = JewelTheme.isDark +): ComponentStyling = provide { + val isDark = JewelTheme.isDark - val currentWindowStyle = - windowStyle - ?: if (isDark) DecoratedWindowStyle.dark() else DecoratedWindowStyle.light() - val currentTitleBarStyle = - titleBarStyle - ?: if (isDark) TitleBarStyle.dark() else TitleBarStyle.light() + val currentWindowStyle = windowStyle ?: if (isDark) DecoratedWindowStyle.dark() else DecoratedWindowStyle.light() + val currentTitleBarStyle = titleBarStyle ?: if (isDark) TitleBarStyle.dark() else TitleBarStyle.light() - arrayOf( - LocalDecoratedWindowStyle provides currentWindowStyle, - LocalTitleBarStyle provides currentTitleBarStyle, - ) - } + arrayOf(LocalDecoratedWindowStyle provides currentWindowStyle, LocalTitleBarStyle provides currentTitleBarStyle) +} diff --git a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiDecoratedWindowStyling.kt b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiDecoratedWindowStyling.kt index a787791a4..890931579 100644 --- a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiDecoratedWindowStyling.kt +++ b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiDecoratedWindowStyling.kt @@ -29,4 +29,5 @@ public fun DecoratedWindowColors.Companion.dark( inactiveBorderColor: Color = borderColor, ): DecoratedWindowColors = DecoratedWindowColors(borderColor, inactiveBorderColor) -public fun DecoratedWindowMetrics.Companion.defaults(borderWidth: Dp = 1.dp): DecoratedWindowMetrics = DecoratedWindowMetrics(borderWidth) +public fun DecoratedWindowMetrics.Companion.defaults(borderWidth: Dp = 1.dp): DecoratedWindowMetrics = + DecoratedWindowMetrics(borderWidth) diff --git a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiTitleBarStyling.kt b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiTitleBarStyling.kt index 3736ffe3e..bb1cac611 100644 --- a/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiTitleBarStyling.kt +++ b/int-ui/int-ui-decorated-window/src/main/kotlin/org/jetbrains/jewel/intui/window/styling/IntUiTitleBarStyling.kt @@ -178,30 +178,27 @@ public fun TitleBarStyle.Companion.dark( ), ) -private fun titleBarIconButtonStyle( - hoveredBackground: Color, - pressedBackground: Color, - metrics: IconButtonMetrics, -) = IconButtonStyle( - IconButtonColors( - foregroundSelectedActivated = Color.Unspecified, - background = Color.Unspecified, - backgroundDisabled = Color.Unspecified, - backgroundSelected = Color.Unspecified, - backgroundSelectedActivated = Color.Unspecified, - backgroundFocused = Color.Unspecified, - backgroundPressed = hoveredBackground, - backgroundHovered = pressedBackground, - border = Color.Unspecified, - borderDisabled = Color.Unspecified, - borderSelected = Color.Unspecified, - borderSelectedActivated = Color.Unspecified, - borderFocused = hoveredBackground, - borderPressed = pressedBackground, - borderHovered = Color.Unspecified, - ), - metrics, -) +private fun titleBarIconButtonStyle(hoveredBackground: Color, pressedBackground: Color, metrics: IconButtonMetrics) = + IconButtonStyle( + IconButtonColors( + foregroundSelectedActivated = Color.Unspecified, + background = Color.Unspecified, + backgroundDisabled = Color.Unspecified, + backgroundSelected = Color.Unspecified, + backgroundSelectedActivated = Color.Unspecified, + backgroundFocused = Color.Unspecified, + backgroundPressed = hoveredBackground, + backgroundHovered = pressedBackground, + border = Color.Unspecified, + borderDisabled = Color.Unspecified, + borderSelected = Color.Unspecified, + borderSelectedActivated = Color.Unspecified, + borderFocused = hoveredBackground, + borderPressed = pressedBackground, + borderHovered = Color.Unspecified, + ), + metrics, + ) @Composable public fun TitleBarColors.Companion.light( @@ -226,7 +223,8 @@ public fun TitleBarColors.Companion.light( // but in com.intellij.ide.ui.laf.darcula.ui.ToolbarComboWidgetUI#paintBackground, // transparentHoveredBackground is used first, which is guessed to be due to the gradient // background - // caused by the project color of the titlebar, which makes the pure color background look strange + // caused by the project color of the titlebar, which makes the pure color background look + // strange // in the area. In order to simplify the use in Jewel, here directly use // transparentHoveredBackground // as hoveredBackground. diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/JetBrainsMonoFont.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/JetBrainsMonoFont.kt index 562adb634..e38f5919a 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/JetBrainsMonoFont.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/JetBrainsMonoFont.kt @@ -8,7 +8,11 @@ import androidx.compose.ui.text.platform.Font private val JetBrainsMonoFontFamily = FontFamily( Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Thin.ttf", weight = FontWeight.Thin), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-ThinItalic.ttf", weight = FontWeight.Thin, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-ThinItalic.ttf", + weight = FontWeight.Thin, + style = FontStyle.Italic, + ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-ExtraLight.ttf", weight = FontWeight.ExtraLight), Font( resource = "/fonts/jetbrains-mono/JetBrainsMono-ExtraLightItalic.ttf", @@ -16,11 +20,23 @@ private val JetBrainsMonoFontFamily = style = FontStyle.Italic, ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Light.ttf", weight = FontWeight.Light), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-LightItalic.ttf", weight = FontWeight.Light, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-LightItalic.ttf", + weight = FontWeight.Light, + style = FontStyle.Italic, + ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Regular.ttf", weight = FontWeight.Normal), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Italic.ttf", weight = FontWeight.Normal, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-Italic.ttf", + weight = FontWeight.Normal, + style = FontStyle.Italic, + ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Medium.ttf", weight = FontWeight.Medium), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-MediumItalic.ttf", weight = FontWeight.Medium, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-MediumItalic.ttf", + weight = FontWeight.Medium, + style = FontStyle.Italic, + ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-SemiBold.ttf", weight = FontWeight.SemiBold), Font( resource = "/fonts/jetbrains-mono/JetBrainsMono-SemiBoldItalic.ttf", @@ -28,7 +44,11 @@ private val JetBrainsMonoFontFamily = style = FontStyle.Italic, ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Bold.ttf", weight = FontWeight.Bold), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-BoldItalic.ttf", weight = FontWeight.Bold, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-BoldItalic.ttf", + weight = FontWeight.Bold, + style = FontStyle.Italic, + ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-ExtraBold.ttf", weight = FontWeight.ExtraBold), Font( resource = "/fonts/jetbrains-mono/JetBrainsMono-ExtraBoldItalic.ttf", @@ -36,7 +56,11 @@ private val JetBrainsMonoFontFamily = style = FontStyle.Italic, ), Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-Black.ttf", weight = FontWeight.Black), - Font(resource = "/fonts/jetbrains-mono/JetBrainsMono-BlackItalic.ttf", weight = FontWeight.Black, style = FontStyle.Italic), + Font( + resource = "/fonts/jetbrains-mono/JetBrainsMono-BlackItalic.ttf", + weight = FontWeight.Black, + style = FontStyle.Italic, + ), ) public val FontFamily.Companion.JetBrainsMono: FontFamily diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/PainterProvider.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/PainterProvider.kt index 84fa25645..d9cd73e22 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/PainterProvider.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/PainterProvider.kt @@ -3,8 +3,6 @@ package org.jetbrains.jewel.intui.standalone import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.ui.painter.ResourcePainterProvider -/** - * Create a [PainterProvider][org.jetbrains.jewel.painter.PainterProvider] to load a resource from - * the classpath. - */ -public fun standalonePainterProvider(path: String): ResourcePainterProvider = ResourcePainterProvider(path, JewelTheme::class.java.classLoader) +/** Create a [PainterProvider][org.jetbrains.jewel.painter.PainterProvider] to load a resource from the classpath. */ +public fun standalonePainterProvider(path: String): ResourcePainterProvider = + ResourcePainterProvider(path, JewelTheme::class.java.classLoader) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/StandalonePainterHintsProvider.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/StandalonePainterHintsProvider.kt index 1196d56d2..c410fe40d 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/StandalonePainterHintsProvider.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/StandalonePainterHintsProvider.kt @@ -13,9 +13,8 @@ import org.jetbrains.jewel.ui.painter.hints.PathOverride import org.jetbrains.jewel.ui.util.fromRGBAHexStringOrNull /** Provides the default [PainterHint]s to use to load images. */ -public class StandalonePainterHintsProvider( - theme: ThemeDefinition, -) : PalettePainterHintsProvider( +public class StandalonePainterHintsProvider(theme: ThemeDefinition) : + PalettePainterHintsProvider( theme.isDark, intellijColorPalette, theme.iconData.colorPalette, @@ -23,9 +22,7 @@ public class StandalonePainterHintsProvider( ) { private val overrideHint: PainterHint = PathOverride( - theme.iconData.iconOverrides.entries.associate { (k, v) -> - k.removePrefix("/") to v.removePrefix("/") - }, + theme.iconData.iconOverrides.entries.associate { (k, v) -> k.removePrefix("/") to v.removePrefix("/") } ) protected override val checkBoxByColorPaletteHint: PainterHint @@ -59,13 +56,12 @@ public class StandalonePainterHintsProvider( } @Composable - override fun hints(path: String): List = - buildList { - add(getPaletteHint(path)) - add(overrideHint) - add(HiDpi()) - add(Dark(JewelTheme.isDark)) - } + override fun hints(path: String): List = buildList { + add(getPaletteHint(path)) + add(overrideHint) + add(HiDpi()) + add(Dark(JewelTheme.isDark)) + } public companion object { // Extracted from com.intellij.ide.ui.UITheme#colorPalette diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCheckboxStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCheckboxStyling.kt index 84f183802..953697a44 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCheckboxStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCheckboxStyling.kt @@ -50,29 +50,16 @@ public fun CheckboxMetrics.Companion.defaults( outlineSize: DpSize = DpSize(15.dp, 15.dp), outlineOffset: DpOffset = DpOffset(2.5.dp, 1.5.dp), iconContentGap: Dp = 5.dp, -): CheckboxMetrics = - CheckboxMetrics( - checkboxSize, - checkboxCornerSize, - outlineSize, - outlineOffset, - iconContentGap, - ) +): CheckboxMetrics = CheckboxMetrics(checkboxSize, checkboxCornerSize, outlineSize, outlineOffset, iconContentGap) @Composable public fun CheckboxIcons.Companion.light( checkbox: IconKey = - PathIconKey( - path = "com/intellij/ide/ui/laf/icons/intellij/checkBox.svg", - iconClass = CheckboxIcons::class.java, - ), + PathIconKey(path = "com/intellij/ide/ui/laf/icons/intellij/checkBox.svg", iconClass = CheckboxIcons::class.java) ): CheckboxIcons = CheckboxIcons(checkbox) @Composable public fun CheckboxIcons.Companion.dark( checkbox: IconKey = - PathIconKey( - path = "com/intellij/ide/ui/laf/icons/darcula/checkBox.svg", - iconClass = CheckboxIcons::class.java, - ), + PathIconKey(path = "com/intellij/ide/ui/laf/icons/darcula/checkBox.svg", iconClass = CheckboxIcons::class.java) ): CheckboxIcons = CheckboxIcons(checkbox) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCircularProgressStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCircularProgressStyling.kt index 15b29b78c..9024c466e 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCircularProgressStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiCircularProgressStyling.kt @@ -1,14 +1,11 @@ -@file:Suppress( - "MatchingDeclarationName", - "ktlint:standard:filename", -) // Going for consistency with other files +@file:Suppress("MatchingDeclarationName", "ktlint:standard:filename") // Going for consistency with other files package org.jetbrains.jewel.intui.standalone.styling import androidx.compose.ui.graphics.Color -import org.jetbrains.jewel.ui.component.styling.CircularProgressStyle import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds +import org.jetbrains.jewel.ui.component.styling.CircularProgressStyle public fun CircularProgressStyle.Companion.dark( frameTime: Duration = 125.milliseconds, diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiDropdownStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiDropdownStyling.kt index 0c710aa45..6a1b60f28 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiDropdownStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiDropdownStyling.kt @@ -259,4 +259,5 @@ public fun DropdownMetrics.Companion.undecorated( borderWidth: Dp = 0.dp, ): DropdownMetrics = DropdownMetrics(arrowMinSize, minSize, cornerSize, contentPadding, borderWidth) -public fun DropdownIcons.Companion.defaults(chevronDown: IconKey = AllIconsKeys.General.ChevronDown): DropdownIcons = DropdownIcons(chevronDown) +public fun DropdownIcons.Companion.defaults(chevronDown: IconKey = AllIconsKeys.General.ChevronDown): DropdownIcons = + DropdownIcons(chevronDown) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiGroupHeaderStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiGroupHeaderStyling.kt index 7f4df04a1..1d1808207 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiGroupHeaderStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiGroupHeaderStyling.kt @@ -23,12 +23,12 @@ public fun GroupHeaderStyle.Companion.dark( ): GroupHeaderStyle = GroupHeaderStyle(colors, metrics) @Composable -public fun GroupHeaderColors.Companion.light(divider: Color = IntUiLightTheme.colors.gray(12)): GroupHeaderColors = GroupHeaderColors(divider) +public fun GroupHeaderColors.Companion.light(divider: Color = IntUiLightTheme.colors.gray(12)): GroupHeaderColors = + GroupHeaderColors(divider) @Composable -public fun GroupHeaderColors.Companion.dark(divider: Color = IntUiDarkTheme.colors.gray(3)): GroupHeaderColors = GroupHeaderColors(divider) +public fun GroupHeaderColors.Companion.dark(divider: Color = IntUiDarkTheme.colors.gray(3)): GroupHeaderColors = + GroupHeaderColors(divider) -public fun GroupHeaderMetrics.Companion.defaults( - dividerThickness: Dp = 1.dp, - indent: Dp = 8.dp, -): GroupHeaderMetrics = GroupHeaderMetrics(dividerThickness, indent) +public fun GroupHeaderMetrics.Companion.defaults(dividerThickness: Dp = 1.dp, indent: Dp = 8.dp): GroupHeaderMetrics = + GroupHeaderMetrics(dividerThickness, indent) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiHorizontalProgressBarStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiHorizontalProgressBarStyling.kt index c5cf32bb3..5ebaa1e7e 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiHorizontalProgressBarStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiHorizontalProgressBarStyling.kt @@ -5,13 +5,13 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.intui.core.theme.IntUiDarkTheme import org.jetbrains.jewel.intui.core.theme.IntUiLightTheme import org.jetbrains.jewel.ui.component.styling.HorizontalProgressBarColors import org.jetbrains.jewel.ui.component.styling.HorizontalProgressBarMetrics import org.jetbrains.jewel.ui.component.styling.HorizontalProgressBarStyle -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds @Composable public fun HorizontalProgressBarStyle.Companion.light( diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiLazyTreeStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiLazyTreeStyling.kt index af7407797..6c308b950 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiLazyTreeStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiLazyTreeStyling.kt @@ -91,10 +91,4 @@ public fun LazyTreeIcons.Companion.defaults( chevronExpanded: IconKey = AllIconsKeys.General.ChevronDown, chevronSelectedCollapsed: IconKey = chevronCollapsed, chevronSelectedExpanded: IconKey = chevronExpanded, -): LazyTreeIcons = - LazyTreeIcons( - chevronCollapsed, - chevronExpanded, - chevronSelectedCollapsed, - chevronSelectedExpanded, - ) +): LazyTreeIcons = LazyTreeIcons(chevronCollapsed, chevronExpanded, chevronSelectedCollapsed, chevronSelectedExpanded) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiMenuStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiMenuStyling.kt index 30cd2adae..05cf77711 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiMenuStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiMenuStyling.kt @@ -39,13 +39,7 @@ public fun MenuColors.Companion.light( border: Color = IntUiLightTheme.colors.gray(9), shadow: Color = Color(0x78919191), // Not a palette color itemColors: MenuItemColors = MenuItemColors.light(), -): MenuColors = - MenuColors( - background = background, - border = border, - shadow = shadow, - itemColors = itemColors, - ) +): MenuColors = MenuColors(background = background, border = border, shadow = shadow, itemColors = itemColors) @Composable public fun MenuColors.Companion.dark( @@ -53,13 +47,7 @@ public fun MenuColors.Companion.dark( border: Color = IntUiDarkTheme.colors.gray(3), shadow: Color = Color(0x66000000), // Not a palette color itemColors: MenuItemColors = MenuItemColors.dark(), -): MenuColors = - MenuColors( - background = background, - border = border, - shadow = shadow, - itemColors = itemColors, - ) +): MenuColors = MenuColors(background = background, border = border, shadow = shadow, itemColors = itemColors) @Composable public fun MenuItemColors.Companion.light( @@ -167,16 +155,7 @@ public fun MenuMetrics.Companion.defaults( itemMetrics: MenuItemMetrics = MenuItemMetrics.defaults(), submenuMetrics: SubmenuMetrics = SubmenuMetrics.defaults(), ): MenuMetrics = - MenuMetrics( - cornerSize, - menuMargin, - contentPadding, - offset, - shadowSize, - borderWidth, - itemMetrics, - submenuMetrics, - ) + MenuMetrics(cornerSize, menuMargin, contentPadding, offset, shadowSize, borderWidth, itemMetrics, submenuMetrics) public fun MenuItemMetrics.Companion.defaults( selectionCornerSize: CornerSize = CornerSize(4.dp), @@ -201,6 +180,8 @@ public fun MenuItemMetrics.Companion.defaults( minHeight, ) -public fun SubmenuMetrics.Companion.defaults(offset: DpOffset = DpOffset(0.dp, (-8).dp)): SubmenuMetrics = SubmenuMetrics(offset) +public fun SubmenuMetrics.Companion.defaults(offset: DpOffset = DpOffset(0.dp, (-8).dp)): SubmenuMetrics = + SubmenuMetrics(offset) -public fun MenuIcons.Companion.defaults(submenuChevron: IconKey = AllIconsKeys.General.ChevronRight): MenuIcons = MenuIcons(submenuChevron) +public fun MenuIcons.Companion.defaults(submenuChevron: IconKey = AllIconsKeys.General.ChevronRight): MenuIcons = + MenuIcons(submenuChevron) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiRadioButtonStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiRadioButtonStyling.kt index 05d102d33..1855cd391 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiRadioButtonStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiRadioButtonStyling.kt @@ -71,16 +71,10 @@ public fun RadioButtonMetrics.Companion.defaults( public fun RadioButtonIcons.Companion.light( radioButton: IconKey = - PathIconKey( - path = "com/intellij/ide/ui/laf/icons/intellij/radio.svg", - iconClass = RadioButtonIcons::class.java, - ), + PathIconKey(path = "com/intellij/ide/ui/laf/icons/intellij/radio.svg", iconClass = RadioButtonIcons::class.java) ): RadioButtonIcons = RadioButtonIcons(radioButton) public fun RadioButtonIcons.Companion.dark( radioButton: IconKey = - PathIconKey( - path = "com/intellij/ide/ui/laf/icons/darcula/radio.svg", - iconClass = RadioButtonIcons::class.java, - ), + PathIconKey(path = "com/intellij/ide/ui/laf/icons/darcula/radio.svg", iconClass = RadioButtonIcons::class.java) ): RadioButtonIcons = RadioButtonIcons(radioButton) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiScrollbarStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiScrollbarStyling.kt index e1096ee66..ea280b9d0 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiScrollbarStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiScrollbarStyling.kt @@ -5,6 +5,8 @@ import androidx.compose.foundation.shape.CornerSize import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.ui.component.styling.ScrollbarColors import org.jetbrains.jewel.ui.component.styling.ScrollbarMetrics import org.jetbrains.jewel.ui.component.styling.ScrollbarStyle @@ -13,8 +15,6 @@ import org.jetbrains.jewel.ui.component.styling.ScrollbarVisibility.AlwaysVisibl import org.jetbrains.jewel.ui.component.styling.ScrollbarVisibility.WhenScrolling import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior import org.jetbrains.skiko.hostOs -import kotlin.time.Duration -import kotlin.time.Duration.Companion.milliseconds public fun ScrollbarStyle.Companion.light(): ScrollbarStyle = if (hostOs.isMacOS) { diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSegmentedControlButtonStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSegmentedControlButtonStyling.kt index a48633733..5f146fada 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSegmentedControlButtonStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSegmentedControlButtonStyling.kt @@ -89,9 +89,4 @@ public fun SegmentedControlButtonMetrics.Companion.defaults( minSize: DpSize = DpSize(width = Dp.Unspecified, height = 24.dp - 2.dp), borderWidth: Dp = 1.dp, ): SegmentedControlButtonMetrics = - SegmentedControlButtonMetrics( - cornerSize, - segmentedButtonPadding, - minSize, - borderWidth, - ) + SegmentedControlButtonMetrics(cornerSize, segmentedButtonPadding, minSize, borderWidth) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSliderStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSliderStyling.kt index d1b6d448d..f26c4b529 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSliderStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiSliderStyling.kt @@ -107,4 +107,5 @@ public fun SliderMetrics.Companion.defaults( stepLineHeight: Dp = 8.dp, stepLineWidth: Dp = 1.dp, trackToStepSpacing: Dp = thumbSize.height / 2 + 4.dp, -): SliderMetrics = SliderMetrics(trackHeight, thumbSize, thumbBorderWidth, stepLineHeight, stepLineWidth, trackToStepSpacing) +): SliderMetrics = + SliderMetrics(trackHeight, thumbSize, thumbBorderWidth, stepLineHeight, stepLineWidth, trackToStepSpacing) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTabStripScrollbarStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTabStripScrollbarStyling.kt index 79561c630..c1334d157 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTabStripScrollbarStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTabStripScrollbarStyling.kt @@ -5,13 +5,13 @@ import androidx.compose.foundation.shape.CornerSize import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.ui.component.styling.ScrollbarColors import org.jetbrains.jewel.ui.component.styling.ScrollbarMetrics import org.jetbrains.jewel.ui.component.styling.ScrollbarStyle import org.jetbrains.jewel.ui.component.styling.ScrollbarVisibility import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior import org.jetbrains.skiko.hostOs -import kotlin.time.Duration.Companion.milliseconds public fun ScrollbarStyle.Companion.tabStripLight(): ScrollbarStyle = if (hostOs.isMacOS) { diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTooltipStyling.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTooltipStyling.kt index c62217579..63fedcaca 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTooltipStyling.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/styling/IntUiTooltipStyling.kt @@ -12,21 +12,13 @@ import org.jetbrains.jewel.ui.component.styling.TooltipStyle public fun TooltipStyle.Companion.light( intUiTooltipColors: TooltipColors = TooltipColors.light(), intUiTooltipMetrics: TooltipMetrics = TooltipMetrics.defaults(), -): TooltipStyle = - TooltipStyle( - colors = intUiTooltipColors, - metrics = intUiTooltipMetrics, - ) +): TooltipStyle = TooltipStyle(colors = intUiTooltipColors, metrics = intUiTooltipMetrics) @Composable public fun TooltipStyle.Companion.dark( intUiTooltipColors: TooltipColors = TooltipColors.dark(), intUiTooltipMetrics: TooltipMetrics = TooltipMetrics.defaults(), -): TooltipStyle = - TooltipStyle( - colors = intUiTooltipColors, - metrics = intUiTooltipMetrics, - ) +): TooltipStyle = TooltipStyle(colors = intUiTooltipColors, metrics = intUiTooltipMetrics) @Composable public fun TooltipColors.Companion.light( @@ -34,8 +26,7 @@ public fun TooltipColors.Companion.light( contentColor: Color = IntUiLightTheme.colors.gray(12), borderColor: Color = backgroundColor, shadow: Color = Color(0x78919191), // Not a palette color -): TooltipColors = - TooltipColors(backgroundColor, contentColor, borderColor, shadow) +): TooltipColors = TooltipColors(backgroundColor, contentColor, borderColor, shadow) @Composable public fun TooltipColors.Companion.dark( @@ -43,5 +34,4 @@ public fun TooltipColors.Companion.dark( contentColor: Color = IntUiDarkTheme.colors.gray(12), borderColor: Color = IntUiDarkTheme.colors.gray(3), shadow: Color = Color(0x66000000), // Not a palette color -): TooltipColors = - TooltipColors(backgroundColor, contentColor, borderColor, shadow) +): TooltipColors = TooltipColors(backgroundColor, contentColor, borderColor, shadow) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalColors.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalColors.kt index a7768185c..27c25cab7 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalColors.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalColors.kt @@ -15,13 +15,7 @@ public fun GlobalColors.Companion.light( outlines: OutlineColors = OutlineColors.light(), text: TextColors = TextColors.light(), paneBackground: Color = IntUiLightTheme.colors.gray(13), -): GlobalColors = - GlobalColors( - borders = borders, - outlines = outlines, - text = text, - panelBackground = paneBackground, - ) +): GlobalColors = GlobalColors(borders = borders, outlines = outlines, text = text, panelBackground = paneBackground) @Composable public fun GlobalColors.Companion.dark( @@ -29,13 +23,7 @@ public fun GlobalColors.Companion.dark( outlines: OutlineColors = OutlineColors.dark(), text: TextColors = TextColors.dark(), paneBackground: Color = IntUiDarkTheme.colors.gray(2), -): GlobalColors = - GlobalColors( - borders = borders, - outlines = outlines, - text = text, - panelBackground = paneBackground, - ) +): GlobalColors = GlobalColors(borders = borders, outlines = outlines, text = text, panelBackground = paneBackground) @Composable public fun BorderColors.Companion.light( diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalMetrics.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalMetrics.kt index e2ed3b49d..51cc00bdc 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalMetrics.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiGlobalMetrics.kt @@ -4,7 +4,5 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import org.jetbrains.jewel.foundation.GlobalMetrics -public fun GlobalMetrics.Companion.defaults( - outlineWidth: Dp = 2.dp, - rowHeight: Dp = 24.dp, -): GlobalMetrics = GlobalMetrics(outlineWidth, rowHeight) +public fun GlobalMetrics.Companion.defaults(outlineWidth: Dp = 2.dp, rowHeight: Dp = 24.dp): GlobalMetrics = + GlobalMetrics(outlineWidth, rowHeight) diff --git a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiTheme.kt b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiTheme.kt index a963bfaa9..9059b35f6 100644 --- a/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiTheme.kt +++ b/int-ui/int-ui-standalone/src/main/kotlin/org/jetbrains/jewel/intui/standalone/theme/IntUiTheme.kt @@ -96,11 +96,10 @@ public fun JewelTheme.Companion.darkThemeDefinition( ) @Composable -public fun ComponentStyling.default(): ComponentStyling = - with { - val isDark = JewelTheme.isDark - if (isDark) dark() else light() - } +public fun ComponentStyling.default(): ComponentStyling = with { + val isDark = JewelTheme.isDark + if (isDark) dark() else light() +} @Composable public fun ComponentStyling.dark( @@ -155,7 +154,7 @@ public fun ComponentStyling.dark( textFieldStyle = textFieldStyle, tooltipStyle = tooltipStyle, undecoratedDropdownStyle = undecoratedDropdownStyle, - ), + ) ) @Composable @@ -211,17 +210,12 @@ public fun ComponentStyling.light( textFieldStyle = textFieldStyle, tooltipStyle = tooltipStyle, undecoratedDropdownStyle = undecoratedDropdownStyle, - ), + ) ) @Composable -public fun IntUiTheme( - isDark: Boolean = false, - swingCompatMode: Boolean = false, - content: @Composable () -> Unit, -) { - val themeDefinition = - if (isDark) JewelTheme.darkThemeDefinition() else JewelTheme.lightThemeDefinition() +public fun IntUiTheme(isDark: Boolean = false, swingCompatMode: Boolean = false, content: @Composable () -> Unit) { + val themeDefinition = if (isDark) JewelTheme.darkThemeDefinition() else JewelTheme.lightThemeDefinition() IntUiTheme( theme = themeDefinition, @@ -238,11 +232,7 @@ public fun IntUiTheme( swingCompatMode: Boolean = false, content: @Composable () -> Unit, ) { - BaseJewelTheme( - theme, - ComponentStyling.default().with(styling), - swingCompatMode, - ) { + BaseJewelTheme(theme, ComponentStyling.default().with(styling), swingCompatMode) { CompositionLocalProvider( LocalPainterHintsProvider provides StandalonePainterHintsProvider(theme), LocalNewUiChecker provides StandaloneNewUiChecker, diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/InlineMarkdown.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/InlineMarkdown.kt index 9b0511c17..03ef42323 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/InlineMarkdown.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/InlineMarkdown.kt @@ -2,27 +2,21 @@ package org.jetbrains.jewel.markdown import org.jetbrains.jewel.foundation.GenerateDataFunctions -/** - * A run of inline Markdown used as content for - * [block-level elements][MarkdownBlock]. - */ +/** A run of inline Markdown used as content for [block-level elements][MarkdownBlock]. */ public sealed interface InlineMarkdown { - @GenerateDataFunctions - public class Code(override val content: String) : InlineMarkdown, WithTextContent + @GenerateDataFunctions public class Code(override val content: String) : InlineMarkdown, WithTextContent public interface CustomNode : InlineMarkdown { /** - * If this custom node has a text-based representation, this function - * should return it. Otherwise, it should return null. + * If this custom node has a text-based representation, this function should return it. Otherwise, it should + * return null. */ public fun contentOrNull(): String? = null } @GenerateDataFunctions - public class Emphasis( - public val delimiter: String, - override val inlineContent: List, - ) : InlineMarkdown, WithInlineMarkdown { + public class Emphasis(public val delimiter: String, override val inlineContent: List) : + InlineMarkdown, WithInlineMarkdown { public constructor( delimiter: String, vararg inlineContent: InlineMarkdown, @@ -31,8 +25,7 @@ public sealed interface InlineMarkdown { public data object HardLineBreak : InlineMarkdown - @GenerateDataFunctions - public class HtmlInline(override val content: String) : InlineMarkdown, WithTextContent + @GenerateDataFunctions public class HtmlInline(override val content: String) : InlineMarkdown, WithTextContent @GenerateDataFunctions public class Image( @@ -65,16 +58,13 @@ public sealed interface InlineMarkdown { public data object SoftLineBreak : InlineMarkdown @GenerateDataFunctions - public class StrongEmphasis( - public val delimiter: String, - override val inlineContent: List, - ) : InlineMarkdown, WithInlineMarkdown { + public class StrongEmphasis(public val delimiter: String, override val inlineContent: List) : + InlineMarkdown, WithInlineMarkdown { public constructor( delimiter: String, vararg inlineContent: InlineMarkdown, ) : this(delimiter, inlineContent.toList()) } - @GenerateDataFunctions - public class Text(override val content: String) : InlineMarkdown, WithTextContent + @GenerateDataFunctions public class Text(override val content: String) : InlineMarkdown, WithTextContent } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/Markdown.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/Markdown.kt index d7288c40f..03f253dad 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/Markdown.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/Markdown.kt @@ -47,8 +47,7 @@ public fun Markdown( ) { var markdownBlocks by remember { mutableStateOf(emptyList()) } LaunchedEffect(markdown, processor) { - markdownBlocks = - withContext(renderingDispatcher) { processor.processMarkdownDocument(markdown) } + markdownBlocks = withContext(renderingDispatcher) { processor.processMarkdownDocument(markdown) } } Markdown( @@ -118,9 +117,7 @@ public fun LazyMarkdown( contentPadding = contentPadding, verticalArrangement = Arrangement.spacedBy(markdownStyling.blockVerticalSpacing), ) { - items(markdownBlocks) { block -> - blockRenderer.render(block, enabled, onUrlClick, onTextClick) - } + items(markdownBlocks) { block -> blockRenderer.render(block, enabled, onUrlClick, onTextClick) } } } } else { @@ -130,9 +127,7 @@ public fun LazyMarkdown( contentPadding = contentPadding, verticalArrangement = Arrangement.spacedBy(markdownStyling.blockVerticalSpacing), ) { - items(markdownBlocks) { block -> - blockRenderer.render(block, enabled, onUrlClick, onTextClick) - } + items(markdownBlocks) { block -> blockRenderer.render(block, enabled, onUrlClick, onTextClick) } } } } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MarkdownBlock.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MarkdownBlock.kt index 99b7c2c5a..309b2d66d 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MarkdownBlock.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MarkdownBlock.kt @@ -11,28 +11,21 @@ public sealed interface MarkdownBlock { public sealed interface CodeBlock : MarkdownBlock { public val content: String - @GenerateDataFunctions - public class IndentedCodeBlock(override val content: String) : CodeBlock + @GenerateDataFunctions public class IndentedCodeBlock(override val content: String) : CodeBlock @GenerateDataFunctions - public class FencedCodeBlock( - override val content: String, - public val mimeType: MimeType?, - ) : CodeBlock + public class FencedCodeBlock(override val content: String, public val mimeType: MimeType?) : CodeBlock } public interface CustomBlock : MarkdownBlock @GenerateDataFunctions - public class Heading( - override val inlineContent: List, - public val level: Int, - ) : MarkdownBlock, WithInlineMarkdown { + public class Heading(override val inlineContent: List, public val level: Int) : + MarkdownBlock, WithInlineMarkdown { public constructor(level: Int, vararg inlineContent: InlineMarkdown) : this(inlineContent.toList(), level) } - @GenerateDataFunctions - public class HtmlBlock(public val content: String) : MarkdownBlock + @GenerateDataFunctions public class HtmlBlock(public val content: String) : MarkdownBlock public sealed interface ListBlock : MarkdownBlock { public val children: List @@ -75,9 +68,7 @@ public sealed interface MarkdownBlock { public data object ThematicBreak : MarkdownBlock @GenerateDataFunctions - public class Paragraph( - override val inlineContent: List, - ) : MarkdownBlock, WithInlineMarkdown { + public class Paragraph(override val inlineContent: List) : MarkdownBlock, WithInlineMarkdown { public constructor(vararg inlineContent: InlineMarkdown) : this(inlineContent.toList()) } } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MimeType.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MimeType.kt index 263c429d4..f72d241bd 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MimeType.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/MimeType.kt @@ -10,30 +10,22 @@ import org.jetbrains.jewel.markdown.MimeType.Known.TYPESCRIPT import org.jetbrains.jewel.markdown.MimeType.Known.YAML /** - * Represents the language and dialect of a source snippet, as an RFC 2046 - * mime type. + * Represents the language and dialect of a source snippet, as an RFC 2046 mime type. * - * For example, a Kotlin source file may have the mime type `text/kotlin`. - * However, if it corresponds to a `build.gradle.kts` file, we'll also - * attach the mime parameter `role=gradle`, resulting in mime type - * `text/kotlin; role=gradle`. + * For example, a Kotlin source file may have the mime type `text/kotlin`. However, if it corresponds to a + * `build.gradle.kts` file, we'll also attach the mime parameter `role=gradle`, resulting in mime type `text/kotlin; + * role=gradle`. * - * For XML resource files, we'll attach other attributes; for example - * `role=manifest` for Android manifest files and `role=resource` for - * XML resource files. For the latter we may also attach for example - * `folderType=values`, and for XML files in general, the root tag, such - * as `text/xml; role=resource; folderType=layout; rootTag=LinearLayout`. + * For XML resource files, we'll attach other attributes; for example `role=manifest` for Android manifest files and + * `role=resource` for XML resource files. For the latter we may also attach for example `folderType=values`, and for + * XML files in general, the root tag, such as `text/xml; role=resource; folderType=layout; rootTag=LinearLayout`. * - * This class does not implement *all* aspects of the RFC; in particular, - * we don't treat attributes as case-insensitive, and we only support - * value tokens, not value strings -- neither of these are needed for our - * purposes. + * This class does not implement *all* aspects of the RFC; in particular, we don't treat attributes as case-insensitive, + * and we only support value tokens, not value strings -- neither of these are needed for our purposes. * - * This is implemented using a value class, such that behind the scenes - * we're really just passing a String around. This also means we can't - * initialize related values such as the corresponding Markdown fenced - * block names, or IntelliJ language id's. Instead, these are looked up via - * `when`-tables. When adding a new language, update all lookup methods: + * This is implemented using a value class, such that behind the scenes we're really just passing a String around. This + * also means we can't initialize related values such as the corresponding Markdown fenced block names, or IntelliJ + * language id's. Instead, these are looked up via `when`-tables. When adding a new language, update all lookup methods: * * [displayName] */ @JvmInline @@ -112,8 +104,7 @@ public value class MimeType(private val mimeType: String) { Known.SHELL, Known.YAML, Known.GO, - Known.UNKNOWN, - -> return this.mimeType + Known.UNKNOWN -> return this.mimeType } val baseEnd = mimeType.indexOf(';') @@ -121,49 +112,41 @@ public value class MimeType(private val mimeType: String) { when (val base = if (baseEnd == -1) mimeType else mimeType.substring(0, baseEnd)) { "text/x-java-source", "application/x-java", - "text/x-java", - -> Known.JAVA.mimeType + "text/x-java" -> Known.JAVA.mimeType "application/kotlin-source", "text/x-kotlin", - "text/x-kotlin-source", - -> KOTLIN.mimeType + "text/x-kotlin-source" -> KOTLIN.mimeType "application/xml" -> Known.XML.mimeType "application/json", "application/vnd.api+json", "application/hal+json", - "application/ld+json", - -> JSON.mimeType + "application/ld+json" -> JSON.mimeType "image/svg+xml" -> Known.XML.mimeType "text/x-python", - "application/x-python-script", - -> PYTHON.mimeType + "application/x-python-script" -> PYTHON.mimeType "text/dart", "text/x-dart", "application/dart", - "application/x-dart", - -> DART.mimeType + "application/x-dart" -> DART.mimeType "application/javascript", "application/x-javascript", "text/ecmascript", "application/ecmascript", - "application/x-ecmascript", - -> Known.JAVASCRIPT.mimeType + "application/x-ecmascript" -> Known.JAVASCRIPT.mimeType "application/typescript" + "application/x-typescript" -> TYPESCRIPT.mimeType "text/x-rust", - "application/x-rust", - -> RUST.mimeType + "application/x-rust" -> RUST.mimeType "text/x-sksl" -> AGSL.mimeType "application/yaml", "text/x-yaml", - "application/x-yaml", - -> YAML.mimeType + "application/x-yaml" -> YAML.mimeType else -> base } @@ -197,16 +180,12 @@ public value class MimeType(private val mimeType: String) { } } - /** - * Returns whether the given attribute should be included in a normalized - * string - */ + /** Returns whether the given attribute should be included in a normalized string */ private fun isRelevantAttribute(attribute: String): Boolean = when (attribute) { ATTR_ROLE, ATTR_ROOT_TAG, - ATTR_FOLDER_TYPE, - -> true + ATTR_FOLDER_TYPE -> true else -> false } @@ -214,9 +193,8 @@ public value class MimeType(private val mimeType: String) { /** * Returns just the language portion of the mime type. * - * For example, for `text/kotlin; role=gradle` this will return - * `text/kotlin`. For `text/plain; charset=us-ascii` this returns - * `text/plain` + * For example, for `text/kotlin; role=gradle` this will return `text/kotlin`. For `text/plain; charset=us-ascii` + * this returns `text/plain` */ public fun base(): MimeType = MimeType(mimeType.substringBefore(';').trim()) @@ -242,15 +220,12 @@ public value class MimeType(private val mimeType: String) { private companion object { /** - * Attribute used to indicate the role this source file plays; for example, - * an XML file may be a "manifest" or a "resource". + * Attribute used to indicate the role this source file plays; for example, an XML file may be a "manifest" or a + * "resource". */ const val ATTR_ROLE: String = "role" - /** - * For XML resource files, the folder type if any (such as "values" or - * "layout") - */ + /** For XML resource files, the folder type if any (such as "values" or "layout") */ const val ATTR_FOLDER_TYPE: String = "folderType" /** For XML files, the root tag in the content */ @@ -264,10 +239,9 @@ public value class MimeType(private val mimeType: String) { // Well known mime types for major languages. /** - * Well known name for Kotlin source snippets. This is the base mime type; - * consider using [isKotlin] instead to check if a mime type represents - * Kotlin code such that it also picks up `build.gradle.kts` files - * (which carry extra attributes in the mime type; see [GRADLE_KTS].) + * Well known name for Kotlin source snippets. This is the base mime type; consider using [isKotlin] instead to + * check if a mime type represents Kotlin code such that it also picks up `build.gradle.kts` files (which carry + * extra attributes in the mime type; see [GRADLE_KTS].) */ public val KOTLIN: MimeType = MimeType("text/kotlin") @@ -278,23 +252,19 @@ public value class MimeType(private val mimeType: String) { public val TEXT: MimeType = MimeType("text/plain") /** - * Special marker mimetype for unknown or unspecified mime types. These - * will generally be treated as [TEXT] for editor purposes. (The standard - * "unknown" mime type is application/octet-stream (from RFC 2046) but we - * know this isn't binary data; it's text.) + * Special marker mimetype for unknown or unspecified mime types. These will generally be treated as [TEXT] for + * editor purposes. (The standard "unknown" mime type is application/octet-stream (from RFC 2046) but we know + * this isn't binary data; it's text.) * - * Note that [MimeType] is generally nullable in places where it's optional - * instead of being set to this value, but this mime type is there for - * places where we need a specific value to point to. + * Note that [MimeType] is generally nullable in places where it's optional instead of being set to this value, + * but this mime type is there for places where we need a specific value to point to. */ public val UNKNOWN: MimeType = MimeType("text/unknown") /** - * Well known name for XML source snippets. This is the base mime type; - * consider using [isXml] instead to check if a mime type represents any - * XML such that it also picks up manifest files, resource files etc., - * which all carry extra attributes in the mime type; see for example - * [MANIFEST] and [RESOURCE]. + * Well known name for XML source snippets. This is the base mime type; consider using [isXml] instead to check + * if a mime type represents any XML such that it also picks up manifest files, resource files etc., which all + * carry extra attributes in the mime type; see for example [MANIFEST] and [RESOURCE]. */ public val XML: MimeType = MimeType("text/xml") public val PROPERTIES: MimeType = MimeType("text/properties") @@ -319,10 +289,7 @@ public value class MimeType(private val mimeType: String) { public val YAML: MimeType = MimeType("text/yaml") public val GO: MimeType = MimeType("text/go") - /** - * Note that most resource files will also have a folder type, so don't use - * equality on this mime type - */ + /** Note that most resource files will also have a folder type, so don't use equality on this mime type */ public val RESOURCE: MimeType = MimeType("$XML; $ATTR_ROLE=resource") public val MANIFEST: MimeType = MimeType("$XML;$ATTR_ROLE=manifest $ATTR_ROOT_TAG=manifest") public val GRADLE: MimeType = MimeType("$GROOVY; $ATTR_ROLE=gradle") @@ -334,18 +301,15 @@ public value class MimeType(private val mimeType: String) { when (name) { "kotlin", "kt", - "kts", - -> KOTLIN + "kts" -> KOTLIN "java" -> JAVA "xml" -> XML "json", - "json5", - -> JSON + "json5" -> JSON "regex", - "regexp", - -> REGEX + "regexp" -> REGEX "groovy" -> GROOVY "toml" -> TOML @@ -359,30 +323,25 @@ public value class MimeType(private val mimeType: String) { "python2", "python3", "py", - "python", - -> PYTHON + "python" -> PYTHON "dart" -> DART "rust" -> RUST "js", - "javascript", - -> JAVASCRIPT + "javascript" -> JAVASCRIPT "typescript" -> TYPESCRIPT "sksl" -> AGSL "sh", "bash", "zsh", - "shell", - -> SHELL + "shell" -> SHELL "yaml", - "yml", - -> YAML + "yml" -> YAML "go", - "golang", - -> YAML + "golang" -> YAML else -> null } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/Markdown.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/Markdown.kt index 9537d15df..e42195c24 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/Markdown.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/Markdown.kt @@ -8,26 +8,23 @@ import org.jetbrains.jewel.markdown.processing.MarkdownProcessor import org.jetbrains.jewel.markdown.rendering.MarkdownBlockRenderer import org.jetbrains.jewel.markdown.rendering.MarkdownStyling -public val LocalMarkdownStyling: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No MarkdownStyling defined, have you forgotten to provide it?") - } +public val LocalMarkdownStyling: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No MarkdownStyling defined, have you forgotten to provide it?") +} public val JewelTheme.Companion.markdownStyling: MarkdownStyling @Composable get() = LocalMarkdownStyling.current -public val LocalMarkdownProcessor: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No MarkdownProcessor defined, have you forgotten to provide it?") - } +public val LocalMarkdownProcessor: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No MarkdownProcessor defined, have you forgotten to provide it?") +} public val JewelTheme.Companion.markdownProcessor: MarkdownProcessor @Composable get() = LocalMarkdownProcessor.current -public val LocalMarkdownBlockRenderer: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No MarkdownBlockRenderer defined, have you forgotten to provide it?") - } +public val LocalMarkdownBlockRenderer: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No MarkdownBlockRenderer defined, have you forgotten to provide it?") +} public val JewelTheme.Companion.markdownBlockRenderer: MarkdownBlockRenderer @Composable get() = LocalMarkdownBlockRenderer.current diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockProcessorExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockProcessorExtension.kt index 75c81711e..9ffdbf924 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockProcessorExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockProcessorExtension.kt @@ -13,13 +13,9 @@ public interface MarkdownBlockProcessorExtension { public fun canProcess(block: CustomBlock): Boolean /** - * Processes the [block] as a [MarkdownBlock.CustomBlock], if possible. Note - * that you should always check that [canProcess] returns true for the same - * [block], as implementations might throw an exception for unsupported - * block types. + * Processes the [block] as a [MarkdownBlock.CustomBlock], if possible. Note that you should always check that + * [canProcess] returns true for the same [block], as implementations might throw an exception for unsupported block + * types. */ - public fun processMarkdownBlock( - block: CustomBlock, - processor: MarkdownProcessor, - ): MarkdownBlock.CustomBlock? + public fun processMarkdownBlock(block: CustomBlock, processor: MarkdownProcessor): MarkdownBlock.CustomBlock? } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockRendererExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockRendererExtension.kt index e037e9bdb..4ce722a3a 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockRendererExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownBlockRendererExtension.kt @@ -6,17 +6,14 @@ import org.jetbrains.jewel.markdown.MarkdownBlock.CustomBlock import org.jetbrains.jewel.markdown.rendering.InlineMarkdownRenderer import org.jetbrains.jewel.markdown.rendering.MarkdownBlockRenderer -/** - * An extension for [MarkdownBlockRenderer] that can render one or more - * [MarkdownBlock.CustomBlock]s. - */ +/** An extension for [MarkdownBlockRenderer] that can render one or more [MarkdownBlock.CustomBlock]s. */ public interface MarkdownBlockRendererExtension { /** Check whether the provided [block] can be rendered by this extension. */ public fun canRender(block: CustomBlock): Boolean /** - * Render a [MarkdownBlock.CustomBlock] as a native Composable. Note that if - * [canRender] returns `false` for [block], the implementation might throw. + * Render a [MarkdownBlock.CustomBlock] as a native Composable. Note that if [canRender] returns `false` for + * [block], the implementation might throw. */ @Composable public fun render( diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineProcessorExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineProcessorExtension.kt index d9600fef0..658671044 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineProcessorExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineProcessorExtension.kt @@ -13,13 +13,9 @@ public interface MarkdownInlineProcessorExtension { public fun canProcess(node: CustomNode): Boolean /** - * Processes the [node] as a [InlineMarkdown.CustomNode], if possible. Note - * that you should always check that [canProcess] returns true for the same - * [node], as implementations might throw an exception for unsupported node + * Processes the [node] as a [InlineMarkdown.CustomNode], if possible. Note that you should always check that + * [canProcess] returns true for the same [node], as implementations might throw an exception for unsupported node * types. */ - public fun processInlineMarkdown( - node: CustomNode, - processor: MarkdownProcessor, - ): InlineMarkdown.CustomNode? + public fun processInlineMarkdown(node: CustomNode, processor: MarkdownProcessor): InlineMarkdown.CustomNode? } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineRendererExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineRendererExtension.kt index 1b7e7de90..723d0a2c0 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineRendererExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownInlineRendererExtension.kt @@ -4,21 +4,14 @@ import org.jetbrains.jewel.markdown.InlineMarkdown import org.jetbrains.jewel.markdown.InlineMarkdown.CustomNode import org.jetbrains.jewel.markdown.rendering.InlineMarkdownRenderer -/** - * An extension for [InlineMarkdownRenderer] that can render one or more - * [InlineMarkdown.CustomNode]s. - */ +/** An extension for [InlineMarkdownRenderer] that can render one or more [InlineMarkdown.CustomNode]s. */ public interface MarkdownInlineRendererExtension { /** Check whether the provided [inline] can be rendered by this extension. */ public fun canRender(inline: CustomNode): Boolean /** - * Render a [CustomNode] as an annotated string. Note that if - * [canRender] returns `false` for [inline], the implementation might throw. + * Render a [CustomNode] as an annotated string. Note that if [canRender] returns `false` for [inline], the + * implementation might throw. */ - public fun render( - inline: CustomNode, - inlineRenderer: InlineMarkdownRenderer, - enabled: Boolean, - ) + public fun render(inline: CustomNode, inlineRenderer: InlineMarkdownRenderer, enabled: Boolean) } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownProcessorExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownProcessorExtension.kt index 81f70e8ad..231db7e6b 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownProcessorExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownProcessorExtension.kt @@ -8,31 +8,26 @@ import org.jetbrains.jewel.foundation.ExperimentalJewelApi @ExperimentalJewelApi public interface MarkdownProcessorExtension { /** - * A CommonMark [ParserExtension] that will be used to parse the extended - * syntax represented by this extension instance. + * A CommonMark [ParserExtension] that will be used to parse the extended syntax represented by this extension + * instance. * - * Can be null if all required processing is already handled by an existing - * [org.commonmark.parser.Parser]. + * Can be null if all required processing is already handled by an existing [org.commonmark.parser.Parser]. */ public val parserExtension: ParserExtension? get() = null /** - * A CommonMark [TextContentRendererExtension] that will be used to render - * the text content of the CommonMark [org.commonmark.node.CustomBlock] - * produced by the [parserExtension]. + * A CommonMark [TextContentRendererExtension] that will be used to render the text content of the CommonMark + * [org.commonmark.node.CustomBlock] produced by the [parserExtension]. * - * Can be null if all required processing is already handled by an existing - * [org.commonmark.renderer.Renderer]. + * Can be null if all required processing is already handled by an existing [org.commonmark.renderer.Renderer]. */ public val textRendererExtension: TextContentRendererExtension? get() = null /** - * An extension for - * [`MarkdownProcessor`][org.jetbrains.jewel.markdown.processing.MarkdownProcessor] - * that will transform a supported [org.commonmark.node.CustomBlock] into - * the corresponding + * An extension for [`MarkdownProcessor`][org.jetbrains.jewel.markdown.processing.MarkdownProcessor] that will + * transform a supported [org.commonmark.node.CustomBlock] into the corresponding * [org.jetbrains.jewel.markdown.MarkdownBlock.CustomBlock]. * * Can be null if all required processing is already handled by @@ -43,10 +38,8 @@ public interface MarkdownProcessorExtension { get() = null /** - * An extension for - * [`MarkdownProcessor`][org.jetbrains.jewel.markdown.processing.MarkdownProcessor] - * that will transform a supported [org.commonmark.node.CustomNode] into - * the corresponding + * An extension for [`MarkdownProcessor`][org.jetbrains.jewel.markdown.processing.MarkdownProcessor] that will + * transform a supported [org.commonmark.node.CustomNode] into the corresponding * [org.jetbrains.jewel.markdown.InlineMarkdown.CustomNode]. * * Can be null if all required processing is already handled by diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownRendererExtension.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownRendererExtension.kt index 4da685756..82f1199bd 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownRendererExtension.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/MarkdownRendererExtension.kt @@ -6,11 +6,9 @@ import org.jetbrains.jewel.foundation.ExperimentalJewelApi @ExperimentalJewelApi public interface MarkdownRendererExtension { /** - * An extension for - * [`MarkdownBlockRenderer`][org.jetbrains.jewel.markdown.rendering.MarkdownBlockRenderer] - * that will render a supported - * [`CustomBlock`][org.jetbrains.jewel.markdown.MarkdownBlock.CustomBlock] into - * a native Jewel UI. + * An extension for [`MarkdownBlockRenderer`][org.jetbrains.jewel.markdown.rendering.MarkdownBlockRenderer] that + * will render a supported [`CustomBlock`][org.jetbrains.jewel.markdown.MarkdownBlock.CustomBlock] into a native + * Jewel UI. * * Can be null if this extension doesn't support rendering blocks. */ @@ -18,11 +16,9 @@ public interface MarkdownRendererExtension { get() = null /** - * An extension for - * [`InlineMarkdownRenderer`][org.jetbrains.jewel.markdown.rendering.InlineMarkdownRenderer] - * that will render a supported - * [`CustomNode`][org.jetbrains.jewel.markdown.InlineMarkdown.CustomNode] into - * an annotated string. + * An extension for [`InlineMarkdownRenderer`][org.jetbrains.jewel.markdown.rendering.InlineMarkdownRenderer] that + * will render a supported [`CustomNode`][org.jetbrains.jewel.markdown.InlineMarkdown.CustomNode] into an annotated + * string. * * Can be null if this extension doesn't support rendering inline nodes. */ diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownParserFactory.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownParserFactory.kt index e4abc9c84..645a6b65f 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownParserFactory.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownParserFactory.kt @@ -5,25 +5,21 @@ import org.commonmark.parser.Parser import org.jetbrains.jewel.markdown.extensions.MarkdownProcessorExtension /** - * Simplifies creating a [CommonMark `Parser`][Parser] while also - * supporting Jewel's [MarkdownProcessorExtension]s and the `optimizeEdits` - * flag. + * Simplifies creating a [CommonMark `Parser`][Parser] while also supporting Jewel's [MarkdownProcessorExtension]s and + * the `optimizeEdits` flag. */ public object MarkdownParserFactory { /** - * Create a [CommonMark `Parser`][Parser] with the provided [extensions]. - * The parser's [Builder][Parser.Builder] can be customized by providing a - * non-null [customizeBuilder] lambda. + * Create a [CommonMark `Parser`][Parser] with the provided [extensions]. The parser's [Builder][Parser.Builder] can + * be customized by providing a non-null [customizeBuilder] lambda. * - * Make sure to provide the right value for [optimizeEdits], matching the - * one provided to the [MarkdownProcessor], or this parser will not be set - * up correctly. + * Make sure to provide the right value for [optimizeEdits], matching the one provided to the [MarkdownProcessor], + * or this parser will not be set up correctly. * - * @param optimizeEdits If true, sets up the [Parser] to allow for edits - * optimization in the [MarkdownProcessor]. + * @param optimizeEdits If true, sets up the [Parser] to allow for edits optimization in the [MarkdownProcessor]. * @param extensions A list of [MarkdownProcessorExtension] to attach. - * @param customizeBuilder Allows customizing the [Parser.Builder] before - * its [build()][Parser.Builder.build] method is called. + * @param customizeBuilder Allows customizing the [Parser.Builder] before its [build()][Parser.Builder.build] method + * is called. */ public fun create( optimizeEdits: Boolean, diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessor.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessor.kt index 3b41bb0ba..7d55fe612 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessor.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessor.kt @@ -9,6 +9,7 @@ import org.commonmark.node.FencedCodeBlock import org.commonmark.node.Heading import org.commonmark.node.HtmlBlock import org.commonmark.node.IndentedCodeBlock +import org.commonmark.node.ListBlock as CMListBlock import org.commonmark.node.ListItem import org.commonmark.node.Node import org.commonmark.node.OrderedList @@ -27,35 +28,27 @@ import org.jetbrains.jewel.markdown.MarkdownBlock.ListBlock import org.jetbrains.jewel.markdown.MimeType import org.jetbrains.jewel.markdown.extensions.MarkdownProcessorExtension import org.jetbrains.jewel.markdown.rendering.DefaultInlineMarkdownRenderer -import org.commonmark.node.ListBlock as CMListBlock /** - * Reads raw Markdown strings and processes them into a list of - * [MarkdownBlock]. + * Reads raw Markdown strings and processes them into a list of [MarkdownBlock]. * - * @param extensions Extensions to use when processing the Markdown (e.g., - * to support parsing custom block-level Markdown). - * @param editorMode Indicates whether the processor should be optimized - * for an editor/preview scenario, where it assumes small incremental - * changes as performed by a user typing. This means it will only update - * the changed blocks by keeping state in memory. + * @param extensions Extensions to use when processing the Markdown (e.g., to support parsing custom block-level + * Markdown). + * @param editorMode Indicates whether the processor should be optimized for an editor/preview scenario, where it + * assumes small incremental changes as performed by a user typing. This means it will only update the changed blocks + * by keeping state in memory. * - * Default is `false`; set this to `true` if this parser will be used in - * an editor scenario, where the raw Markdown is only ever going to - * change slightly but frequently (e.g., as the user types). + * Default is `false`; set this to `true` if this parser will be used in an editor scenario, where the raw Markdown is + * only ever going to change slightly but frequently (e.g., as the user types). * - * **Attention:** do **not** reuse or share an instance of - * [MarkdownProcessor] that is in [editorMode]. Processing entirely - * different Markdown strings will defeat the purpose of the - * optimization. When in editor mode, the instance of - * [MarkdownProcessor] is **not** thread-safe! + * **Attention:** do **not** reuse or share an instance of [MarkdownProcessor] that is in [editorMode]. Processing + * entirely different Markdown strings will defeat the purpose of the optimization. When in editor mode, the instance + * of [MarkdownProcessor] is **not** thread-safe! * - * @param commonMarkParser The CommonMark [Parser] used to parse the - * Markdown. By default it's a vanilla instance provided by the - * [MarkdownParserFactory], but you can provide your own if you need to - * customize the parser — e.g., to ignore certain tags. If - * [optimizeEdits] is `true`, make sure you set - * `includeSourceSpans(IncludeSourceSpans.BLOCKS)` on the parser. + * @param commonMarkParser The CommonMark [Parser] used to parse the Markdown. By default it's a vanilla instance + * provided by the [MarkdownParserFactory], but you can provide your own if you need to customize the parser — e.g., + * to ignore certain tags. If [optimizeEdits] is `true`, make sure you set + * `includeSourceSpans(IncludeSourceSpans.BLOCKS)` on the parser. */ @ExperimentalJewelApi public class MarkdownProcessor( @@ -65,22 +58,17 @@ public class MarkdownProcessor( ) { private var currentState = State(emptyList(), emptyList(), emptyList()) - @TestOnly - internal fun getCurrentIndexesInTest() = currentState.indexes + @TestOnly internal fun getCurrentIndexesInTest() = currentState.indexes /** - * Parses a Markdown document, translating from CommonMark - * 0.31.2 to a list of [MarkdownBlock]. Inline Markdown in leaf - * nodes is contained in [InlineMarkdown], which can be rendered - * to an [androidx.compose.ui.text.AnnotatedString] by using - * [DefaultInlineMarkdownRenderer.renderAsAnnotatedString]. + * Parses a Markdown document, translating from CommonMark 0.31.2 to a list of [MarkdownBlock]. Inline Markdown in + * leaf nodes is contained in [InlineMarkdown], which can be rendered to an + * [androidx.compose.ui.text.AnnotatedString] by using [DefaultInlineMarkdownRenderer.renderAsAnnotatedString]. * * @param rawMarkdown the raw Markdown string to process. * @see DefaultInlineMarkdownRenderer */ - public fun processMarkdownDocument( - @Language("Markdown") rawMarkdown: String, - ): List { + public fun processMarkdownDocument(@Language("Markdown") rawMarkdown: String): List { val blocks = if (editorMode) { processWithQuickEdits(rawMarkdown) @@ -92,9 +80,7 @@ public class MarkdownProcessor( } @VisibleForTesting - internal fun processWithQuickEdits( - @Language("Markdown") rawMarkdown: String, - ): List { + internal fun processWithQuickEdits(@Language("Markdown") rawMarkdown: String): List { val (previousLines, previousBlocks, previousIndexes) = currentState val newLines = rawMarkdown.lines() val nLinesDelta = newLines.size - previousLines.size @@ -173,16 +159,11 @@ public class MarkdownProcessor( return newBlocks } - private fun parseRawMarkdown( - @Language("Markdown") rawMarkdown: String, - ): List { + private fun parseRawMarkdown(@Language("Markdown") rawMarkdown: String): List { val document = - commonMarkParser.parse(rawMarkdown) as? Document - ?: error("This doesn't look like a Markdown document") + commonMarkParser.parse(rawMarkdown) as? Document ?: error("This doesn't look like a Markdown document") - return buildList { - document.forEachChild { child -> if (child is Block) add(child) } - } + return buildList { document.forEachChild { child -> if (child is Block) add(child) } } } private fun Node.tryProcessMarkdownBlock(): MarkdownBlock? = @@ -198,23 +179,24 @@ public class MarkdownProcessor( is ThematicBreak -> MarkdownBlock.ThematicBreak is HtmlBlock -> toMarkdownHtmlBlockOrNull() is CustomBlock -> { - extensions.find { it.blockProcessorExtension?.canProcess(this) == true } - ?.blockProcessorExtension?.processMarkdownBlock(this, this@MarkdownProcessor) + extensions + .find { it.blockProcessorExtension?.canProcess(this) == true } + ?.blockProcessorExtension + ?.processMarkdownBlock(this, this@MarkdownProcessor) } else -> null } - private fun Paragraph.toMarkdownParagraph(): MarkdownBlock.Paragraph = MarkdownBlock.Paragraph(readInlineContent().toList()) + private fun Paragraph.toMarkdownParagraph(): MarkdownBlock.Paragraph = + MarkdownBlock.Paragraph(readInlineContent().toList()) - private fun BlockQuote.toMarkdownBlockQuote(): MarkdownBlock.BlockQuote = MarkdownBlock.BlockQuote(processChildren(this)) + private fun BlockQuote.toMarkdownBlockQuote(): MarkdownBlock.BlockQuote = + MarkdownBlock.BlockQuote(processChildren(this)) private fun Heading.toMarkdownHeadingOrNull(): MarkdownBlock.Heading? { if (level < 1 || level > 6) return null - return MarkdownBlock.Heading( - inlineContent = readInlineContent().toList(), - level = level, - ) + return MarkdownBlock.Heading(inlineContent = readInlineContent().toList(), level = level) } private fun FencedCodeBlock.toMarkdownCodeBlockOrNull(): CodeBlock.FencedCodeBlock = @@ -223,17 +205,14 @@ public class MarkdownProcessor( mimeType = MimeType.Known.fromMarkdownLanguageName(info), ) - private fun IndentedCodeBlock.toMarkdownCodeBlockOrNull(): CodeBlock.IndentedCodeBlock = CodeBlock.IndentedCodeBlock(literal.trimEnd('\n')) + private fun IndentedCodeBlock.toMarkdownCodeBlockOrNull(): CodeBlock.IndentedCodeBlock = + CodeBlock.IndentedCodeBlock(literal.trimEnd('\n')) private fun BulletList.toMarkdownListOrNull(): ListBlock.UnorderedList? { val children = processListItems() if (children.isEmpty()) return null - return ListBlock.UnorderedList( - children = children, - isTight = isTight, - marker = marker, - ) + return ListBlock.UnorderedList(children = children, isTight = isTight, marker = marker) } private fun OrderedList.toMarkdownListOrNull(): ListBlock.OrderedList? { @@ -248,29 +227,26 @@ public class MarkdownProcessor( ) } - private fun CMListBlock.processListItems() = - buildList { - forEachChild { child -> - if (child !is ListItem) return@forEachChild - add(MarkdownBlock.ListItem(processChildren(child))) - } + private fun CMListBlock.processListItems() = buildList { + forEachChild { child -> + if (child !is ListItem) return@forEachChild + add(MarkdownBlock.ListItem(processChildren(child))) } + } /** - * Processes the children of a CommonMark [Node]. This function is public - * so that it can be accessed from [MarkdownProcessorExtension]s, but - * should not be used in other scenarios. + * Processes the children of a CommonMark [Node]. This function is public so that it can be accessed from + * [MarkdownProcessorExtension]s, but should not be used in other scenarios. */ @InternalJewelApi - public fun processChildren(node: Node): List = - buildList { - node.forEachChild { child -> - val parsedBlock = child.tryProcessMarkdownBlock() - if (parsedBlock != null) { - add(parsedBlock) - } + public fun processChildren(node: Node): List = buildList { + node.forEachChild { child -> + val parsedBlock = child.tryProcessMarkdownBlock() + if (parsedBlock != null) { + add(parsedBlock) } } + } private fun Node.forEachChild(action: (Node) -> Unit) { var child = firstChild diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/ProcessingUtil.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/ProcessingUtil.kt index bb5c95b31..88df689b5 100644 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/ProcessingUtil.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/processing/ProcessingUtil.kt @@ -1,11 +1,5 @@ package org.jetbrains.jewel.markdown.processing -import org.commonmark.node.Node -import org.jetbrains.annotations.VisibleForTesting -import org.jetbrains.jewel.markdown.InlineMarkdown -import org.jetbrains.jewel.markdown.WithInlineMarkdown -import org.jetbrains.jewel.markdown.WithTextContent -import org.jetbrains.jewel.markdown.extensions.MarkdownProcessorExtension import org.commonmark.node.Code as CMCode import org.commonmark.node.CustomNode as CMCustomNode import org.commonmark.node.Emphasis as CMEmphasis @@ -13,9 +7,15 @@ import org.commonmark.node.HardLineBreak as CMHardLineBreak import org.commonmark.node.HtmlInline as CMHtmlInline import org.commonmark.node.Image as CMImage import org.commonmark.node.Link as CMLink +import org.commonmark.node.Node import org.commonmark.node.SoftLineBreak as CMSoftLineBreak import org.commonmark.node.StrongEmphasis as CMStrongEmphasis import org.commonmark.node.Text as CMText +import org.jetbrains.annotations.VisibleForTesting +import org.jetbrains.jewel.markdown.InlineMarkdown +import org.jetbrains.jewel.markdown.WithInlineMarkdown +import org.jetbrains.jewel.markdown.WithTextContent +import org.jetbrains.jewel.markdown.extensions.MarkdownProcessorExtension @VisibleForTesting internal fun Node.readInlineContent( @@ -23,100 +23,97 @@ internal fun Node.readInlineContent( extensions: List, ): List = object : Iterable { - override fun iterator(): Iterator = - object : Iterator { - var current = this@readInlineContent.firstChild + override fun iterator(): Iterator = + object : Iterator { + var current = this@readInlineContent.firstChild - override fun hasNext(): Boolean = current != null + override fun hasNext(): Boolean = current != null - override fun next(): InlineMarkdown { - while (hasNext()) { - val inline = current.toInlineMarkdownOrNull(markdownProcessor, extensions) + override fun next(): InlineMarkdown { + while (hasNext()) { + val inline = current.toInlineMarkdownOrNull(markdownProcessor, extensions) - current = current.next + current = current.next - if (inline == null) { - continue - } else { - return inline + if (inline == null) { + continue + } else { + return inline + } } - } - throw NoSuchElementException() + throw NoSuchElementException() + } } - } - }.toList() + } + .toList() @VisibleForTesting internal fun Node.toInlineMarkdownOrNull( markdownProcessor: MarkdownProcessor, extensions: List, -) = when (this) { - is CMText -> InlineMarkdown.Text(literal) - is CMLink -> - InlineMarkdown.Link( - destination = destination, - title = title, - inlineContent = readInlineContent(markdownProcessor, extensions), - ) - - is CMEmphasis -> - InlineMarkdown.Emphasis( - delimiter = openingDelimiter, - inlineContent = readInlineContent(markdownProcessor, extensions), - ) - - is CMStrongEmphasis -> - InlineMarkdown.StrongEmphasis( - openingDelimiter, - readInlineContent(markdownProcessor, extensions), - ) - - is CMCode -> InlineMarkdown.Code(literal) - is CMHtmlInline -> InlineMarkdown.HtmlInline(literal) - is CMImage -> { - val inlineContent = readInlineContent(markdownProcessor, extensions) - InlineMarkdown.Image( - source = destination, - alt = inlineContent.renderAsSimpleText().trim(), - title = title, - inlineContent = inlineContent, - ) - } +) = + when (this) { + is CMText -> InlineMarkdown.Text(literal) + is CMLink -> + InlineMarkdown.Link( + destination = destination, + title = title, + inlineContent = readInlineContent(markdownProcessor, extensions), + ) + + is CMEmphasis -> + InlineMarkdown.Emphasis( + delimiter = openingDelimiter, + inlineContent = readInlineContent(markdownProcessor, extensions), + ) + + is CMStrongEmphasis -> + InlineMarkdown.StrongEmphasis(openingDelimiter, readInlineContent(markdownProcessor, extensions)) + + is CMCode -> InlineMarkdown.Code(literal) + is CMHtmlInline -> InlineMarkdown.HtmlInline(literal) + is CMImage -> { + val inlineContent = readInlineContent(markdownProcessor, extensions) + InlineMarkdown.Image( + source = destination, + alt = inlineContent.renderAsSimpleText().trim(), + title = title, + inlineContent = inlineContent, + ) + } - is CMHardLineBreak -> InlineMarkdown.HardLineBreak - is CMSoftLineBreak -> InlineMarkdown.SoftLineBreak - is CMCustomNode -> - extensions.find { it.inlineProcessorExtension?.canProcess(this) == true } - ?.inlineProcessorExtension?.processInlineMarkdown(this, markdownProcessor) + is CMHardLineBreak -> InlineMarkdown.HardLineBreak + is CMSoftLineBreak -> InlineMarkdown.SoftLineBreak + is CMCustomNode -> + extensions + .find { it.inlineProcessorExtension?.canProcess(this) == true } + ?.inlineProcessorExtension + ?.processInlineMarkdown(this, markdownProcessor) - else -> error("Unexpected block $this") -} + else -> error("Unexpected block $this") + } -/** - * Used to render content as simple plain text, used when creating image - * alt text. - */ -internal fun List.renderAsSimpleText(): String = - buildString { - for (node in this@renderAsSimpleText) { - when (node) { - is WithInlineMarkdown -> append(node.inlineContent.renderAsSimpleText()) - is WithTextContent -> append(node.content) - - is InlineMarkdown.CustomNode -> { - val textContent = node.contentOrNull() - if (textContent != null) { - append(' ') - append(textContent) - } +/** Used to render content as simple plain text, used when creating image alt text. */ +internal fun List.renderAsSimpleText(): String = buildString { + for (node in this@renderAsSimpleText) { + when (node) { + is WithInlineMarkdown -> append(node.inlineContent.renderAsSimpleText()) + is WithTextContent -> append(node.content) + + is InlineMarkdown.CustomNode -> { + val textContent = node.contentOrNull() + if (textContent != null) { + append(' ') + append(textContent) } + } - is InlineMarkdown.HardLineBreak -> append('\n') - is InlineMarkdown.SoftLineBreak -> append(' ') - else -> { - // Ignore other nodes - } + is InlineMarkdown.HardLineBreak -> append('\n') + is InlineMarkdown.SoftLineBreak -> append(' ') + else -> { + // Ignore other nodes } } } +} diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultInlineMarkdownRenderer.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultInlineMarkdownRenderer.kt index 3aa840207..60fc29271 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultInlineMarkdownRenderer.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultInlineMarkdownRenderer.kt @@ -12,18 +12,16 @@ import org.jetbrains.jewel.markdown.InlineMarkdown import org.jetbrains.jewel.markdown.extensions.MarkdownRendererExtension @ExperimentalJewelApi -public open class DefaultInlineMarkdownRenderer( - private val rendererExtensions: List, -) : InlineMarkdownRenderer { +public open class DefaultInlineMarkdownRenderer(private val rendererExtensions: List) : + InlineMarkdownRenderer { public override fun renderAsAnnotatedString( inlineMarkdown: Iterable, styling: InlinesStyling, enabled: Boolean, onUrlClicked: ((String) -> Unit)?, - ): AnnotatedString = - buildAnnotatedString { - appendInlineMarkdownFrom(inlineMarkdown, styling, enabled, onUrlClicked) - } + ): AnnotatedString = buildAnnotatedString { + appendInlineMarkdownFrom(inlineMarkdown, styling, enabled, onUrlClicked) + } private fun Builder.appendInlineMarkdownFrom( inlineMarkdown: Iterable, @@ -37,11 +35,7 @@ public open class DefaultInlineMarkdownRenderer( is InlineMarkdown.Emphasis -> { withStyles(styling.emphasis.withEnabled(enabled), child) { - appendInlineMarkdownFrom( - it.inlineContent, - styling, - enabled, - ) + appendInlineMarkdownFrom(it.inlineContent, styling, enabled) } } @@ -70,9 +64,7 @@ public open class DefaultInlineMarkdownRenderer( } is InlineMarkdown.Code -> { - withStyles(styling.inlineCode.withEnabled(enabled), child) { - append(it.content) - } + withStyles(styling.inlineCode.withEnabled(enabled), child) { append(it.content) } } is InlineMarkdown.HardLineBreak -> appendLine() @@ -80,10 +72,7 @@ public open class DefaultInlineMarkdownRenderer( is InlineMarkdown.HtmlInline -> { if (styling.renderInlineHtml) { - withStyles( - styling.inlineHtml.withEnabled(enabled), - child, - ) { append(it.content.trim()) } + withStyles(styling.inlineHtml.withEnabled(enabled), child) { append(it.content.trim()) } } } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultMarkdownBlockRenderer.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultMarkdownBlockRenderer.kt index ebce59c67..6f293b91f 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultMarkdownBlockRenderer.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/DefaultMarkdownBlockRenderer.kt @@ -78,12 +78,7 @@ public open class DefaultMarkdownBlockRenderer( } @Composable - override fun render( - block: MarkdownBlock, - enabled: Boolean, - onUrlClick: (String) -> Unit, - onTextClick: () -> Unit, - ) { + override fun render(block: MarkdownBlock, enabled: Boolean, onUrlClick: (String) -> Unit, onTextClick: () -> Unit) { when (block) { is BlockQuote -> render(block, rootStyling.blockQuote, enabled, onUrlClick, onTextClick) is FencedCodeBlock -> render(block, rootStyling.code.fenced) @@ -198,19 +193,19 @@ public open class DefaultMarkdownBlockRenderer( ) { Column( Modifier.drawBehind { - val isLtr = layoutDirection == Ltr - val lineWidthPx = styling.lineWidth.toPx() - val x = if (isLtr) lineWidthPx / 2 else size.width - lineWidthPx / 2 + val isLtr = layoutDirection == Ltr + val lineWidthPx = styling.lineWidth.toPx() + val x = if (isLtr) lineWidthPx / 2 else size.width - lineWidthPx / 2 - drawLine( - styling.lineColor, - Offset(x, 0f), - Offset(x, size.height), - lineWidthPx, - styling.strokeCap, - styling.pathEffect, - ) - } + drawLine( + styling.lineColor, + Offset(x, 0f), + Offset(x, size.height), + lineWidthPx, + styling.strokeCap, + styling.pathEffect, + ) + } .padding(styling.padding), verticalArrangement = Arrangement.spacedBy(rootStyling.blockVerticalSpacing), ) { @@ -308,22 +303,14 @@ public open class DefaultMarkdownBlockRenderer( } @Composable - override fun render( - block: ListItem, - enabled: Boolean, - onUrlClick: (String) -> Unit, - onTextClick: () -> Unit, - ) { + override fun render(block: ListItem, enabled: Boolean, onUrlClick: (String) -> Unit, onTextClick: () -> Unit) { Column(verticalArrangement = Arrangement.spacedBy(rootStyling.blockVerticalSpacing)) { render(block.children, enabled, onUrlClick, onTextClick) } } @Composable - override fun render( - block: CodeBlock, - styling: MarkdownStyling.Code, - ) { + override fun render(block: CodeBlock, styling: MarkdownStyling.Code) { when (block) { is FencedCodeBlock -> render(block, styling.fenced) is IndentedCodeBlock -> render(block, styling.indented) @@ -331,10 +318,7 @@ public open class DefaultMarkdownBlockRenderer( } @Composable - override fun render( - block: IndentedCodeBlock, - styling: MarkdownStyling.Code.Indented, - ) { + override fun render(block: IndentedCodeBlock, styling: MarkdownStyling.Code.Indented) { MaybeScrollingContainer( isScrollable = styling.scrollsHorizontally, Modifier.background(styling.background, styling.shape) @@ -354,10 +338,7 @@ public open class DefaultMarkdownBlockRenderer( } @Composable - override fun render( - block: FencedCodeBlock, - styling: MarkdownStyling.Code.Fenced, - ) { + override fun render(block: FencedCodeBlock, styling: MarkdownStyling.Code.Fenced) { MaybeScrollingContainer( isScrollable = styling.scrollsHorizontally, Modifier.background(styling.background, styling.shape) @@ -422,10 +403,7 @@ public open class DefaultMarkdownBlockRenderer( } @Composable - override fun render( - block: HtmlBlock, - styling: MarkdownStyling.HtmlBlock, - ) { + override fun render(block: HtmlBlock, styling: MarkdownStyling.HtmlBlock) { // HTML blocks are intentionally not rendered } @@ -435,9 +413,10 @@ public open class DefaultMarkdownBlockRenderer( styling: InlinesStyling, enabled: Boolean, onUrlClick: ((String) -> Unit)? = null, - ) = remember(block.inlineContent, styling, enabled) { - inlineRenderer.renderAsAnnotatedString(block.inlineContent, styling, enabled, onUrlClick) - } + ) = + remember(block.inlineContent, styling, enabled) { + inlineRenderer.renderAsAnnotatedString(block.inlineContent, styling, enabled, onUrlClick) + } @Composable private fun MaybeScrollingContainer( diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/InlineMarkdownRenderer.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/InlineMarkdownRenderer.kt index 73fea2efe..c46312278 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/InlineMarkdownRenderer.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/InlineMarkdownRenderer.kt @@ -6,10 +6,7 @@ import org.jetbrains.jewel.markdown.InlineMarkdown @ExperimentalJewelApi public interface InlineMarkdownRenderer { - /** - * Render the [inlineMarkdown] as an [AnnotatedString], using the [styling] - * provided. - */ + /** Render the [inlineMarkdown] as an [AnnotatedString], using the [styling] provided. */ public fun renderAsAnnotatedString( inlineMarkdown: Iterable, styling: InlinesStyling, diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownBlockRenderer.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownBlockRenderer.kt index f91a28e93..b66ebc497 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownBlockRenderer.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownBlockRenderer.kt @@ -25,12 +25,7 @@ public interface MarkdownBlockRenderer { ) @Composable - public fun render( - block: MarkdownBlock, - enabled: Boolean, - onUrlClick: (String) -> Unit, - onTextClick: () -> Unit, - ) + public fun render(block: MarkdownBlock, enabled: Boolean, onUrlClick: (String) -> Unit, onTextClick: () -> Unit) @Composable public fun render( @@ -96,39 +91,17 @@ public interface MarkdownBlockRenderer { ) @Composable - public fun render( - block: ListItem, - enabled: Boolean, - onUrlClick: (String) -> Unit, - onTextClick: () -> Unit, - ) + public fun render(block: ListItem, enabled: Boolean, onUrlClick: (String) -> Unit, onTextClick: () -> Unit) - @Composable - public fun render( - block: CodeBlock, - styling: MarkdownStyling.Code, - ) + @Composable public fun render(block: CodeBlock, styling: MarkdownStyling.Code) - @Composable - public fun render( - block: IndentedCodeBlock, - styling: MarkdownStyling.Code.Indented, - ) + @Composable public fun render(block: IndentedCodeBlock, styling: MarkdownStyling.Code.Indented) - @Composable - public fun render( - block: FencedCodeBlock, - styling: MarkdownStyling.Code.Fenced, - ) + @Composable public fun render(block: FencedCodeBlock, styling: MarkdownStyling.Code.Fenced) - @Composable - public fun renderThematicBreak(styling: MarkdownStyling.ThematicBreak) + @Composable public fun renderThematicBreak(styling: MarkdownStyling.ThematicBreak) - @Composable - public fun render( - block: HtmlBlock, - styling: MarkdownStyling.HtmlBlock, - ) + @Composable public fun render(block: HtmlBlock, styling: MarkdownStyling.HtmlBlock) public companion object } diff --git a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownStyling.kt b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownStyling.kt index b04464f4b..419c79223 100755 --- a/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownStyling.kt +++ b/markdown/core/src/main/kotlin/org/jetbrains/jewel/markdown/rendering/MarkdownStyling.kt @@ -35,9 +35,7 @@ public class MarkdownStyling( public val htmlBlock: HtmlBlock, ) { @GenerateDataFunctions - public class Paragraph( - override val inlinesStyling: InlinesStyling, - ) : WithInlinesStyling { + public class Paragraph(override val inlinesStyling: InlinesStyling) : WithInlinesStyling { public companion object } @@ -136,10 +134,7 @@ public class MarkdownStyling( } @GenerateDataFunctions - public class List( - public val ordered: Ordered, - public val unordered: Unordered, - ) { + public class List(public val ordered: Ordered, public val unordered: Unordered) { @GenerateDataFunctions public class Ordered( public val numberStyle: TextStyle, @@ -169,10 +164,7 @@ public class MarkdownStyling( } @GenerateDataFunctions - public class Code( - public val indented: Indented, - public val fenced: Fenced, - ) { + public class Code(public val indented: Indented, public val fenced: Fenced) { @GenerateDataFunctions public class Indented( public val editorTextStyle: TextStyle, @@ -281,12 +273,7 @@ public class InlinesStyling( public val renderInlineHtml: Boolean, ) { public val textLinkStyles: TextLinkStyles = - TextLinkStyles( - style = link, - focusedStyle = linkFocused, - hoveredStyle = linkHovered, - pressedStyle = linkPressed, - ) + TextLinkStyles(style = link, focusedStyle = linkFocused, hoveredStyle = linkHovered, pressedStyle = linkPressed) public companion object } @@ -296,13 +283,11 @@ internal val InfoPosition.verticalAlignment when (this) { TopStart, TopCenter, - TopEnd, - -> Alignment.Top + TopEnd -> Alignment.Top BottomStart, BottomCenter, - BottomEnd, - -> Alignment.Bottom + BottomEnd -> Alignment.Bottom Hide -> null } @@ -311,16 +296,13 @@ internal val InfoPosition.horizontalAlignment get() = when (this) { TopStart, - BottomStart, - -> Alignment.Start + BottomStart -> Alignment.Start TopCenter, - BottomCenter, - -> Alignment.CenterHorizontally + BottomCenter -> Alignment.CenterHorizontally TopEnd, - BottomEnd, - -> Alignment.End + BottomEnd -> Alignment.End Hide -> null } diff --git a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingExtraTest.kt b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingExtraTest.kt index 8e2a89336..66bec45a1 100755 --- a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingExtraTest.kt +++ b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingExtraTest.kt @@ -30,18 +30,7 @@ class MarkdownProcessorDocumentParsingExtraTest { * Expected HTML: *

foo bar

*/ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Emphasis( - "_", - Text("foo "), - Emphasis("*", Text("bar")), - ), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Emphasis("_", Text("foo "), Emphasis("*", Text("bar")))))) } @Test @@ -52,15 +41,7 @@ class MarkdownProcessorDocumentParsingExtraTest { * Expected HTML: *

foo bar

*/ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Emphasis("*", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo "), Emphasis("*", Text("bar"))))) } @Test @@ -72,17 +53,7 @@ class MarkdownProcessorDocumentParsingExtraTest { *

foo bar a

*/ parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Emphasis( - "_", - Text("foo "), - Emphasis("*", Text("bar")), - Text(" a"), - ), - ), - ), + Paragraph(Emphasis("*", Emphasis("_", Text("foo "), Emphasis("*", Text("bar")), Text(" a")))) ) } @@ -94,16 +65,7 @@ class MarkdownProcessorDocumentParsingExtraTest { * Expected HTML: *

foo bar a

*/ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Emphasis("*", Text("bar")), - Text(" a"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo "), Emphasis("*", Text("bar")), Text(" a")))) } @Test @@ -115,20 +77,7 @@ class MarkdownProcessorDocumentParsingExtraTest { *

foo bar a

*/ parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Emphasis( - "_", - Emphasis( - "*", - Text("foo "), - Emphasis("*", Text("bar")), - Text(" a"), - ), - ), - ), - ), + Paragraph(Emphasis("*", Emphasis("_", Emphasis("*", Text("foo "), Emphasis("*", Text("bar")), Text(" a"))))) ) } } diff --git a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingTest.kt b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingTest.kt index d40cd14ac..7547a9140 100755 --- a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingTest.kt +++ b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/MarkdownProcessorDocumentParsingTest.kt @@ -15,14 +15,12 @@ import org.jetbrains.jewel.markdown.processing.MarkdownProcessor import org.junit.Test /** - * This class tests that all the snippets in the CommonMark 0.31.2 specs - * are rendered correctly into MarkdownBlocks, matching what the CommonMark - * 0.20 HTML renderer tests also validate. Test cases are extracted from - * [here]( https://spec.commonmark.org/0.31.2/spec.json). + * This class tests that all the snippets in the CommonMark 0.31.2 specs are rendered correctly into MarkdownBlocks, + * matching what the CommonMark 0.20 HTML renderer tests also validate. Test cases are extracted from [here]( + * https://spec.commonmark.org/0.31.2/spec.json). * - * Note that the reference HTML output is only there as information; our - * parsing logic performs various transformations that CommonMark wouldn't. - * For more info, refer to [MarkdownProcessor.processMarkdownDocument]. + * Note that the reference HTML output is only there as information; our parsing logic performs various transformations + * that CommonMark wouldn't. For more info, refer to [MarkdownProcessor.processMarkdownDocument]. */ @Suppress( "HtmlDeprecatedAttribute", @@ -89,15 +87,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem( - paragraph("foo"), - paragraph("bar"), - ), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), paragraph("bar")), isTight = false)) } @Test @@ -114,15 +104,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem( - paragraph("foo"), - indentedCodeBlock(" bar"), - ), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), indentedCodeBlock(" bar")), isTight = false)) } @Test @@ -190,14 +172,9 @@ class MarkdownProcessorDocumentParsingTest { unorderedList( listItem( paragraph("foo"), - unorderedList( - listItem( - paragraph("bar"), - unorderedList(listItem(paragraph("baz"))), - ), - ), - ), - ), + unorderedList(listItem(paragraph("bar"), unorderedList(listItem(paragraph("baz"))))), + ) + ) ) } @@ -227,7 +204,7 @@ class MarkdownProcessorDocumentParsingTest { fun `should parse spec sample 12 correctly {Backslash escapes}`() { val parsed = processor.processMarkdownDocument( - "\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\n", + "\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\\\\\]\\^\\_\\`\\{\\|\\}\\~\n" ) /* @@ -263,7 +240,7 @@ class MarkdownProcessorDocumentParsingTest { |\[foo]: /url "not a reference" |\ö not a character entity """ - .trimMargin(), + .trimMargin() ) /* @@ -297,7 +274,7 @@ class MarkdownProcessorDocumentParsingTest { Text("[foo]: /url \"not a reference\""), SoftLineBreak, Text("ö not a character entity"), - ), + ) ) } @@ -320,7 +297,7 @@ class MarkdownProcessorDocumentParsingTest { |foo\ |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -363,7 +340,7 @@ class MarkdownProcessorDocumentParsingTest { |\[\] |~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -383,13 +360,7 @@ class MarkdownProcessorDocumentParsingTest { *

https://example.com?find=\*

*/ parsed.assertEquals( - Paragraph( - Link( - "https://example.com?find=\\*", - title = null, - Text("https://example.com?find=\\*"), - ), - ), + Paragraph(Link("https://example.com?find=\\*", title = null, Text("https://example.com?find=\\*"))) ) } @@ -424,7 +395,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /bar\* "ti\*tle" """ - .trimMargin(), + .trimMargin() ) /* @@ -443,7 +414,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -464,7 +435,7 @@ class MarkdownProcessorDocumentParsingTest { |¾ ℋ ⅆ |∲ ≧̸ """ - .trimMargin(), + .trimMargin() ) /* @@ -473,15 +444,7 @@ class MarkdownProcessorDocumentParsingTest { * ¾ ℋ ⅆ * ∲ ≧̸

*/ - parsed.assertEquals( - Paragraph( - Text("  & © Æ Ď"), - SoftLineBreak, - Text("¾ ℋ ⅆ"), - SoftLineBreak, - Text("∲ ≧̸"), - ), - ) + parsed.assertEquals(Paragraph(Text("  & © Æ Ď"), SoftLineBreak, Text("¾ ℋ ⅆ"), SoftLineBreak, Text("∲ ≧̸"))) } @Test @@ -517,7 +480,7 @@ class MarkdownProcessorDocumentParsingTest { |&#abcdef0; |&ThisIsNotDefined; &hi?; """ - .trimMargin(), + .trimMargin() ) /* @@ -536,7 +499,7 @@ class MarkdownProcessorDocumentParsingTest { Text("&#abcdef0;"), SoftLineBreak, Text("&ThisIsNotDefined; &hi?;"), - ), + ) ) } @@ -594,7 +557,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /föö "föö" """ - .trimMargin(), + .trimMargin() ) /* @@ -614,7 +577,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -657,13 +620,7 @@ class MarkdownProcessorDocumentParsingTest { *

*foo* * foo

*/ - parsed.assertEquals( - Paragraph( - Text("*foo*"), - SoftLineBreak, - Emphasis("*", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("*foo*"), SoftLineBreak, Emphasis("*", Text("foo")))) } @Test @@ -675,7 +632,7 @@ class MarkdownProcessorDocumentParsingTest { | |* foo """ - .trimMargin(), + .trimMargin() ) /* @@ -685,10 +642,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • foo
  • * */ - parsed.assertEquals( - paragraph("* foo"), - unorderedList(listItem(paragraph("foo")), marker = "*"), - ) + parsed.assertEquals(paragraph("* foo"), unorderedList(listItem(paragraph("foo")), marker = "*")) } @Test @@ -734,7 +688,7 @@ class MarkdownProcessorDocumentParsingTest { |- `one |- two` """ - .trimMargin(), + .trimMargin() ) /* @@ -744,12 +698,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • two`
  • * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("`one")), - listItem(paragraph("two`")), - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("`one")), listItem(paragraph("two`")))) } @Test @@ -761,7 +710,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |___ """ - .trimMargin(), + .trimMargin() ) /* @@ -770,11 +719,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *
    */ - parsed.assertEquals( - thematicBreak(), - thematicBreak(), - thematicBreak(), - ) + parsed.assertEquals(thematicBreak(), thematicBreak(), thematicBreak()) } @Test @@ -808,7 +753,7 @@ class MarkdownProcessorDocumentParsingTest { |** |__ """ - .trimMargin(), + .trimMargin() ) /* @@ -817,15 +762,7 @@ class MarkdownProcessorDocumentParsingTest { * ** * __

    */ - parsed.assertEquals( - Paragraph( - Text("--"), - SoftLineBreak, - Text("**"), - SoftLineBreak, - Text("__"), - ), - ) + parsed.assertEquals(Paragraph(Text("--"), SoftLineBreak, Text("**"), SoftLineBreak, Text("__"))) } @Test @@ -837,7 +774,7 @@ class MarkdownProcessorDocumentParsingTest { | *** | *** """ - .trimMargin(), + .trimMargin() ) /* @@ -846,11 +783,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *
    */ - parsed.assertEquals( - thematicBreak(), - thematicBreak(), - thematicBreak(), - ) + parsed.assertEquals(thematicBreak(), thematicBreak(), thematicBreak()) } @Test @@ -873,7 +806,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo | *** """ - .trimMargin(), + .trimMargin() ) /* @@ -950,7 +883,7 @@ class MarkdownProcessorDocumentParsingTest { | |---a--- """ - .trimMargin(), + .trimMargin() ) /* @@ -959,11 +892,7 @@ class MarkdownProcessorDocumentParsingTest { *

    a------

    *

    ---a---

    */ - parsed.assertEquals( - paragraph("_ _ _ _ a"), - paragraph("a------"), - paragraph("---a---"), - ) + parsed.assertEquals(paragraph("_ _ _ _ a"), paragraph("a------"), paragraph("---a---")) } @Test @@ -986,7 +915,7 @@ class MarkdownProcessorDocumentParsingTest { |*** |- bar """ - .trimMargin(), + .trimMargin() ) /* @@ -1015,7 +944,7 @@ class MarkdownProcessorDocumentParsingTest { |*** |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -1024,11 +953,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *

    bar

    */ - parsed.assertEquals( - paragraph("Foo"), - thematicBreak(), - paragraph("bar"), - ) + parsed.assertEquals(paragraph("Foo"), thematicBreak(), paragraph("bar")) } @Test @@ -1040,7 +965,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -1048,10 +973,7 @@ class MarkdownProcessorDocumentParsingTest { *

    Foo

    *

    bar

    */ - parsed.assertEquals( - heading(2, Text("Foo")), - paragraph("bar"), - ) + parsed.assertEquals(heading(2, Text("Foo")), paragraph("bar")) } @Test @@ -1063,7 +985,7 @@ class MarkdownProcessorDocumentParsingTest { |* * * |* Bar """ - .trimMargin(), + .trimMargin() ) /* @@ -1091,7 +1013,7 @@ class MarkdownProcessorDocumentParsingTest { |- Foo |- * * * """ - .trimMargin(), + .trimMargin() ) /* @@ -1103,12 +1025,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("Foo")), - listItem(thematicBreak()), - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("Foo")), listItem(thematicBreak()))) } @Test @@ -1123,7 +1040,7 @@ class MarkdownProcessorDocumentParsingTest { |##### foo |###### foo """ - .trimMargin(), + .trimMargin() ) /* @@ -1165,7 +1082,7 @@ class MarkdownProcessorDocumentParsingTest { | |#hashtag """ - .trimMargin(), + .trimMargin() ) /* @@ -1173,10 +1090,7 @@ class MarkdownProcessorDocumentParsingTest { *

    #5 bolt

    *

    #hashtag

    */ - parsed.assertEquals( - paragraph("#5 bolt"), - paragraph("#hashtag"), - ) + parsed.assertEquals(paragraph("#5 bolt"), paragraph("#hashtag")) } @Test @@ -1198,14 +1112,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar *baz*

    */ - parsed.assertEquals( - heading( - level = 1, - Text("foo "), - Emphasis("*", Text("bar")), - Text(" *baz*"), - ), - ) + parsed.assertEquals(heading(level = 1, Text("foo "), Emphasis("*", Text("bar")), Text(" *baz*"))) } @Test @@ -1228,7 +1135,7 @@ class MarkdownProcessorDocumentParsingTest { | ## foo | # foo """ - .trimMargin(), + .trimMargin() ) /* @@ -1264,7 +1171,7 @@ class MarkdownProcessorDocumentParsingTest { |foo | # bar """ - .trimMargin(), + .trimMargin() ) /* @@ -1283,7 +1190,7 @@ class MarkdownProcessorDocumentParsingTest { |## foo ## | ### bar ### """ - .trimMargin(), + .trimMargin() ) /* @@ -1291,10 +1198,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    *

    bar

    */ - parsed.assertEquals( - heading(level = 2, Text("foo")), - heading(level = 3, Text("bar")), - ) + parsed.assertEquals(heading(level = 2, Text("foo")), heading(level = 3, Text("bar"))) } @Test @@ -1305,7 +1209,7 @@ class MarkdownProcessorDocumentParsingTest { |# foo ################################## |##### foo ## """ - .trimMargin(), + .trimMargin() ) /* @@ -1313,10 +1217,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    *
    foo
    */ - parsed.assertEquals( - heading(level = 1, Text("foo")), - heading(level = 5, Text("foo")), - ) + parsed.assertEquals(heading(level = 1, Text("foo")), heading(level = 5, Text("foo"))) } @Test @@ -1361,7 +1262,7 @@ class MarkdownProcessorDocumentParsingTest { |## foo #\## |# foo \# """ - .trimMargin(), + .trimMargin() ) /* @@ -1386,7 +1287,7 @@ class MarkdownProcessorDocumentParsingTest { |## foo |**** """ - .trimMargin(), + .trimMargin() ) /* @@ -1395,11 +1296,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    *
    */ - parsed.assertEquals( - thematicBreak(), - heading(level = 2, Text("foo")), - thematicBreak(), - ) + parsed.assertEquals(thematicBreak(), heading(level = 2, Text("foo")), thematicBreak()) } @Test @@ -1411,7 +1308,7 @@ class MarkdownProcessorDocumentParsingTest { |# baz |Bar foo """ - .trimMargin(), + .trimMargin() ) /* @@ -1420,11 +1317,7 @@ class MarkdownProcessorDocumentParsingTest { *

    baz

    *

    Bar foo

    */ - parsed.assertEquals( - paragraph("Foo bar"), - heading(level = 1, Text("baz")), - paragraph("Bar foo"), - ) + parsed.assertEquals(paragraph("Foo bar"), heading(level = 1, Text("baz")), paragraph("Bar foo")) } @Test @@ -1436,7 +1329,7 @@ class MarkdownProcessorDocumentParsingTest { |# |### ### """ - .trimMargin(), + .trimMargin() ) /* @@ -1463,7 +1356,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo *bar* |--------- """ - .trimMargin(), + .trimMargin() ) /* @@ -1487,7 +1380,7 @@ class MarkdownProcessorDocumentParsingTest { |baz* |==== """ - .trimMargin(), + .trimMargin() ) /* @@ -1495,13 +1388,7 @@ class MarkdownProcessorDocumentParsingTest { *

    Foo bar * baz

    */ - parsed.assertEquals( - heading( - level = 1, - Text("Foo "), - Emphasis("*", Text("bar"), SoftLineBreak, Text("baz")), - ), - ) + parsed.assertEquals(heading(level = 1, Text("Foo "), Emphasis("*", Text("bar"), SoftLineBreak, Text("baz")))) } @Test @@ -1514,12 +1401,7 @@ class MarkdownProcessorDocumentParsingTest { * baz */ parsed.assertEquals( - heading( - level = 1, - Text("Foo "), - Emphasis("*", Text("bar"), SoftLineBreak, Text("baz")), - Text(""), - ), + heading(level = 1, Text("Foo "), Emphasis("*", Text("bar"), SoftLineBreak, Text("baz")), Text("")) ) } @@ -1534,7 +1416,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo |= """ - .trimMargin(), + .trimMargin() ) /* @@ -1542,10 +1424,7 @@ class MarkdownProcessorDocumentParsingTest { *

    Foo

    *

    Foo

    */ - parsed.assertEquals( - heading(level = 2, Text("Foo")), - heading(level = 1, Text("Foo")), - ) + parsed.assertEquals(heading(level = 2, Text("Foo")), heading(level = 1, Text("Foo"))) } @Test @@ -1562,7 +1441,7 @@ class MarkdownProcessorDocumentParsingTest { | Foo | === """ - .trimMargin(), + .trimMargin() ) /* @@ -1589,7 +1468,7 @@ class MarkdownProcessorDocumentParsingTest { | Foo |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1601,10 +1480,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - indentedCodeBlock("Foo\n---\n\nFoo"), - thematicBreak(), - ) + parsed.assertEquals(indentedCodeBlock("Foo\n---\n\nFoo"), thematicBreak()) } @Test @@ -1615,7 +1491,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo | ---- """ - .trimMargin(), + .trimMargin() ) /* @@ -1633,7 +1509,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo | --- """ - .trimMargin(), + .trimMargin() ) /* @@ -1655,7 +1531,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo |--- - """ - .trimMargin(), + .trimMargin() ) /* @@ -1665,11 +1541,7 @@ class MarkdownProcessorDocumentParsingTest { *

    Foo

    *
    */ - parsed.assertEquals( - Paragraph(Text("Foo"), SoftLineBreak, Text("= =")), - paragraph("Foo"), - thematicBreak(), - ) + parsed.assertEquals(Paragraph(Text("Foo"), SoftLineBreak, Text("= =")), paragraph("Foo"), thematicBreak()) } @Test @@ -1680,7 +1552,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo |----- """ - .trimMargin(), + .trimMargin() ) /* @@ -1698,7 +1570,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo\ |---- """ - .trimMargin(), + .trimMargin() ) /* @@ -1721,7 +1593,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |of dashes"/> """ - .trimMargin(), + .trimMargin() ) /* @@ -1747,7 +1619,7 @@ class MarkdownProcessorDocumentParsingTest { |> Foo |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1757,10 +1629,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - blockQuote(paragraph("Foo")), - thematicBreak(), - ) + parsed.assertEquals(blockQuote(paragraph("Foo")), thematicBreak()) } @Test @@ -1772,7 +1641,7 @@ class MarkdownProcessorDocumentParsingTest { |bar |=== """ - .trimMargin(), + .trimMargin() ) /* @@ -1783,17 +1652,7 @@ class MarkdownProcessorDocumentParsingTest { * ===

    * */ - parsed.assertEquals( - blockQuote( - Paragraph( - Text("foo"), - SoftLineBreak, - Text("bar"), - SoftLineBreak, - Text("==="), - ), - ), - ) + parsed.assertEquals(blockQuote(Paragraph(Text("foo"), SoftLineBreak, Text("bar"), SoftLineBreak, Text("===")))) } @Test @@ -1804,7 +1663,7 @@ class MarkdownProcessorDocumentParsingTest { |- Foo |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1814,10 +1673,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - unorderedList(listItem(paragraph("Foo"))), - thematicBreak(), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("Foo"))), thematicBreak()) } @Test @@ -1829,7 +1685,7 @@ class MarkdownProcessorDocumentParsingTest { |Bar |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1852,7 +1708,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |Baz """ - .trimMargin(), + .trimMargin() ) /* @@ -1878,7 +1734,7 @@ class MarkdownProcessorDocumentParsingTest { | |==== """ - .trimMargin(), + .trimMargin() ) /* @@ -1896,7 +1752,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1904,10 +1760,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *
    */ - parsed.assertEquals( - thematicBreak(), - thematicBreak(), - ) + parsed.assertEquals(thematicBreak(), thematicBreak()) } @Test @@ -1918,7 +1771,7 @@ class MarkdownProcessorDocumentParsingTest { |- foo |----- """ - .trimMargin(), + .trimMargin() ) /* @@ -1928,10 +1781,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - unorderedList(listItem(paragraph("foo"))), - thematicBreak(), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"))), thematicBreak()) } @Test @@ -1942,7 +1792,7 @@ class MarkdownProcessorDocumentParsingTest { | foo |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -1951,10 +1801,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - indentedCodeBlock("foo"), - thematicBreak(), - ) + parsed.assertEquals(indentedCodeBlock("foo"), thematicBreak()) } @Test @@ -1965,7 +1812,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo |----- """ - .trimMargin(), + .trimMargin() ) /* @@ -1975,10 +1822,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - blockQuote(paragraph("foo")), - thematicBreak(), - ) + parsed.assertEquals(blockQuote(paragraph("foo")), thematicBreak()) } @Test @@ -1989,7 +1833,7 @@ class MarkdownProcessorDocumentParsingTest { |\> foo |------ """ - .trimMargin(), + .trimMargin() ) /* @@ -2010,7 +1854,7 @@ class MarkdownProcessorDocumentParsingTest { |--- |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2019,11 +1863,7 @@ class MarkdownProcessorDocumentParsingTest { *

    bar

    *

    baz

    */ - parsed.assertEquals( - paragraph("Foo"), - heading(level = 2, Text("bar")), - paragraph("baz"), - ) + parsed.assertEquals(paragraph("Foo"), heading(level = 2, Text("bar")), paragraph("baz")) } @Test @@ -2038,7 +1878,7 @@ class MarkdownProcessorDocumentParsingTest { | |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2048,11 +1888,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *

    baz

    */ - parsed.assertEquals( - Paragraph(Text("Foo"), SoftLineBreak, Text("bar")), - thematicBreak(), - paragraph("baz"), - ) + parsed.assertEquals(Paragraph(Text("Foo"), SoftLineBreak, Text("bar")), thematicBreak(), paragraph("baz")) } @Test @@ -2065,7 +1901,7 @@ class MarkdownProcessorDocumentParsingTest { |* * * |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2075,11 +1911,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *

    baz

    */ - parsed.assertEquals( - Paragraph(Text("Foo"), SoftLineBreak, Text("bar")), - thematicBreak(), - paragraph("baz"), - ) + parsed.assertEquals(Paragraph(Text("Foo"), SoftLineBreak, Text("bar")), thematicBreak(), paragraph("baz")) } @Test @@ -2092,7 +1924,7 @@ class MarkdownProcessorDocumentParsingTest { |\--- |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2103,15 +1935,7 @@ class MarkdownProcessorDocumentParsingTest { * baz

    */ parsed.assertEquals( - Paragraph( - Text("Foo"), - SoftLineBreak, - Text("bar"), - SoftLineBreak, - Text("---"), - SoftLineBreak, - Text("baz"), - ), + Paragraph(Text("Foo"), SoftLineBreak, Text("bar"), SoftLineBreak, Text("---"), SoftLineBreak, Text("baz")) ) } @@ -2123,7 +1947,7 @@ class MarkdownProcessorDocumentParsingTest { | a simple | indented code block """ - .trimMargin(), + .trimMargin() ) /* @@ -2144,7 +1968,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -2156,12 +1980,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("foo"), paragraph("bar")), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), paragraph("bar")), isTight = false)) } @Test @@ -2173,7 +1992,7 @@ class MarkdownProcessorDocumentParsingTest { | | - bar """ - .trimMargin(), + .trimMargin() ) /* @@ -2188,13 +2007,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem( - paragraph("foo"), - unorderedList(listItem(paragraph("bar"))), - ), - isTight = false, - ), + orderedList(listItem(paragraph("foo"), unorderedList(listItem(paragraph("bar")))), isTight = false) ) } @@ -2208,7 +2021,7 @@ class MarkdownProcessorDocumentParsingTest { | | - one """ - .trimMargin(), + .trimMargin() ) /* @@ -2235,7 +2048,7 @@ class MarkdownProcessorDocumentParsingTest { | | chunk3 """ - .trimMargin(), + .trimMargin() ) /* @@ -2274,7 +2087,7 @@ class MarkdownProcessorDocumentParsingTest { |Foo | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -2293,7 +2106,7 @@ class MarkdownProcessorDocumentParsingTest { | foo |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -2302,10 +2115,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    bar

    */ - parsed.assertEquals( - indentedCodeBlock("foo"), - paragraph("bar"), - ) + parsed.assertEquals(indentedCodeBlock("foo"), paragraph("bar")) } @Test @@ -2320,7 +2130,7 @@ class MarkdownProcessorDocumentParsingTest { | foo |---- """ - .trimMargin(), + .trimMargin() ) /* @@ -2350,7 +2160,7 @@ class MarkdownProcessorDocumentParsingTest { | foo | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -2372,7 +2182,7 @@ class MarkdownProcessorDocumentParsingTest { | foo | """ - .trimMargin(), + .trimMargin() ) /* @@ -2405,7 +2215,7 @@ class MarkdownProcessorDocumentParsingTest { | > |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2427,7 +2237,7 @@ class MarkdownProcessorDocumentParsingTest { | > |~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -2448,7 +2258,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |`` """ - .trimMargin(), + .trimMargin() ) /* @@ -2468,7 +2278,7 @@ class MarkdownProcessorDocumentParsingTest { |~~~ |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2490,7 +2300,7 @@ class MarkdownProcessorDocumentParsingTest { |``` |~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -2512,7 +2322,7 @@ class MarkdownProcessorDocumentParsingTest { |``` |`````` """ - .trimMargin(), + .trimMargin() ) /* @@ -2534,7 +2344,7 @@ class MarkdownProcessorDocumentParsingTest { |~~~ |~~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -2567,7 +2377,7 @@ class MarkdownProcessorDocumentParsingTest { |``` |aaa """ - .trimMargin(), + .trimMargin() ) /* @@ -2590,7 +2400,7 @@ class MarkdownProcessorDocumentParsingTest { | |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -2601,10 +2411,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    bbb

    */ - parsed.assertEquals( - blockQuote(fencedCodeBlock("aaa")), - paragraph("bbb"), - ) + parsed.assertEquals(blockQuote(fencedCodeBlock("aaa")), paragraph("bbb")) } @Test @@ -2617,7 +2424,7 @@ class MarkdownProcessorDocumentParsingTest { | |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2637,7 +2444,7 @@ class MarkdownProcessorDocumentParsingTest { |``` |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2657,7 +2464,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2680,7 +2487,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2704,7 +2511,7 @@ class MarkdownProcessorDocumentParsingTest { | aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2726,7 +2533,7 @@ class MarkdownProcessorDocumentParsingTest { | aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2748,7 +2555,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2768,7 +2575,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2788,7 +2595,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa | ``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2808,7 +2615,7 @@ class MarkdownProcessorDocumentParsingTest { |``` ``` |aaa """ - .trimMargin(), + .trimMargin() ) /* @@ -2828,7 +2635,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa |~~~ ~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -2851,7 +2658,7 @@ class MarkdownProcessorDocumentParsingTest { |``` |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2861,11 +2668,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    baz

    */ - parsed.assertEquals( - paragraph("foo"), - fencedCodeBlock("bar"), - paragraph("baz"), - ) + parsed.assertEquals(paragraph("foo"), fencedCodeBlock("bar"), paragraph("baz")) } @Test @@ -2880,7 +2683,7 @@ class MarkdownProcessorDocumentParsingTest { |~~~ |# baz """ - .trimMargin(), + .trimMargin() ) /* @@ -2890,11 +2693,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    baz

    */ - parsed.assertEquals( - heading(level = 2, Text("foo")), - fencedCodeBlock("bar"), - heading(level = 1, Text("baz")), - ) + parsed.assertEquals(heading(level = 2, Text("foo")), fencedCodeBlock("bar"), heading(level = 1, Text("baz"))) } @Test @@ -2908,7 +2707,7 @@ class MarkdownProcessorDocumentParsingTest { |end |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -2919,10 +2718,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - fencedCodeBlock( - "def foo(x)\n return 3\nend", - mimeType = MimeType.Known.fromMarkdownLanguageName("ruby"), - ), + fencedCodeBlock("def foo(x)\n return 3\nend", mimeType = MimeType.Known.fromMarkdownLanguageName("ruby")) ) } @@ -2937,7 +2733,7 @@ class MarkdownProcessorDocumentParsingTest { |end |~~~~~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -2948,10 +2744,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - fencedCodeBlock( - "def foo(x)\n return 3\nend", - mimeType = MimeType.Known.fromMarkdownLanguageName("ruby"), - ), + fencedCodeBlock("def foo(x)\n return 3\nend", mimeType = MimeType.Known.fromMarkdownLanguageName("ruby")) ) } @@ -2963,19 +2756,14 @@ class MarkdownProcessorDocumentParsingTest { |````; |```` """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *
    */ - parsed.assertEquals( - fencedCodeBlock( - "", - mimeType = MimeType.Known.fromMarkdownLanguageName(";"), - ), - ) + parsed.assertEquals(fencedCodeBlock("", mimeType = MimeType.Known.fromMarkdownLanguageName(";"))) } @Test @@ -2986,7 +2774,7 @@ class MarkdownProcessorDocumentParsingTest { |``` aa ``` |foo """ - .trimMargin(), + .trimMargin() ) /* @@ -3006,7 +2794,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |~~~ """ - .trimMargin(), + .trimMargin() ) /* @@ -3014,12 +2802,7 @@ class MarkdownProcessorDocumentParsingTest { *
    foo
              * 
    */ - parsed.assertEquals( - fencedCodeBlock( - "foo", - mimeType = MimeType.Known.fromMarkdownLanguageName("aa"), - ), - ) + parsed.assertEquals(fencedCodeBlock("foo", mimeType = MimeType.Known.fromMarkdownLanguageName("aa"))) } @Test @@ -3031,7 +2814,7 @@ class MarkdownProcessorDocumentParsingTest { |``` aaa |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -3055,7 +2838,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -3069,12 +2852,7 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( htmlBlock("
    \n
    \n**Hello**,"),
    -            Paragraph(
    -                Emphasis("_", Text("world")),
    -                Text("."),
    -                SoftLineBreak,
    -                HtmlInline("
    "), - ), + Paragraph(Emphasis("_", Text("world")), Text("."), SoftLineBreak, HtmlInline("")), htmlBlock("
    "), ) } @@ -3094,7 +2872,7 @@ class MarkdownProcessorDocumentParsingTest { | |okay. """ - .trimMargin(), + .trimMargin() ) /* @@ -3119,7 +2897,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ), paragraph("okay."), ) @@ -3134,7 +2912,7 @@ class MarkdownProcessorDocumentParsingTest { | *hello* | """ - .trimMargin(), + .trimMargin() ) /* @@ -3154,7 +2932,7 @@ class MarkdownProcessorDocumentParsingTest { | |*foo* """ - .trimMargin(), + .trimMargin() ) /* @@ -3176,7 +2954,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -3201,7 +2979,7 @@ class MarkdownProcessorDocumentParsingTest { | class="bar"> | """ - .trimMargin(), + .trimMargin() ) /* @@ -3217,8 +2995,8 @@ class MarkdownProcessorDocumentParsingTest { | class="bar"> | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3231,7 +3009,7 @@ class MarkdownProcessorDocumentParsingTest { | baz"> | """ - .trimMargin(), + .trimMargin() ) /* @@ -3247,8 +3025,8 @@ class MarkdownProcessorDocumentParsingTest { | baz"> | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3262,7 +3040,7 @@ class MarkdownProcessorDocumentParsingTest { | |*bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -3271,10 +3049,7 @@ class MarkdownProcessorDocumentParsingTest { * *foo* *

    bar

    */ - parsed.assertEquals( - htmlBlock("
    \n*foo*"), - Paragraph(Emphasis("*", Text("bar"))), - ) + parsed.assertEquals(htmlBlock("
    \n*foo*"), Paragraph(Emphasis("*", Text("bar")))) } @Test @@ -3285,7 +3060,7 @@ class MarkdownProcessorDocumentParsingTest { |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -3370,8 +3145,8 @@ class MarkdownProcessorDocumentParsingTest { |foo | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3385,7 +3160,7 @@ class MarkdownProcessorDocumentParsingTest { |int x = 33; |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -3403,8 +3178,8 @@ class MarkdownProcessorDocumentParsingTest { |int x = 33; |``` """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3417,7 +3192,7 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), + .trimMargin() ) /* @@ -3433,8 +3208,8 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3447,7 +3222,7 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), + .trimMargin() ) /* @@ -3463,8 +3238,8 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3477,7 +3252,7 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), + .trimMargin() ) /* @@ -3493,8 +3268,8 @@ class MarkdownProcessorDocumentParsingTest { |*bar* | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3506,7 +3281,7 @@ class MarkdownProcessorDocumentParsingTest { | |*bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -3520,8 +3295,8 @@ class MarkdownProcessorDocumentParsingTest { | |*bar* """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3534,7 +3309,7 @@ class MarkdownProcessorDocumentParsingTest { |*foo* | """ - .trimMargin(), + .trimMargin() ) /* @@ -3550,8 +3325,8 @@ class MarkdownProcessorDocumentParsingTest { |*foo* | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3566,7 +3341,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -3575,11 +3350,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    * */ - parsed.assertEquals( - htmlBlock(""), - Paragraph(Emphasis("*", Text("foo"))), - htmlBlock(""), - ) + parsed.assertEquals(htmlBlock(""), Paragraph(Emphasis("*", Text("foo"))), htmlBlock("")) } @Test @@ -3590,13 +3361,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - HtmlInline(""), - Emphasis("*", Text("foo")), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(HtmlInline(""), Emphasis("*", Text("foo")), HtmlInline(""))) } @Test @@ -3612,7 +3377,7 @@ class MarkdownProcessorDocumentParsingTest { | |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -3635,7 +3400,7 @@ class MarkdownProcessorDocumentParsingTest { |main = print $ parseTags tags | """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -3653,7 +3418,7 @@ class MarkdownProcessorDocumentParsingTest { | |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -3674,7 +3439,7 @@ class MarkdownProcessorDocumentParsingTest { |document.getElementById("demo").innerHTML = "Hello JavaScript!"; | """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -3693,7 +3458,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -3717,8 +3482,8 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3735,7 +3500,7 @@ class MarkdownProcessorDocumentParsingTest { | |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -3758,7 +3523,7 @@ class MarkdownProcessorDocumentParsingTest { |p {color:blue;} | """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -3774,7 +3539,7 @@ class MarkdownProcessorDocumentParsingTest { | |foo """ - .trimMargin(), + .trimMargin() ) /* @@ -3792,8 +3557,8 @@ class MarkdownProcessorDocumentParsingTest { | |foo """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3807,7 +3572,7 @@ class MarkdownProcessorDocumentParsingTest { | |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -3818,10 +3583,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    bar

    */ - parsed.assertEquals( - blockQuote(htmlBlock("
    \nfoo")), - paragraph("bar"), - ) + parsed.assertEquals(blockQuote(htmlBlock("
    \nfoo")), paragraph("bar")) } @Test @@ -3832,7 +3594,7 @@ class MarkdownProcessorDocumentParsingTest { |-
    |- foo """ - .trimMargin(), + .trimMargin() ) /* @@ -3844,12 +3606,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • foo
  • * */ - parsed.assertEquals( - unorderedList( - listItem(htmlBlock("
    ")), - listItem(paragraph("foo")), - ), - ) + parsed.assertEquals(unorderedList(listItem(htmlBlock("
    ")), listItem(paragraph("foo")))) } @Test @@ -3860,7 +3617,7 @@ class MarkdownProcessorDocumentParsingTest { | |*foo* """ - .trimMargin(), + .trimMargin() ) /* @@ -3868,10 +3625,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    foo

    */ - parsed.assertEquals( - htmlBlock(""), - Paragraph(Emphasis("*", Text("foo"))), - ) + parsed.assertEquals(htmlBlock(""), Paragraph(Emphasis("*", Text("foo")))) } @Test @@ -3882,7 +3636,7 @@ class MarkdownProcessorDocumentParsingTest { |*bar* |*baz* """ - .trimMargin(), + .trimMargin() ) /* @@ -3890,10 +3644,7 @@ class MarkdownProcessorDocumentParsingTest { * *bar* *

    baz

    */ - parsed.assertEquals( - htmlBlock("*bar*"), - Paragraph(Emphasis("*", Text("baz"))), - ) + parsed.assertEquals(htmlBlock("*bar*"), Paragraph(Emphasis("*", Text("baz")))) } @Test @@ -3905,7 +3656,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |1. *bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -3921,8 +3672,8 @@ class MarkdownProcessorDocumentParsingTest { |foo |1. *bar* """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -3937,7 +3688,7 @@ class MarkdownProcessorDocumentParsingTest { | baz --> |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -3956,7 +3707,7 @@ class MarkdownProcessorDocumentParsingTest { |bar | baz --> """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -3974,7 +3725,7 @@ class MarkdownProcessorDocumentParsingTest { |?> |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -3995,7 +3746,7 @@ class MarkdownProcessorDocumentParsingTest { | |?> """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -4031,7 +3782,7 @@ class MarkdownProcessorDocumentParsingTest { |]]> |okay """ - .trimMargin(), + .trimMargin() ) /* @@ -4066,7 +3817,7 @@ class MarkdownProcessorDocumentParsingTest { |} |]]> """ - .trimMargin(), + .trimMargin() ), paragraph("okay"), ) @@ -4081,7 +3832,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -4090,10 +3841,7 @@ class MarkdownProcessorDocumentParsingTest { *
    <!-- foo -->
              * 
    */ - parsed.assertEquals( - htmlBlock(" "), - indentedCodeBlock(""), - ) + parsed.assertEquals(htmlBlock(" "), indentedCodeBlock("")) } @Test @@ -4105,7 +3853,7 @@ class MarkdownProcessorDocumentParsingTest { | |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -4114,10 +3862,7 @@ class MarkdownProcessorDocumentParsingTest { *
    <div>
              * 
    */ - parsed.assertEquals( - htmlBlock("
    "), - indentedCodeBlock("
    "), - ) + parsed.assertEquals(htmlBlock("
    "), indentedCodeBlock("
    ")) } @Test @@ -4130,7 +3875,7 @@ class MarkdownProcessorDocumentParsingTest { |bar |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -4148,7 +3893,7 @@ class MarkdownProcessorDocumentParsingTest { |bar |
    """ - .trimMargin(), + .trimMargin() ), ) } @@ -4163,7 +3908,7 @@ class MarkdownProcessorDocumentParsingTest { |
    |*foo* """ - .trimMargin(), + .trimMargin() ) /* @@ -4181,8 +3926,8 @@ class MarkdownProcessorDocumentParsingTest { |
    |*foo* """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -4195,7 +3940,7 @@ class MarkdownProcessorDocumentParsingTest { | |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -4205,13 +3950,7 @@ class MarkdownProcessorDocumentParsingTest { * baz

    */ parsed.assertEquals( - Paragraph( - Text("Foo"), - SoftLineBreak, - HtmlInline("
    "), - SoftLineBreak, - Text("baz"), - ), + Paragraph(Text("Foo"), SoftLineBreak, HtmlInline(""), SoftLineBreak, Text("baz")) ) } @@ -4226,7 +3965,7 @@ class MarkdownProcessorDocumentParsingTest { | |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -4251,7 +3990,7 @@ class MarkdownProcessorDocumentParsingTest { |*Emphasized* text. |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -4267,8 +4006,8 @@ class MarkdownProcessorDocumentParsingTest { |*Emphasized* text. |
    """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -4289,7 +4028,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -4328,7 +4067,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -4360,7 +4099,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4381,7 +4120,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4400,16 +4139,14 @@ class MarkdownProcessorDocumentParsingTest { | |[Foo*bar\]] """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    Foo*bar]

    */ - parsed.assertEquals( - Paragraph(Link(destination = "my_(url)", title = "title (with parens)", Text("Foo*bar]"))), - ) + parsed.assertEquals(Paragraph(Link(destination = "my_(url)", title = "title (with parens)", Text("Foo*bar]")))) } @Test @@ -4423,7 +4160,7 @@ class MarkdownProcessorDocumentParsingTest { | |[Foo bar] """ - .trimMargin(), + .trimMargin() ) /* @@ -4446,7 +4183,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4471,7 +4208,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4480,11 +4217,7 @@ class MarkdownProcessorDocumentParsingTest { *

    with blank line'

    *

    [foo]

    */ - parsed.assertEquals( - paragraph("[foo]: /url 'title"), - paragraph("with blank line'"), - paragraph("[foo]"), - ) + parsed.assertEquals(paragraph("[foo]: /url 'title"), paragraph("with blank line'"), paragraph("[foo]")) } @Test @@ -4497,7 +4230,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4516,7 +4249,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4524,10 +4257,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [foo]:

    *

    [foo]

    */ - parsed.assertEquals( - paragraph("[foo]:"), - paragraph("[foo]"), - ) + parsed.assertEquals(paragraph("[foo]:"), paragraph("[foo]")) } @Test @@ -4539,7 +4269,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4558,7 +4288,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4566,10 +4296,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [foo]: (baz)

    *

    [foo]

    */ - parsed.assertEquals( - Paragraph(Text("[foo]: "), HtmlInline(""), Text("(baz)")), - paragraph("[foo]"), - ) + parsed.assertEquals(Paragraph(Text("[foo]: "), HtmlInline(""), Text("(baz)")), paragraph("[foo]")) } @Test @@ -4581,7 +4308,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4600,7 +4327,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: url """ - .trimMargin(), + .trimMargin() ) /* @@ -4620,7 +4347,7 @@ class MarkdownProcessorDocumentParsingTest { |[foo]: first |[foo]: second """ - .trimMargin(), + .trimMargin() ) /* @@ -4639,7 +4366,7 @@ class MarkdownProcessorDocumentParsingTest { | |[Foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4658,7 +4385,7 @@ class MarkdownProcessorDocumentParsingTest { | |[αγω] """ - .trimMargin(), + .trimMargin() ) /* @@ -4689,7 +4416,7 @@ class MarkdownProcessorDocumentParsingTest { |]: /url |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -4718,7 +4445,7 @@ class MarkdownProcessorDocumentParsingTest { |[foo]: /url |"title" ok """ - .trimMargin(), + .trimMargin() ) /* @@ -4737,7 +4464,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4746,10 +4473,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    [foo]

    */ - parsed.assertEquals( - indentedCodeBlock("[foo]: /url \"title\""), - paragraph("[foo]"), - ) + parsed.assertEquals(indentedCodeBlock("[foo]: /url \"title\""), paragraph("[foo]")) } @Test @@ -4763,7 +4487,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4772,10 +4496,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    [foo]

    */ - parsed.assertEquals( - fencedCodeBlock("[foo]: /url"), - paragraph("[foo]"), - ) + parsed.assertEquals(fencedCodeBlock("[foo]: /url"), paragraph("[foo]")) } @Test @@ -4788,7 +4509,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar] """ - .trimMargin(), + .trimMargin() ) /* @@ -4797,14 +4518,7 @@ class MarkdownProcessorDocumentParsingTest { * [bar]: /baz

    *

    [bar]

    */ - parsed.assertEquals( - Paragraph( - Text("Foo"), - SoftLineBreak, - Text("[bar]: /baz"), - ), - paragraph("[bar]"), - ) + parsed.assertEquals(Paragraph(Text("Foo"), SoftLineBreak, Text("[bar]: /baz")), paragraph("[bar]")) } @Test @@ -4816,7 +4530,7 @@ class MarkdownProcessorDocumentParsingTest { |[foo]: /url |> bar """ - .trimMargin(), + .trimMargin() ) /* @@ -4842,7 +4556,7 @@ class MarkdownProcessorDocumentParsingTest { |=== |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4865,7 +4579,7 @@ class MarkdownProcessorDocumentParsingTest { |=== |[foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -4874,11 +4588,7 @@ class MarkdownProcessorDocumentParsingTest { * foo

    */ parsed.assertEquals( - Paragraph( - Text("==="), - SoftLineBreak, - Link(destination = "/url", title = null, Text("foo")), - ), + Paragraph(Text("==="), SoftLineBreak, Link(destination = "/url", title = null, Text("foo"))) ) } @@ -4896,7 +4606,7 @@ class MarkdownProcessorDocumentParsingTest { |[bar], |[baz] """ - .trimMargin(), + .trimMargin() ) /* @@ -4914,7 +4624,7 @@ class MarkdownProcessorDocumentParsingTest { Text(","), SoftLineBreak, Link(destination = "/baz-url", title = null, Text("baz")), - ), + ) ) } @@ -4927,7 +4637,7 @@ class MarkdownProcessorDocumentParsingTest { | |> [foo]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -4936,10 +4646,7 @@ class MarkdownProcessorDocumentParsingTest { *
    *
    */ - parsed.assertEquals( - Paragraph(Link(destination = "/url", title = null, Text("foo"))), - blockQuote(), - ) + parsed.assertEquals(Paragraph(Link(destination = "/url", title = null, Text("foo"))), blockQuote()) } @Test @@ -4951,7 +4658,7 @@ class MarkdownProcessorDocumentParsingTest { | |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -4959,10 +4666,7 @@ class MarkdownProcessorDocumentParsingTest { *

    aaa

    *

    bbb

    */ - parsed.assertEquals( - paragraph("aaa"), - paragraph("bbb"), - ) + parsed.assertEquals(paragraph("aaa"), paragraph("bbb")) } @Test @@ -4976,7 +4680,7 @@ class MarkdownProcessorDocumentParsingTest { |ccc |ddd """ - .trimMargin(), + .trimMargin() ) /* @@ -5002,7 +4706,7 @@ class MarkdownProcessorDocumentParsingTest { | |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5010,10 +4714,7 @@ class MarkdownProcessorDocumentParsingTest { *

    aaa

    *

    bbb

    */ - parsed.assertEquals( - paragraph("aaa"), - paragraph("bbb"), - ) + parsed.assertEquals(paragraph("aaa"), paragraph("bbb")) } @Test @@ -5024,7 +4725,7 @@ class MarkdownProcessorDocumentParsingTest { | aaa | bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5044,7 +4745,7 @@ class MarkdownProcessorDocumentParsingTest { | bbb | ccc """ - .trimMargin(), + .trimMargin() ) /* @@ -5053,15 +4754,7 @@ class MarkdownProcessorDocumentParsingTest { * bbb * ccc

    */ - parsed.assertEquals( - Paragraph( - Text("aaa"), - SoftLineBreak, - Text("bbb"), - SoftLineBreak, - Text("ccc"), - ), - ) + parsed.assertEquals(Paragraph(Text("aaa"), SoftLineBreak, Text("bbb"), SoftLineBreak, Text("ccc"))) } @Test @@ -5072,7 +4765,7 @@ class MarkdownProcessorDocumentParsingTest { | aaa |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5091,7 +4784,7 @@ class MarkdownProcessorDocumentParsingTest { | aaa |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5100,10 +4793,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    bbb

    */ - parsed.assertEquals( - indentedCodeBlock("aaa"), - paragraph("bbb"), - ) + parsed.assertEquals(indentedCodeBlock("aaa"), paragraph("bbb")) } @Test @@ -5114,7 +4804,7 @@ class MarkdownProcessorDocumentParsingTest { |aaa |bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5139,7 +4829,7 @@ class MarkdownProcessorDocumentParsingTest { | | """ - .trimMargin(), + .trimMargin() ) /* @@ -5147,10 +4837,7 @@ class MarkdownProcessorDocumentParsingTest { *

    aaa

    *

    aaa

    */ - parsed.assertEquals( - paragraph("aaa"), - heading(level = 1, Text("aaa")), - ) + parsed.assertEquals(paragraph("aaa"), heading(level = 1, Text("aaa"))) } @Test @@ -5162,7 +4849,7 @@ class MarkdownProcessorDocumentParsingTest { |> bar |> baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5174,10 +4861,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - blockQuote( - heading(level = 1, Text("Foo")), - Paragraph(Text("bar"), SoftLineBreak, Text("baz")), - ), + blockQuote(heading(level = 1, Text("Foo")), Paragraph(Text("bar"), SoftLineBreak, Text("baz"))) ) } @@ -5190,7 +4874,7 @@ class MarkdownProcessorDocumentParsingTest { |>bar |> baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5202,10 +4886,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - blockQuote( - heading(level = 1, Text("Foo")), - Paragraph(Text("bar"), SoftLineBreak, Text("baz")), - ), + blockQuote(heading(level = 1, Text("Foo")), Paragraph(Text("bar"), SoftLineBreak, Text("baz"))) ) } @@ -5218,7 +4899,7 @@ class MarkdownProcessorDocumentParsingTest { | > bar | > baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5230,10 +4911,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - blockQuote( - heading(level = 1, Text("Foo")), - Paragraph(Text("bar"), SoftLineBreak, Text("baz")), - ), + blockQuote(heading(level = 1, Text("Foo")), Paragraph(Text("bar"), SoftLineBreak, Text("baz"))) ) } @@ -5246,7 +4924,7 @@ class MarkdownProcessorDocumentParsingTest { | > bar | > baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5268,7 +4946,7 @@ class MarkdownProcessorDocumentParsingTest { |> bar |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5280,10 +4958,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - blockQuote( - heading(level = 1, Text("Foo")), - Paragraph(Text("bar"), SoftLineBreak, Text("baz")), - ), + blockQuote(heading(level = 1, Text("Foo")), Paragraph(Text("bar"), SoftLineBreak, Text("baz"))) ) } @@ -5296,7 +4971,7 @@ class MarkdownProcessorDocumentParsingTest { |baz |> foo """ - .trimMargin(), + .trimMargin() ) /* @@ -5307,17 +4982,7 @@ class MarkdownProcessorDocumentParsingTest { * foo

    * */ - parsed.assertEquals( - blockQuote( - Paragraph( - Text("bar"), - SoftLineBreak, - Text("baz"), - SoftLineBreak, - Text("foo"), - ), - ), - ) + parsed.assertEquals(blockQuote(Paragraph(Text("bar"), SoftLineBreak, Text("baz"), SoftLineBreak, Text("foo")))) } @Test @@ -5328,7 +4993,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo |--- """ - .trimMargin(), + .trimMargin() ) /* @@ -5338,10 +5003,7 @@ class MarkdownProcessorDocumentParsingTest { * *
    */ - parsed.assertEquals( - blockQuote(paragraph("foo")), - thematicBreak(), - ) + parsed.assertEquals(blockQuote(paragraph("foo")), thematicBreak()) } @Test @@ -5352,7 +5014,7 @@ class MarkdownProcessorDocumentParsingTest { |> - foo |- bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5380,7 +5042,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5392,10 +5054,7 @@ class MarkdownProcessorDocumentParsingTest { *
    bar
              * 
    */ - parsed.assertEquals( - blockQuote(indentedCodeBlock("foo")), - indentedCodeBlock("bar"), - ) + parsed.assertEquals(blockQuote(indentedCodeBlock("foo")), indentedCodeBlock("bar")) } @Test @@ -5407,7 +5066,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |``` """ - .trimMargin(), + .trimMargin() ) /* @@ -5418,11 +5077,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    *
    */ - parsed.assertEquals( - blockQuote(fencedCodeBlock("")), - paragraph("foo"), - fencedCodeBlock(""), - ) + parsed.assertEquals(blockQuote(fencedCodeBlock("")), paragraph("foo"), fencedCodeBlock("")) } @Test @@ -5433,7 +5088,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo | - bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5467,7 +5122,7 @@ class MarkdownProcessorDocumentParsingTest { |> |> """ - .trimMargin(), + .trimMargin() ) /* @@ -5487,7 +5142,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo |> """ - .trimMargin(), + .trimMargin() ) /* @@ -5508,7 +5163,7 @@ class MarkdownProcessorDocumentParsingTest { | |> bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5520,10 +5175,7 @@ class MarkdownProcessorDocumentParsingTest { *

    bar

    * */ - parsed.assertEquals( - blockQuote(paragraph("foo")), - blockQuote(paragraph("bar")), - ) + parsed.assertEquals(blockQuote(paragraph("foo")), blockQuote(paragraph("bar"))) } @Test @@ -5534,7 +5186,7 @@ class MarkdownProcessorDocumentParsingTest { |> foo |> bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5556,7 +5208,7 @@ class MarkdownProcessorDocumentParsingTest { |> |> bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5566,12 +5218,7 @@ class MarkdownProcessorDocumentParsingTest { *

    bar

    * */ - parsed.assertEquals( - blockQuote( - paragraph("foo"), - paragraph("bar"), - ), - ) + parsed.assertEquals(blockQuote(paragraph("foo"), paragraph("bar"))) } @Test @@ -5582,7 +5229,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |> bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5592,10 +5239,7 @@ class MarkdownProcessorDocumentParsingTest { *

    bar

    * */ - parsed.assertEquals( - paragraph("foo"), - blockQuote(paragraph("bar")), - ) + parsed.assertEquals(paragraph("foo"), blockQuote(paragraph("bar"))) } @Test @@ -5607,7 +5251,7 @@ class MarkdownProcessorDocumentParsingTest { |*** |> bbb """ - .trimMargin(), + .trimMargin() ) /* @@ -5620,11 +5264,7 @@ class MarkdownProcessorDocumentParsingTest { *

    bbb

    * */ - parsed.assertEquals( - blockQuote(paragraph("aaa")), - thematicBreak(), - blockQuote(paragraph("bbb")), - ) + parsed.assertEquals(blockQuote(paragraph("aaa")), thematicBreak(), blockQuote(paragraph("bbb"))) } @Test @@ -5635,7 +5275,7 @@ class MarkdownProcessorDocumentParsingTest { |> bar |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5657,7 +5297,7 @@ class MarkdownProcessorDocumentParsingTest { | |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5667,10 +5307,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    baz

    */ - parsed.assertEquals( - blockQuote(paragraph("bar")), - paragraph("baz"), - ) + parsed.assertEquals(blockQuote(paragraph("bar")), paragraph("baz")) } @Test @@ -5682,7 +5319,7 @@ class MarkdownProcessorDocumentParsingTest { |> |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5692,10 +5329,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    baz

    */ - parsed.assertEquals( - blockQuote(paragraph("bar")), - paragraph("baz"), - ) + parsed.assertEquals(blockQuote(paragraph("bar")), paragraph("baz")) } @Test @@ -5706,7 +5340,7 @@ class MarkdownProcessorDocumentParsingTest { |> > > foo |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -5720,13 +5354,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - blockQuote( - blockQuote( - blockQuote(Paragraph(Text("foo"), SoftLineBreak, Text("bar"))), - ), - ), - ) + parsed.assertEquals(blockQuote(blockQuote(blockQuote(Paragraph(Text("foo"), SoftLineBreak, Text("bar")))))) } @Test @@ -5738,7 +5366,7 @@ class MarkdownProcessorDocumentParsingTest { |> bar |>>baz """ - .trimMargin(), + .trimMargin() ) /* @@ -5755,18 +5383,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( blockQuote( - blockQuote( - blockQuote( - Paragraph( - Text("foo"), - SoftLineBreak, - Text("bar"), - SoftLineBreak, - Text("baz"), - ), - ), - ), - ), + blockQuote(blockQuote(Paragraph(Text("foo"), SoftLineBreak, Text("bar"), SoftLineBreak, Text("baz")))) + ) ) } @@ -5779,7 +5397,7 @@ class MarkdownProcessorDocumentParsingTest { | |> not code """ - .trimMargin(), + .trimMargin() ) /* @@ -5792,10 +5410,7 @@ class MarkdownProcessorDocumentParsingTest { *

    not code

    * */ - parsed.assertEquals( - blockQuote(indentedCodeBlock("code")), - blockQuote(paragraph("not code")), - ) + parsed.assertEquals(blockQuote(indentedCodeBlock("code")), blockQuote(paragraph("not code"))) } @Test @@ -5810,7 +5425,7 @@ class MarkdownProcessorDocumentParsingTest { | |> A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -5842,7 +5457,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -5867,7 +5482,7 @@ class MarkdownProcessorDocumentParsingTest { blockQuote(paragraph("A block quote.")), ), isTight = false, - ), + ) ) } @@ -5880,7 +5495,7 @@ class MarkdownProcessorDocumentParsingTest { | | two """ - .trimMargin(), + .trimMargin() ) /* @@ -5890,10 +5505,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    two

    */ - parsed.assertEquals( - unorderedList(listItem(paragraph("one"))), - paragraph("two"), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("one"))), paragraph("two")) } @Test @@ -5905,7 +5517,7 @@ class MarkdownProcessorDocumentParsingTest { | | two """ - .trimMargin(), + .trimMargin() ) /* @@ -5917,12 +5529,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("one"), paragraph("two")), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("one"), paragraph("two")), isTight = false)) } @Test @@ -5934,7 +5541,7 @@ class MarkdownProcessorDocumentParsingTest { | | two """ - .trimMargin(), + .trimMargin() ) /* @@ -5945,10 +5552,7 @@ class MarkdownProcessorDocumentParsingTest { *
     two
              * 
    */ - parsed.assertEquals( - unorderedList(listItem(paragraph("one"))), - indentedCodeBlock(" two"), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("one"))), indentedCodeBlock(" two")) } @Test @@ -5960,7 +5564,7 @@ class MarkdownProcessorDocumentParsingTest { | | two """ - .trimMargin(), + .trimMargin() ) /* @@ -5972,12 +5576,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("one"), paragraph("two")), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("one"), paragraph("two")), isTight = false)) } @Test @@ -5989,7 +5588,7 @@ class MarkdownProcessorDocumentParsingTest { |>> |>> two """ - .trimMargin(), + .trimMargin() ) /* @@ -6006,14 +5605,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - blockQuote( - blockQuote( - orderedList( - listItem(paragraph("one"), paragraph("two")), - isTight = false, - ), - ), - ), + blockQuote(blockQuote(orderedList(listItem(paragraph("one"), paragraph("two")), isTight = false))) ) } @@ -6026,7 +5618,7 @@ class MarkdownProcessorDocumentParsingTest { |>> | > > two """ - .trimMargin(), + .trimMargin() ) /* @@ -6040,14 +5632,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - blockQuote( - blockQuote( - unorderedList(listItem(paragraph("one"))), - paragraph("two"), - ), - ), - ) + parsed.assertEquals(blockQuote(blockQuote(unorderedList(listItem(paragraph("one"))), paragraph("two")))) } @Test @@ -6059,7 +5644,7 @@ class MarkdownProcessorDocumentParsingTest { | |2.two """ - .trimMargin(), + .trimMargin() ) /* @@ -6067,10 +5652,7 @@ class MarkdownProcessorDocumentParsingTest { *

    -one

    *

    2.two

    */ - parsed.assertEquals( - paragraph("-one"), - paragraph("2.two"), - ) + parsed.assertEquals(paragraph("-one"), paragraph("2.two")) } @Test @@ -6083,7 +5665,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6095,15 +5677,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem( - paragraph("foo"), - paragraph("bar"), - ), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), paragraph("bar")), isTight = false)) } @Test @@ -6121,7 +5695,7 @@ class MarkdownProcessorDocumentParsingTest { | | > bam """ - .trimMargin(), + .trimMargin() ) /* @@ -6140,14 +5714,9 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( orderedList( - listItem( - paragraph("foo"), - fencedCodeBlock("bar"), - paragraph("baz"), - blockQuote(paragraph("bam")), - ), + listItem(paragraph("foo"), fencedCodeBlock("bar"), paragraph("baz"), blockQuote(paragraph("bam"))), isTight = false, - ), + ) ) } @@ -6163,7 +5732,7 @@ class MarkdownProcessorDocumentParsingTest { | | baz """ - .trimMargin(), + .trimMargin() ) /* @@ -6180,10 +5749,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("Foo"), indentedCodeBlock("bar\n\n\nbaz")), - isTight = false, - ), + unorderedList(listItem(paragraph("Foo"), indentedCodeBlock("bar\n\n\nbaz")), isTight = false) ) } @@ -6257,7 +5823,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6270,12 +5836,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("foo"), indentedCodeBlock("bar")), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), indentedCodeBlock("bar")), isTight = false)) } @Test @@ -6287,7 +5848,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6301,11 +5862,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(paragraph("foo"), indentedCodeBlock("bar")), - startFrom = 10, - isTight = false, - ), + orderedList(listItem(paragraph("foo"), indentedCodeBlock("bar")), startFrom = 10, isTight = false) ) } @@ -6320,7 +5877,7 @@ class MarkdownProcessorDocumentParsingTest { | | more code """ - .trimMargin(), + .trimMargin() ) /* @@ -6331,11 +5888,7 @@ class MarkdownProcessorDocumentParsingTest { *
    more code
              * 
    */ - parsed.assertEquals( - indentedCodeBlock("indented code"), - paragraph("paragraph"), - indentedCodeBlock("more code"), - ) + parsed.assertEquals(indentedCodeBlock("indented code"), paragraph("paragraph"), indentedCodeBlock("more code")) } @Test @@ -6349,7 +5902,7 @@ class MarkdownProcessorDocumentParsingTest { | | more code """ - .trimMargin(), + .trimMargin() ) /* @@ -6366,13 +5919,9 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( orderedList( - listItem( - indentedCodeBlock("indented code"), - paragraph("paragraph"), - indentedCodeBlock("more code"), - ), + listItem(indentedCodeBlock("indented code"), paragraph("paragraph"), indentedCodeBlock("more code")), isTight = false, - ), + ) ) } @@ -6387,7 +5936,7 @@ class MarkdownProcessorDocumentParsingTest { | | more code """ - .trimMargin(), + .trimMargin() ) /* @@ -6404,13 +5953,9 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( orderedList( - listItem( - indentedCodeBlock(" indented code"), - paragraph("paragraph"), - indentedCodeBlock("more code"), - ), + listItem(indentedCodeBlock(" indented code"), paragraph("paragraph"), indentedCodeBlock("more code")), isTight = false, - ), + ) ) } @@ -6423,7 +5968,7 @@ class MarkdownProcessorDocumentParsingTest { | |bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6431,10 +5976,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    *

    bar

    */ - parsed.assertEquals( - paragraph("foo"), - paragraph("bar"), - ) + parsed.assertEquals(paragraph("foo"), paragraph("bar")) } @Test @@ -6446,7 +5988,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6456,10 +5998,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    bar

    */ - parsed.assertEquals( - unorderedList(listItem(paragraph("foo"))), - paragraph("bar"), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"))), paragraph("bar")) } @Test @@ -6471,7 +6010,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6483,12 +6022,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("foo"), paragraph("bar")), - isTight = false, - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo"), paragraph("bar")), isTight = false)) } @Test @@ -6505,7 +6039,7 @@ class MarkdownProcessorDocumentParsingTest { |- | baz """ - .trimMargin(), + .trimMargin() ) /* @@ -6527,7 +6061,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("foo")), listItem(fencedCodeBlock("bar")), listItem(indentedCodeBlock("baz")), - ), + ) ) } @@ -6539,7 +6073,7 @@ class MarkdownProcessorDocumentParsingTest { |- | foo """ - .trimMargin(), + .trimMargin() ) /* @@ -6560,7 +6094,7 @@ class MarkdownProcessorDocumentParsingTest { | | foo """ - .trimMargin(), + .trimMargin() ) /* @@ -6570,10 +6104,7 @@ class MarkdownProcessorDocumentParsingTest { * *

    foo

    */ - parsed.assertEquals( - unorderedList(listItem()), - paragraph("foo"), - ) + parsed.assertEquals(unorderedList(listItem()), paragraph("foo")) } @Test @@ -6585,7 +6116,7 @@ class MarkdownProcessorDocumentParsingTest { |- |- bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6596,13 +6127,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • bar
  • * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("foo")), - listItem(), - listItem(paragraph("bar")), - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo")), listItem(), listItem(paragraph("bar")))) } @Test @@ -6614,7 +6139,7 @@ class MarkdownProcessorDocumentParsingTest { |- |- bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6625,13 +6150,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • bar
  • * */ - parsed.assertEquals( - unorderedList( - listItem(paragraph("foo")), - listItem(), - listItem(paragraph("bar")), - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("foo")), listItem(), listItem(paragraph("bar")))) } @Test @@ -6643,7 +6162,7 @@ class MarkdownProcessorDocumentParsingTest { |2. |3. bar """ - .trimMargin(), + .trimMargin() ) /* @@ -6654,13 +6173,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • bar
  • * */ - parsed.assertEquals( - orderedList( - listItem(paragraph("foo")), - listItem(), - listItem(paragraph("bar")), - ), - ) + parsed.assertEquals(orderedList(listItem(paragraph("foo")), listItem(), listItem(paragraph("bar")))) } @Test @@ -6687,7 +6200,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |1. """ - .trimMargin(), + .trimMargin() ) /* @@ -6715,7 +6228,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -6740,7 +6253,7 @@ class MarkdownProcessorDocumentParsingTest { blockQuote(paragraph("A block quote.")), ), isTight = false, - ), + ) ) } @@ -6756,7 +6269,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -6781,7 +6294,7 @@ class MarkdownProcessorDocumentParsingTest { blockQuote(paragraph("A block quote.")), ), isTight = false, - ), + ) ) } @@ -6797,7 +6310,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -6822,7 +6335,7 @@ class MarkdownProcessorDocumentParsingTest { blockQuote(paragraph("A block quote.")), ), isTight = false, - ), + ) ) } @@ -6838,7 +6351,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -6861,8 +6374,8 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), - ), + .trimMargin() + ) ) } @@ -6878,7 +6391,7 @@ class MarkdownProcessorDocumentParsingTest { | | > A block quote. """ - .trimMargin(), + .trimMargin() ) /* @@ -6903,7 +6416,7 @@ class MarkdownProcessorDocumentParsingTest { blockQuote(paragraph("A block quote.")), ), isTight = false, - ), + ) ) } @@ -6915,7 +6428,7 @@ class MarkdownProcessorDocumentParsingTest { | 1. A paragraph | with two lines. """ - .trimMargin(), + .trimMargin() ) /* @@ -6926,9 +6439,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(Paragraph(Text("A paragraph"), SoftLineBreak, Text("with two lines."))), - ), + orderedList(listItem(Paragraph(Text("A paragraph"), SoftLineBreak, Text("with two lines.")))) ) } @@ -6940,7 +6451,7 @@ class MarkdownProcessorDocumentParsingTest { |> 1. > Blockquote |continued here. """ - .trimMargin(), + .trimMargin() ) /* @@ -6958,12 +6469,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( blockQuote( - orderedList( - listItem( - blockQuote(Paragraph(Text("Blockquote"), SoftLineBreak, Text("continued here."))), - ), - ), - ), + orderedList(listItem(blockQuote(Paragraph(Text("Blockquote"), SoftLineBreak, Text("continued here."))))) + ) ) } @@ -6975,7 +6482,7 @@ class MarkdownProcessorDocumentParsingTest { |> 1. > Blockquote |> continued here. """ - .trimMargin(), + .trimMargin() ) /* @@ -6993,12 +6500,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( blockQuote( - orderedList( - listItem( - blockQuote(Paragraph(Text("Blockquote"), SoftLineBreak, Text("continued here."))), - ), - ), - ), + orderedList(listItem(blockQuote(Paragraph(Text("Blockquote"), SoftLineBreak, Text("continued here."))))) + ) ) } @@ -7012,7 +6515,7 @@ class MarkdownProcessorDocumentParsingTest { | - baz | - boo """ - .trimMargin(), + .trimMargin() ) /* @@ -7040,16 +6543,11 @@ class MarkdownProcessorDocumentParsingTest { unorderedList( listItem( paragraph("bar"), - unorderedList( - listItem( - paragraph("baz"), - unorderedList(listItem(paragraph("boo"))), - ), - ), - ), + unorderedList(listItem(paragraph("baz"), unorderedList(listItem(paragraph("boo"))))), + ) ), - ), - ), + ) + ) ) } @@ -7063,7 +6561,7 @@ class MarkdownProcessorDocumentParsingTest { | - baz | - boo """ - .trimMargin(), + .trimMargin() ) /* @@ -7081,7 +6579,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("bar")), listItem(paragraph("baz")), listItem(paragraph("boo")), - ), + ) ) } @@ -7093,7 +6591,7 @@ class MarkdownProcessorDocumentParsingTest { |10) foo | - bar """ - .trimMargin(), + .trimMargin() ) /* @@ -7108,13 +6606,10 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( orderedList( - listItem( - paragraph("foo"), - unorderedList(listItem(paragraph("bar"))), - ), + listItem(paragraph("foo"), unorderedList(listItem(paragraph("bar")))), startFrom = 10, delimiter = ")", - ), + ) ) } @@ -7126,7 +6621,7 @@ class MarkdownProcessorDocumentParsingTest { |10) foo | - bar """ - .trimMargin(), + .trimMargin() ) /* @@ -7139,11 +6634,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(paragraph("foo")), - startFrom = 10, - delimiter = ")", - ), + orderedList(listItem(paragraph("foo")), startFrom = 10, delimiter = ")"), unorderedList(listItem(paragraph("bar"))), ) } @@ -7162,13 +6653,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem( - unorderedList(listItem(paragraph("foo"))), - ), - ), - ) + parsed.assertEquals(unorderedList(listItem(unorderedList(listItem(paragraph("foo")))))) } @Test @@ -7190,18 +6675,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem( - unorderedList( - listItem( - orderedList( - listItem(paragraph("foo")), - startFrom = 2, - ), - ), - ), - ), - ), + orderedList(listItem(unorderedList(listItem(orderedList(listItem(paragraph("foo")), startFrom = 2))))) ) } @@ -7215,7 +6689,7 @@ class MarkdownProcessorDocumentParsingTest { | --- | baz """ - .trimMargin(), + .trimMargin() ) /* @@ -7233,7 +6707,7 @@ class MarkdownProcessorDocumentParsingTest { unorderedList( listItem(heading(level = 1, Text("Foo"))), listItem(heading(level = 2, Text("Bar")), paragraph("baz")), - ), + ) ) } @@ -7246,7 +6720,7 @@ class MarkdownProcessorDocumentParsingTest { |- bar |+ baz """ - .trimMargin(), + .trimMargin() ) /* @@ -7260,14 +6734,8 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("foo")), - listItem(paragraph("bar")), - ), - unorderedList( - listItem(paragraph("baz")), - marker = "+", - ), + unorderedList(listItem(paragraph("foo")), listItem(paragraph("bar"))), + unorderedList(listItem(paragraph("baz")), marker = "+"), ) } @@ -7280,7 +6748,7 @@ class MarkdownProcessorDocumentParsingTest { |2. bar |3) baz """ - .trimMargin(), + .trimMargin() ) /* @@ -7294,15 +6762,8 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(paragraph("foo")), - listItem(paragraph("bar")), - ), - orderedList( - listItem(paragraph("baz")), - startFrom = 3, - delimiter = ")", - ), + orderedList(listItem(paragraph("foo")), listItem(paragraph("bar"))), + orderedList(listItem(paragraph("baz")), startFrom = 3, delimiter = ")"), ) } @@ -7315,7 +6776,7 @@ class MarkdownProcessorDocumentParsingTest { |- bar |- baz """ - .trimMargin(), + .trimMargin() ) /* @@ -7326,13 +6787,7 @@ class MarkdownProcessorDocumentParsingTest { *
  • baz
  • * */ - parsed.assertEquals( - paragraph("Foo"), - unorderedList( - listItem(paragraph("bar")), - listItem(paragraph("baz")), - ), - ) + parsed.assertEquals(paragraph("Foo"), unorderedList(listItem(paragraph("bar")), listItem(paragraph("baz")))) } @Test @@ -7343,7 +6798,7 @@ class MarkdownProcessorDocumentParsingTest { |The number of windows in my house is |14. The number of doors is 6. """ - .trimMargin(), + .trimMargin() ) /* @@ -7356,7 +6811,7 @@ class MarkdownProcessorDocumentParsingTest { Text("The number of windows in my house is"), SoftLineBreak, Text("14. The number of doors is 6."), - ), + ) ) } @@ -7368,7 +6823,7 @@ class MarkdownProcessorDocumentParsingTest { |The number of windows in my house is |1. The number of doors is 6. """ - .trimMargin(), + .trimMargin() ) /* @@ -7396,7 +6851,7 @@ class MarkdownProcessorDocumentParsingTest { | |- baz """ - .trimMargin(), + .trimMargin() ) /* @@ -7419,7 +6874,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("bar")), listItem(paragraph("baz")), isTight = false, - ), + ) ) } @@ -7435,7 +6890,7 @@ class MarkdownProcessorDocumentParsingTest { | | bim """ - .trimMargin(), + .trimMargin() ) /* @@ -7462,17 +6917,11 @@ class MarkdownProcessorDocumentParsingTest { unorderedList( listItem( paragraph("bar"), - unorderedList( - listItem( - paragraph("baz"), - paragraph("bim"), - ), - isTight = false, - ), - ), + unorderedList(listItem(paragraph("baz"), paragraph("bim")), isTight = false), + ) ), - ), - ), + ) + ) ) } @@ -7489,7 +6938,7 @@ class MarkdownProcessorDocumentParsingTest { |- baz |- bim """ - .trimMargin(), + .trimMargin() ) /* @@ -7505,15 +6954,9 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("foo")), - listItem(paragraph("bar")), - ), + unorderedList(listItem(paragraph("foo")), listItem(paragraph("bar"))), htmlBlock(""), - unorderedList( - listItem(paragraph("baz")), - listItem(paragraph("bim")), - ), + unorderedList(listItem(paragraph("baz")), listItem(paragraph("bim"))), ) } @@ -7532,7 +6975,7 @@ class MarkdownProcessorDocumentParsingTest { | | code """ - .trimMargin(), + .trimMargin() ) /* @@ -7574,7 +7017,7 @@ class MarkdownProcessorDocumentParsingTest { | - f |- g """ - .trimMargin(), + .trimMargin() ) /* @@ -7598,7 +7041,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("e")), listItem(paragraph("f")), listItem(paragraph("g")), - ), + ) ) } @@ -7613,7 +7056,7 @@ class MarkdownProcessorDocumentParsingTest { | | 3. c """ - .trimMargin(), + .trimMargin() ) /* @@ -7631,12 +7074,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(paragraph("a")), - listItem(paragraph("b")), - listItem(paragraph("c")), - isTight = false, - ), + orderedList(listItem(paragraph("a")), listItem(paragraph("b")), listItem(paragraph("c")), isTight = false) ) } @@ -7651,7 +7089,7 @@ class MarkdownProcessorDocumentParsingTest { | - d | - e """ - .trimMargin(), + .trimMargin() ) /* @@ -7670,7 +7108,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("b")), listItem(paragraph("c")), listItem(Paragraph(Text("d"), SoftLineBreak, Text("- e"))), - ), + ) ) } @@ -7685,7 +7123,7 @@ class MarkdownProcessorDocumentParsingTest { | | 3. c """ - .trimMargin(), + .trimMargin() ) /* @@ -7702,11 +7140,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - orderedList( - listItem(paragraph("a")), - listItem(paragraph("b")), - isTight = false, - ), + orderedList(listItem(paragraph("a")), listItem(paragraph("b")), isTight = false), indentedCodeBlock("3. c"), ) } @@ -7721,7 +7155,7 @@ class MarkdownProcessorDocumentParsingTest { | |- c """ - .trimMargin(), + .trimMargin() ) /* @@ -7739,12 +7173,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("a")), - listItem(paragraph("b")), - listItem(paragraph("c")), - isTight = false, - ), + unorderedList(listItem(paragraph("a")), listItem(paragraph("b")), listItem(paragraph("c")), isTight = false) ) } @@ -7758,7 +7187,7 @@ class MarkdownProcessorDocumentParsingTest { | |* c """ - .trimMargin(), + .trimMargin() ) /* @@ -7774,13 +7203,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("a")), - listItem(), - listItem(paragraph("c")), - isTight = false, - marker = "*", - ), + unorderedList(listItem(paragraph("a")), listItem(), listItem(paragraph("c")), isTight = false, marker = "*") ) } @@ -7795,7 +7218,7 @@ class MarkdownProcessorDocumentParsingTest { | c |- d """ - .trimMargin(), + .trimMargin() ) /* @@ -7819,7 +7242,7 @@ class MarkdownProcessorDocumentParsingTest { listItem(paragraph("b"), paragraph("c")), listItem(paragraph("d")), isTight = false, - ), + ) ) } @@ -7834,7 +7257,7 @@ class MarkdownProcessorDocumentParsingTest { | [ref]: /url |- d """ - .trimMargin(), + .trimMargin() ) /* @@ -7852,12 +7275,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("a")), - listItem(paragraph("b")), - listItem(paragraph("d")), - isTight = false, - ), + unorderedList(listItem(paragraph("a")), listItem(paragraph("b")), listItem(paragraph("d")), isTight = false) ) } @@ -7874,7 +7292,7 @@ class MarkdownProcessorDocumentParsingTest { | ``` |- c """ - .trimMargin(), + .trimMargin() ) /* @@ -7891,11 +7309,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("a")), - listItem(fencedCodeBlock("b")), - listItem(paragraph("c")), - ), + unorderedList(listItem(paragraph("a")), listItem(fencedCodeBlock("b")), listItem(paragraph("c"))) ) } @@ -7910,7 +7324,7 @@ class MarkdownProcessorDocumentParsingTest { | c |- d """ - .trimMargin(), + .trimMargin() ) /* @@ -7929,18 +7343,9 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( unorderedList( - listItem( - paragraph("a"), - unorderedList( - listItem( - paragraph("b"), - paragraph("c"), - ), - isTight = false, - ), - ), + listItem(paragraph("a"), unorderedList(listItem(paragraph("b"), paragraph("c")), isTight = false)), listItem(paragraph("d")), - ), + ) ) } @@ -7954,7 +7359,7 @@ class MarkdownProcessorDocumentParsingTest { | > |* c """ - .trimMargin(), + .trimMargin() ) /* @@ -7969,11 +7374,7 @@ class MarkdownProcessorDocumentParsingTest { * */ parsed.assertEquals( - unorderedList( - listItem(paragraph("a"), blockQuote(paragraph("b"))), - listItem(paragraph("c")), - marker = "*", - ), + unorderedList(listItem(paragraph("a"), blockQuote(paragraph("b"))), listItem(paragraph("c")), marker = "*") ) } @@ -7989,7 +7390,7 @@ class MarkdownProcessorDocumentParsingTest { | ``` |- d """ - .trimMargin(), + .trimMargin() ) /* @@ -8007,13 +7408,9 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( unorderedList( - listItem( - paragraph("a"), - blockQuote(paragraph("b")), - fencedCodeBlock("c"), - ), + listItem(paragraph("a"), blockQuote(paragraph("b")), fencedCodeBlock("c")), listItem(paragraph("d")), - ), + ) ) } @@ -8038,7 +7435,7 @@ class MarkdownProcessorDocumentParsingTest { |- a | - b """ - .trimMargin(), + .trimMargin() ) /* @@ -8051,14 +7448,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - unorderedList( - listItem( - paragraph("a"), - unorderedList(listItem(paragraph("b"))), - ), - ), - ) + parsed.assertEquals(unorderedList(listItem(paragraph("a"), unorderedList(listItem(paragraph("b")))))) } @Test @@ -8072,7 +7462,7 @@ class MarkdownProcessorDocumentParsingTest { | | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -8085,15 +7475,7 @@ class MarkdownProcessorDocumentParsingTest { * * */ - parsed.assertEquals( - orderedList( - listItem( - fencedCodeBlock("foo"), - paragraph("bar"), - ), - isTight = false, - ), - ) + parsed.assertEquals(orderedList(listItem(fencedCodeBlock("foo"), paragraph("bar")), isTight = false)) } @Test @@ -8106,7 +7488,7 @@ class MarkdownProcessorDocumentParsingTest { | | baz """ - .trimMargin(), + .trimMargin() ) /* @@ -8123,17 +7505,10 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( unorderedList( - listItem( - paragraph("foo"), - unorderedList( - listItem(paragraph("bar")), - marker = "*", - ), - paragraph("baz"), - ), + listItem(paragraph("foo"), unorderedList(listItem(paragraph("bar")), marker = "*"), paragraph("baz")), marker = "*", isTight = false, - ), + ) ) } @@ -8150,7 +7525,7 @@ class MarkdownProcessorDocumentParsingTest { | - e | - f """ - .trimMargin(), + .trimMargin() ) /* @@ -8174,22 +7549,10 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( unorderedList( - listItem( - paragraph("a"), - unorderedList( - listItem(paragraph("b")), - listItem(paragraph("c")), - ), - ), - listItem( - paragraph("d"), - unorderedList( - listItem(paragraph("e")), - listItem(paragraph("f")), - ), - ), + listItem(paragraph("a"), unorderedList(listItem(paragraph("b")), listItem(paragraph("c")))), + listItem(paragraph("d"), unorderedList(listItem(paragraph("e")), listItem(paragraph("f")))), isTight = false, - ), + ) ) } @@ -8278,7 +7641,7 @@ class MarkdownProcessorDocumentParsingTest { |` ` |` ` """ - .trimMargin(), + .trimMargin() ) /* @@ -8300,7 +7663,7 @@ class MarkdownProcessorDocumentParsingTest { |baz |`` """ - .trimMargin(), + .trimMargin() ) /* @@ -8319,7 +7682,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |`` """ - .trimMargin(), + .trimMargin() ) /* @@ -8337,7 +7700,7 @@ class MarkdownProcessorDocumentParsingTest { |`foo bar |baz` """ - .trimMargin(), + .trimMargin() ) /* @@ -8444,10 +7807,7 @@ class MarkdownProcessorDocumentParsingTest { *

    https://foo.bar.`baz`

    */ parsed.assertEquals( - Paragraph( - Link(destination = "https://foo.bar.`baz", title = null, Text("https://foo.bar.`baz")), - Text("`"), - ), + Paragraph(Link(destination = "https://foo.bar.`baz", title = null, Text("https://foo.bar.`baz")), Text("`")) ) } @@ -8538,7 +7898,8 @@ class MarkdownProcessorDocumentParsingTest { |*£*bravo. | |*€*charlie. - """.trimMargin(), + """ + .trimMargin() ) /* @@ -8547,11 +7908,7 @@ class MarkdownProcessorDocumentParsingTest { *

    *£*bravo.

    *

    *€*charlie.

    */ - parsed.assertEquals( - paragraph("*$*alpha."), - paragraph("*£*bravo."), - paragraph("*€*charlie."), - ) + parsed.assertEquals(paragraph("*$*alpha."), paragraph("*£*bravo."), paragraph("*€*charlie.")) } @Test @@ -8573,13 +7930,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    5678

    */ - parsed.assertEquals( - Paragraph( - Text("5"), - Emphasis("*", Text("6")), - Text("78"), - ), - ) + parsed.assertEquals(Paragraph(Text("5"), Emphasis("*", Text("6")), Text("78"))) } @Test @@ -8700,7 +8051,7 @@ class MarkdownProcessorDocumentParsingTest { |*foo bar |* """ - .trimMargin(), + .trimMargin() ) /* @@ -8730,16 +8081,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (foo)

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("("), - Emphasis("*", Text("foo")), - Text(")"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("("), Emphasis("*", Text("foo")), Text(")")))) } @Test @@ -8783,16 +8125,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (foo)

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Text("("), - Emphasis("_", Text("foo")), - Text(")"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("("), Emphasis("_", Text("foo")), Text(")")))) } @Test @@ -8836,12 +8169,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (bar).

    */ - parsed.assertEquals( - Paragraph( - Emphasis("_", Text("(bar)")), - Text("."), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("(bar)")), Text("."))) } @Test @@ -8885,12 +8213,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobar

    */ - parsed.assertEquals( - Paragraph( - Text("foo"), - StrongEmphasis("**", Text("bar")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo"), StrongEmphasis("**", Text("bar")))) } @Test @@ -8923,7 +8246,7 @@ class MarkdownProcessorDocumentParsingTest { |__ |foo bar__ """ - .trimMargin(), + .trimMargin() ) /* @@ -8987,14 +8310,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo, bar, baz

    */ parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - Text("foo, "), - StrongEmphasis("__", Text("bar")), - Text(", baz"), - ), - ), + Paragraph(StrongEmphasis("__", Text("foo, "), StrongEmphasis("__", Text("bar")), Text(", baz"))) ) } @@ -9006,12 +8322,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo-(bar)

    */ - parsed.assertEquals( - Paragraph( - Text("foo-"), - StrongEmphasis("__", Text("(bar)")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo-"), StrongEmphasis("__", Text("(bar)")))) } @Test @@ -9044,16 +8355,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (foo)

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("("), - StrongEmphasis("**", Text("foo")), - Text(")"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("("), StrongEmphasis("**", Text("foo")), Text(")")))) } @Test @@ -9064,7 +8366,7 @@ class MarkdownProcessorDocumentParsingTest { |**Gomphocarpus (*Gomphocarpus physocarpus*, syn. |*Asclepias physocarpa*)** """ - .trimMargin(), + .trimMargin() ) /* @@ -9082,8 +8384,8 @@ class MarkdownProcessorDocumentParsingTest { SoftLineBreak, Emphasis("*", Text("Asclepias physocarpa")), Text(")"), - ), - ), + ) + ) ) } @@ -9095,16 +8397,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo "bar" foo

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo \""), - Emphasis("*", Text("bar")), - Text("\" foo"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo \""), Emphasis("*", Text("bar")), Text("\" foo")))) } @Test @@ -9115,12 +8408,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis("**", Text("foo")), - Text("bar"), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo")), Text("bar"))) } @Test @@ -9153,16 +8441,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (foo)

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Text("("), - StrongEmphasis("__", Text("foo")), - Text(")"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("("), StrongEmphasis("__", Text("foo")), Text(")")))) } @Test @@ -9206,12 +8485,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    (bar).

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis("__", Text("(bar)")), - Text("."), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", Text("(bar)")), Text("."))) } @Test @@ -9223,13 +8497,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar

    */ parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - Link(destination = "/url", title = null, Text("bar")), - ), - ), + Paragraph(Emphasis("*", Text("foo "), Link(destination = "/url", title = null, Text("bar")))) ) } @@ -9241,7 +8509,7 @@ class MarkdownProcessorDocumentParsingTest { |*foo |bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -9249,16 +8517,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo * bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo"), - SoftLineBreak, - Text("bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo"), SoftLineBreak, Text("bar")))) } @Test @@ -9269,16 +8528,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar baz

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Text("foo "), - StrongEmphasis("__", Text("bar")), - Text(" baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("foo "), StrongEmphasis("__", Text("bar")), Text(" baz")))) } @Test @@ -9289,16 +8539,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar baz

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Text("foo "), - Emphasis("_", Text("bar")), - Text(" baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("foo "), Emphasis("_", Text("bar")), Text(" baz")))) } @Test @@ -9309,15 +8550,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Emphasis("_", Text("foo")), - Text(" bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Emphasis("_", Text("foo")), Text(" bar")))) } @Test @@ -9328,15 +8561,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - Emphasis("*", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo "), Emphasis("*", Text("bar"))))) } @Test @@ -9347,16 +8572,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar baz

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - StrongEmphasis("**", Text("bar")), - Text(" baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo "), StrongEmphasis("**", Text("bar")), Text(" baz")))) } @Test @@ -9367,16 +8583,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobarbaz

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo"), - StrongEmphasis("**", Text("bar")), - Text("baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo"), StrongEmphasis("**", Text("bar")), Text("baz")))) } @Test @@ -9398,15 +8605,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - StrongEmphasis("**", Text("foo")), - Text(" bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", StrongEmphasis("**", Text("foo")), Text(" bar")))) } @Test @@ -9417,15 +8616,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - StrongEmphasis("**", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo "), StrongEmphasis("**", Text("bar"))))) } @Test @@ -9436,15 +8627,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo"), - StrongEmphasis("**", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo"), StrongEmphasis("**", Text("bar"))))) } @Test @@ -9455,16 +8638,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobarbaz

    */ - parsed.assertEquals( - Paragraph( - Text("foo"), - Emphasis( - "*", - StrongEmphasis("**", Text("bar")), - ), - Text("baz"), - ), - ) + parsed.assertEquals(Paragraph(Text("foo"), Emphasis("*", StrongEmphasis("**", Text("bar"))), Text("baz"))) } @Test @@ -9478,12 +8652,9 @@ class MarkdownProcessorDocumentParsingTest { parsed.assertEquals( Paragraph( Text("foo"), - StrongEmphasis( - "**", - StrongEmphasis("**", StrongEmphasis("**", Text("bar"))), - ), + StrongEmphasis("**", StrongEmphasis("**", StrongEmphasis("**", Text("bar")))), Text("***baz"), - ), + ) ) } @@ -9500,15 +8671,10 @@ class MarkdownProcessorDocumentParsingTest { Emphasis( "*", Text("foo "), - StrongEmphasis( - "**", - Text("bar "), - Emphasis("*", Text("baz")), - Text(" bim"), - ), + StrongEmphasis("**", Text("bar "), Emphasis("*", Text("baz")), Text(" bim")), Text(" bop"), - ), - ), + ) + ) ) } @@ -9521,13 +8687,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar

    */ parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - Link(destination = "/url", title = null, Emphasis("*", Text("bar"))), - ), - ), + Paragraph(Emphasis("*", Text("foo "), Link(destination = "/url", title = null, Emphasis("*", Text("bar"))))) ) } @@ -9562,13 +8722,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar

    */ parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Link(destination = "/url", title = null, Text("bar")), - ), - ), + Paragraph(StrongEmphasis("**", Text("foo "), Link(destination = "/url", title = null, Text("bar")))) ) } @@ -9580,7 +8734,7 @@ class MarkdownProcessorDocumentParsingTest { |**foo |bar** """ - .trimMargin(), + .trimMargin() ) /* @@ -9588,16 +8742,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo * bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo"), - SoftLineBreak, - Text("bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo"), SoftLineBreak, Text("bar")))) } @Test @@ -9608,16 +8753,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar baz

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - Text("foo "), - Emphasis("_", Text("bar")), - Text(" baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", Text("foo "), Emphasis("_", Text("bar")), Text(" baz")))) } @Test @@ -9629,14 +8765,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar baz

    */ parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - Text("foo "), - StrongEmphasis("__", Text("bar")), - Text(" baz"), - ), - ), + Paragraph(StrongEmphasis("__", Text("foo "), StrongEmphasis("__", Text("bar")), Text(" baz"))) ) } @@ -9648,15 +8777,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - StrongEmphasis("__", Text("foo")), - Text(" bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", StrongEmphasis("__", Text("foo")), Text(" bar")))) } @Test @@ -9667,15 +8788,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - StrongEmphasis("**", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo "), StrongEmphasis("**", Text("bar"))))) } @Test @@ -9686,16 +8799,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar baz

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Emphasis("*", Text("bar")), - Text(" baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo "), Emphasis("*", Text("bar")), Text(" baz")))) } @Test @@ -9706,16 +8810,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foobarbaz

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo"), - Emphasis("*", Text("bar")), - Text("baz"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo"), Emphasis("*", Text("bar")), Text("baz")))) } @Test @@ -9726,15 +8821,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Emphasis("*", Text("foo")), - Text(" bar"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Emphasis("*", Text("foo")), Text(" bar")))) } @Test @@ -9745,15 +8832,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Emphasis("*", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo "), Emphasis("*", Text("bar"))))) } @Test @@ -9764,7 +8843,7 @@ class MarkdownProcessorDocumentParsingTest { |**foo *bar **baz** |bim* bop** """ - .trimMargin(), + .trimMargin() ) /* @@ -9777,16 +8856,10 @@ class MarkdownProcessorDocumentParsingTest { StrongEmphasis( "**", Text("foo "), - Emphasis( - "*", - Text("bar "), - StrongEmphasis("**", Text("baz")), - SoftLineBreak, - Text("bim"), - ), + Emphasis("*", Text("bar "), StrongEmphasis("**", Text("baz")), SoftLineBreak, Text("bim")), Text(" bop"), - ), - ), + ) + ) ) } @@ -9800,12 +8873,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( Paragraph( - StrongEmphasis( - "**", - Text("foo "), - Link(destination = "/url", title = null, Emphasis("*", Text("bar"))), - ), - ), + StrongEmphasis("**", Text("foo "), Link(destination = "/url", title = null, Emphasis("*", Text("bar")))) + ) ) } @@ -9850,12 +8919,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo *

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - Emphasis("*", Text("*")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), Emphasis("*", Text("*")))) } @Test @@ -9866,12 +8930,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo _

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - Emphasis("*", Text("_")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), Emphasis("*", Text("_")))) } @Test @@ -9893,12 +8952,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo *

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - StrongEmphasis("**", Text("*")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), StrongEmphasis("**", Text("*")))) } @Test @@ -9909,12 +8963,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo _

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - StrongEmphasis("**", Text("_")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), StrongEmphasis("**", Text("_")))) } @Test @@ -9925,12 +8974,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *foo

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - Emphasis("*", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), Emphasis("*", Text("foo")))) } @Test @@ -9941,12 +8985,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo*

    */ - parsed.assertEquals( - Paragraph( - Emphasis("*", Text("foo")), - Text("*"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo")), Text("*"))) } @Test @@ -9957,12 +8996,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *foo

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - StrongEmphasis("**", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), StrongEmphasis("**", Text("foo")))) } @Test @@ -9973,12 +9007,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    ***foo

    */ - parsed.assertEquals( - Paragraph( - Text("***"), - Emphasis("*", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("***"), Emphasis("*", Text("foo")))) } @Test @@ -9989,12 +9018,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo*

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis("**", Text("foo")), - Text("*"), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", Text("foo")), Text("*"))) } @Test @@ -10005,12 +9029,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo***

    */ - parsed.assertEquals( - Paragraph( - Emphasis("*", Text("foo")), - Text("***"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo")), Text("***"))) } @Test @@ -10032,12 +9051,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo _

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - Emphasis("_", Text("_")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), Emphasis("_", Text("_")))) } @Test @@ -10048,12 +9062,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo *

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - Emphasis("_", Text("*")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), Emphasis("_", Text("*")))) } @Test @@ -10075,12 +9084,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo _

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - StrongEmphasis("__", Text("_")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), StrongEmphasis("__", Text("_")))) } @Test @@ -10091,12 +9095,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo *

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - StrongEmphasis("__", Text("*")), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), StrongEmphasis("__", Text("*")))) } @Test @@ -10107,12 +9106,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    _foo

    */ - parsed.assertEquals( - Paragraph( - Text("_"), - Emphasis("_", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("_"), Emphasis("_", Text("foo")))) } @Test @@ -10123,12 +9117,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo_

    */ - parsed.assertEquals( - Paragraph( - Emphasis("_", Text("foo")), - Text("_"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("foo")), Text("_"))) } @Test @@ -10139,12 +9128,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    _foo

    */ - parsed.assertEquals( - Paragraph( - Text("_"), - StrongEmphasis("__", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("_"), StrongEmphasis("__", Text("foo")))) } @Test @@ -10155,12 +9139,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    ___foo

    */ - parsed.assertEquals( - Paragraph( - Text("___"), - Emphasis("_", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("___"), Emphasis("_", Text("foo")))) } @Test @@ -10171,12 +9150,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo_

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis("__", Text("foo")), - Text("_"), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", Text("foo")), Text("_"))) } @Test @@ -10187,12 +9161,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo___

    */ - parsed.assertEquals( - Paragraph( - Emphasis("_", Text("foo")), - Text("___"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("foo")), Text("___"))) } @Test @@ -10214,14 +9183,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Emphasis("_", Text("foo")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Emphasis("_", Text("foo"))))) } @Test @@ -10243,18 +9205,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Emphasis( - "*", - Text("foo "), - Emphasis("_", Text("bar")), - ), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Emphasis("*", Text("foo "), Emphasis("_", Text("bar")))))) } @Test @@ -10265,15 +9216,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - Text("foo "), - Emphasis("_", Text("bar")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", Text("foo "), Emphasis("_", Text("bar"))))) } @Test @@ -10285,17 +9228,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar a

    */ parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Emphasis( - "*", - Text("foo "), - Emphasis("_", Text("bar")), - Text(" a"), - ), - ), - ), + Paragraph(Emphasis("_", Emphasis("*", Text("foo "), Emphasis("_", Text("bar")), Text(" a")))) ) } @@ -10307,16 +9240,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo bar a

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - Text("foo "), - Emphasis("_", Text("bar")), - Text(" a"), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", Text("foo "), Emphasis("_", Text("bar")), Text(" a")))) } @Test @@ -10328,17 +9252,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar a

    */ parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Emphasis( - "*", - Text("foo "), - Emphasis("*", Text("bar")), - Text(" a"), - ), - ), - ), + Paragraph(Emphasis("_", Emphasis("*", Text("foo "), Emphasis("*", Text("bar")), Text(" a")))) ) } @@ -10350,14 +9264,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Emphasis("*", Text("foo")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Emphasis("*", Text("foo"))))) } @Test @@ -10368,14 +9275,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - StrongEmphasis("**", Text("foo")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", StrongEmphasis("**", Text("foo"))))) } @Test @@ -10386,14 +9286,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "__", - StrongEmphasis("__", Text("foo")), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("__", StrongEmphasis("__", Text("foo"))))) } @Test @@ -10404,14 +9297,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - StrongEmphasis( - "**", - StrongEmphasis("**", StrongEmphasis("**", Text("foo"))), - ), - ), - ) + parsed.assertEquals(Paragraph(StrongEmphasis("**", StrongEmphasis("**", StrongEmphasis("**", Text("foo")))))) } @Test @@ -10422,14 +9308,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - StrongEmphasis("**", Text("foo")), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", StrongEmphasis("**", Text("foo"))))) } @Test @@ -10440,14 +9319,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - StrongEmphasis("__", StrongEmphasis("__", Text("foo"))), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", StrongEmphasis("__", StrongEmphasis("__", Text("foo")))))) } @Test @@ -10458,12 +9330,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo _bar baz_

    */ - parsed.assertEquals( - Paragraph( - Emphasis("*", Text("foo _bar")), - Text(" baz_"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo _bar")), Text(" baz_"))) } @Test @@ -10475,14 +9342,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar *baz bim bam

    */ parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo "), - StrongEmphasis("__", Text("bar *baz bim")), - Text(" bam"), - ), - ), + Paragraph(Emphasis("*", Text("foo "), StrongEmphasis("__", Text("bar *baz bim")), Text(" bam"))) ) } @@ -10494,12 +9354,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    **foo bar baz

    */ - parsed.assertEquals( - Paragraph( - Text("**foo "), - StrongEmphasis("**", Text("bar baz")), - ), - ) + parsed.assertEquals(Paragraph(Text("**foo "), StrongEmphasis("**", Text("bar baz")))) } @Test @@ -10510,12 +9365,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *foo bar baz

    */ - parsed.assertEquals( - Paragraph( - Text("*foo "), - Emphasis("*", Text("bar baz")), - ), - ) + parsed.assertEquals(Paragraph(Text("*foo "), Emphasis("*", Text("bar baz")))) } @Test @@ -10526,12 +9376,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *bar*

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - Link(destination = "/url", title = null, Text("bar*")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), Link(destination = "/url", title = null, Text("bar*")))) } @Test @@ -10542,12 +9387,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    _foo bar_

    */ - parsed.assertEquals( - Paragraph( - Text("_foo "), - Link(destination = "/url", title = null, Text("bar_")), - ), - ) + parsed.assertEquals(Paragraph(Text("_foo "), Link(destination = "/url", title = null, Text("bar_")))) } @Test @@ -10558,12 +9398,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), HtmlInline(""))) } @Test @@ -10574,12 +9409,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    **

    */ - parsed.assertEquals( - Paragraph( - Text("**"), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("**"), HtmlInline(""))) } @Test @@ -10590,12 +9420,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    __

    */ - parsed.assertEquals( - Paragraph( - Text("__"), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("__"), HtmlInline(""))) } @Test @@ -10606,15 +9431,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    a *

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("a "), - Code("*"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("a "), Code("*")))) } @Test @@ -10625,15 +9442,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    a _

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "_", - Text("a "), - Code("_"), - ), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("_", Text("a "), Code("_")))) } @Test @@ -10648,7 +9457,7 @@ class MarkdownProcessorDocumentParsingTest { Paragraph( Text("**a"), Link(destination = "https://foo.bar/?q=**", title = null, Text("https://foo.bar/?q=**")), - ), + ) ) } @@ -10664,7 +9473,7 @@ class MarkdownProcessorDocumentParsingTest { Paragraph( Text("__a"), Link(destination = "https://foo.bar/?q=__", title = null, Text("https://foo.bar/?q=__")), - ), + ) ) } @@ -10764,7 +9573,7 @@ class MarkdownProcessorDocumentParsingTest { |[link](foo |bar) """ - .trimMargin(), + .trimMargin() ) /* @@ -10783,7 +9592,7 @@ class MarkdownProcessorDocumentParsingTest { |[link]() """ - .trimMargin(), + .trimMargin() ) /* @@ -10825,7 +9634,7 @@ class MarkdownProcessorDocumentParsingTest { |[a]( |[a](c) """ - .trimMargin(), + .trimMargin() ) /* @@ -10843,7 +9652,7 @@ class MarkdownProcessorDocumentParsingTest { Text(content = "[a]("), HtmlInline(content = ""), Text(content = "c)"), - ), + ) ) } @@ -10924,7 +9733,7 @@ class MarkdownProcessorDocumentParsingTest { | |[link](https://example.com?foo=3#frag) """ - .trimMargin(), + .trimMargin() ) /* @@ -10982,7 +9791,7 @@ class MarkdownProcessorDocumentParsingTest { |[link](/url 'title') |[link](/url (title)) """ - .trimMargin(), + .trimMargin() ) /* @@ -10998,7 +9807,7 @@ class MarkdownProcessorDocumentParsingTest { Link(destination = "/url", title = "title", Text("link")), SoftLineBreak, Link(destination = "/url", title = "title", Text("link")), - ), + ) ) } @@ -11054,7 +9863,7 @@ class MarkdownProcessorDocumentParsingTest { |[link]( /uri | "title" ) """ - .trimMargin(), + .trimMargin() ) /* @@ -11105,12 +9914,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    [link bar

    */ - parsed.assertEquals( - Paragraph( - Text("[link "), - Link(destination = "/uri", title = null, Text("bar")), - ), - ) + parsed.assertEquals(Paragraph(Text("[link "), Link(destination = "/uri", title = null, Text("bar")))) } @Test @@ -11138,15 +9942,9 @@ class MarkdownProcessorDocumentParsingTest { destination = "/uri", title = null, Text("link "), - Emphasis( - "*", - Text("foo "), - StrongEmphasis("**", Text("bar")), - Text(" "), - Code("#"), - ), - ), - ), + Emphasis("*", Text("foo "), StrongEmphasis("**", Text("bar")), Text(" "), Code("#")), + ) + ) ) } @@ -11164,8 +9962,8 @@ class MarkdownProcessorDocumentParsingTest { destination = "/uri", title = null, Image(source = "moon.jpg", alt = "moon", title = null, Text("moon")), - ), - ), + ) + ) ) } @@ -11178,11 +9976,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [foo bar](/uri)

    */ parsed.assertEquals( - Paragraph( - Text("[foo "), - Link(destination = "/uri", title = null, Text("bar")), - Text("](/uri)"), - ), + Paragraph(Text("[foo "), Link(destination = "/uri", title = null, Text("bar")), Text("](/uri)")) ) } @@ -11197,14 +9991,9 @@ class MarkdownProcessorDocumentParsingTest { parsed.assertEquals( Paragraph( Text("[foo "), - Emphasis( - "*", - Text("[bar "), - Link(destination = "/uri", title = null, Text("baz")), - Text("](/uri)"), - ), + Emphasis("*", Text("[bar "), Link(destination = "/uri", title = null, Text("baz")), Text("](/uri)")), Text("](/uri)"), - ), + ) ) } @@ -11225,8 +10014,8 @@ class MarkdownProcessorDocumentParsingTest { Text("["), Link(destination = "uri1", title = null, Text("foo")), Text("](uri2)"), - ), - ), + ) + ) ) } @@ -11238,12 +10027,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    *foo*

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - Link(destination = "/uri", title = null, Text("foo*")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), Link(destination = "/uri", title = null, Text("foo*")))) } @Test @@ -11265,15 +10049,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo [bar baz]

    */ - parsed.assertEquals( - Paragraph( - Emphasis( - "*", - Text("foo [bar"), - ), - Text(" baz]"), - ), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo [bar")), Text(" baz]"))) } @Test @@ -11295,12 +10071,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    [foo](/uri)

    */ - parsed.assertEquals( - Paragraph( - Text("[foo"), - Code("](/uri)"), - ), - ) + parsed.assertEquals(Paragraph(Text("[foo"), Code("](/uri)"))) } @Test @@ -11319,7 +10090,7 @@ class MarkdownProcessorDocumentParsingTest { title = null, Text("https://example.com/?search=](uri)"), ), - ), + ) ) } @@ -11332,7 +10103,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11351,7 +10122,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11370,7 +10141,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11389,7 +10160,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11402,15 +10173,9 @@ class MarkdownProcessorDocumentParsingTest { destination = "/uri", title = null, Text("link "), - Emphasis( - "*", - Text("foo "), - StrongEmphasis("**", Text("bar")), - Text(" "), - Code("#"), - ), - ), - ), + Emphasis("*", Text("foo "), StrongEmphasis("**", Text("bar")), Text(" "), Code("#")), + ) + ) ) } @@ -11423,7 +10188,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11436,8 +10201,8 @@ class MarkdownProcessorDocumentParsingTest { destination = "/uri", title = null, Image(source = "moon.jpg", alt = "moon", title = null, Text("moon")), - ), - ), + ) + ) ) } @@ -11450,7 +10215,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11463,7 +10228,7 @@ class MarkdownProcessorDocumentParsingTest { Link(destination = "/uri", title = null, Text("bar")), Text("]"), Link(destination = "/uri", title = null, Text("ref")), - ), + ) ) } @@ -11476,7 +10241,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11486,14 +10251,10 @@ class MarkdownProcessorDocumentParsingTest { parsed.assertEquals( Paragraph( Text("[foo "), - Emphasis( - "*", - Text("bar "), - Link("/uri", null, Text("baz")), - ), + Emphasis("*", Text("bar "), Link("/uri", null, Text("baz"))), Text("]"), Link(destination = "/uri", title = null, Text("ref")), - ), + ) ) } @@ -11506,19 +10267,14 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    *foo*

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - Link(destination = "/uri", title = null, Text("foo*")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), Link(destination = "/uri", title = null, Text("foo*")))) } @Test @@ -11530,19 +10286,14 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    foo *bar*

    */ - parsed.assertEquals( - Paragraph( - Link(destination = "/uri", title = null, Text("foo *bar")), - Text("*"), - ), - ) + parsed.assertEquals(Paragraph(Link(destination = "/uri", title = null, Text("foo *bar")), Text("*"))) } @Test @@ -11554,7 +10305,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11573,7 +10324,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11592,7 +10343,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11607,7 +10358,7 @@ class MarkdownProcessorDocumentParsingTest { title = null, Text("https://example.com/?search=][ref]"), ), - ), + ) ) } @@ -11620,7 +10371,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11639,7 +10390,7 @@ class MarkdownProcessorDocumentParsingTest { | |[SS]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -11659,7 +10410,7 @@ class MarkdownProcessorDocumentParsingTest { | |[Baz][Foo bar] """ - .trimMargin(), + .trimMargin() ) /* @@ -11678,19 +10429,14 @@ class MarkdownProcessorDocumentParsingTest { | |[bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    [foo] bar

    */ - parsed.assertEquals( - Paragraph( - Text("[foo] "), - Link(destination = "/url", title = "title", Text("bar")), - ), - ) + parsed.assertEquals(Paragraph(Text("[foo] "), Link(destination = "/url", title = "title", Text("bar")))) } @Test @@ -11703,7 +10449,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11712,11 +10458,7 @@ class MarkdownProcessorDocumentParsingTest { * bar

    */ parsed.assertEquals( - Paragraph( - Text("[foo]"), - SoftLineBreak, - Link(destination = "/url", title = "title", Text("bar")), - ), + Paragraph(Text("[foo]"), SoftLineBreak, Link(destination = "/url", title = "title", Text("bar"))) ) } @@ -11731,7 +10473,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar][foo] """ - .trimMargin(), + .trimMargin() ) /* @@ -11750,7 +10492,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo!]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -11769,7 +10511,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref[]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11777,10 +10519,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [foo][ref[]

    *

    [ref[]: /uri

    */ - parsed.assertEquals( - paragraph("[foo][ref[]"), - paragraph("[ref[]: /uri"), - ) + parsed.assertEquals(paragraph("[foo][ref[]"), paragraph("[ref[]: /uri")) } @Test @@ -11792,7 +10531,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref[bar]]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11800,10 +10539,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [foo][ref[bar]]

    *

    [ref[bar]]: /uri

    */ - parsed.assertEquals( - paragraph("[foo][ref[bar]]"), - paragraph("[ref[bar]]: /uri"), - ) + parsed.assertEquals(paragraph("[foo][ref[bar]]"), paragraph("[ref[bar]]: /uri")) } @Test @@ -11815,7 +10551,7 @@ class MarkdownProcessorDocumentParsingTest { | |[[[foo]]]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -11823,10 +10559,7 @@ class MarkdownProcessorDocumentParsingTest { *

    [[[foo]]]

    *

    [[[foo]]]: /url

    */ - parsed.assertEquals( - paragraph("[[[foo]]]"), - paragraph("[[[foo]]]: /url"), - ) + parsed.assertEquals(paragraph("[[[foo]]]"), paragraph("[[[foo]]]: /url")) } @Test @@ -11838,7 +10571,7 @@ class MarkdownProcessorDocumentParsingTest { | |[ref\[]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11857,7 +10590,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar\\] """ - .trimMargin(), + .trimMargin() ) /* @@ -11876,7 +10609,7 @@ class MarkdownProcessorDocumentParsingTest { | |[]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11884,10 +10617,7 @@ class MarkdownProcessorDocumentParsingTest { *

    []

    *

    []: /uri

    */ - parsed.assertEquals( - paragraph("[]"), - paragraph("[]: /uri"), - ) + parsed.assertEquals(paragraph("[]"), paragraph("[]: /uri")) } @Test @@ -11901,7 +10631,7 @@ class MarkdownProcessorDocumentParsingTest { |[ | ]: /uri """ - .trimMargin(), + .trimMargin() ) /* @@ -11926,7 +10656,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11945,7 +10675,7 @@ class MarkdownProcessorDocumentParsingTest { | |[*foo* bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11953,14 +10683,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "/url", - title = "title", - Emphasis("*", Text("foo")), - Text(" bar"), - ), - ), + Paragraph(Link(destination = "/url", title = "title", Emphasis("*", Text("foo")), Text(" bar"))) ) } @@ -11973,7 +10696,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -11993,7 +10716,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12007,7 +10730,7 @@ class MarkdownProcessorDocumentParsingTest { Text(""), // This looks wrong but apparently is correct SoftLineBreak, Text("[]"), - ), + ) ) } @@ -12020,7 +10743,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12039,7 +10762,7 @@ class MarkdownProcessorDocumentParsingTest { | |[*foo* bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12047,14 +10770,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo bar

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "/url", - title = "title", - Emphasis("*", Text("foo")), - Text(" bar"), - ), - ), + Paragraph(Link(destination = "/url", title = "title", Emphasis("*", Text("foo")), Text(" bar"))) ) } @@ -12067,7 +10783,7 @@ class MarkdownProcessorDocumentParsingTest { | |[*foo* bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12077,14 +10793,9 @@ class MarkdownProcessorDocumentParsingTest { parsed.assertEquals( Paragraph( Text("["), - Link( - destination = "/url", - title = "title", - Emphasis("*", Text("foo")), - Text(" bar"), - ), + Link(destination = "/url", title = "title", Emphasis("*", Text("foo")), Text(" bar")), Text("]"), - ), + ) ) } @@ -12097,19 +10808,14 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    [[bar foo

    */ - parsed.assertEquals( - Paragraph( - Text("[[bar "), - Link(destination = "/url", title = null, Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("[[bar "), Link(destination = "/url", title = null, Text("foo")))) } @Test @@ -12121,7 +10827,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12140,19 +10846,14 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    foo bar

    */ - parsed.assertEquals( - Paragraph( - Link(destination = "/url", title = null, Text("foo")), - Text(" bar"), - ), - ) + parsed.assertEquals(Paragraph(Link(destination = "/url", title = null, Text("foo")), Text(" bar"))) } @Test @@ -12164,7 +10865,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12183,19 +10884,14 @@ class MarkdownProcessorDocumentParsingTest { | |*[foo*] """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    *foo*

    */ - parsed.assertEquals( - Paragraph( - Text("*"), - Link(destination = "/url", title = null, Text("foo*")), - ), - ) + parsed.assertEquals(Paragraph(Text("*"), Link(destination = "/url", title = null, Text("foo*")))) } @Test @@ -12208,7 +10904,7 @@ class MarkdownProcessorDocumentParsingTest { |[foo]: /url1 |[bar]: /url2 """ - .trimMargin(), + .trimMargin() ) /* @@ -12227,7 +10923,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url1 """ - .trimMargin(), + .trimMargin() ) /* @@ -12246,7 +10942,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url1 """ - .trimMargin(), + .trimMargin() ) /* @@ -12265,19 +10961,14 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url1 """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    foo(not a link)

    */ - parsed.assertEquals( - Paragraph( - Link(destination = "/url1", title = null, Text("foo")), - Text("(not a link)"), - ), - ) + parsed.assertEquals(Paragraph(Link(destination = "/url1", title = null, Text("foo")), Text("(not a link)"))) } @Test @@ -12289,19 +10980,14 @@ class MarkdownProcessorDocumentParsingTest { | |[baz]: /url """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    [foo]bar

    */ - parsed.assertEquals( - Paragraph( - Text("[foo]"), - Link(destination = "/url", title = null, Text("bar")), - ), - ) + parsed.assertEquals(Paragraph(Text("[foo]"), Link(destination = "/url", title = null, Text("bar")))) } @Test @@ -12314,7 +11000,7 @@ class MarkdownProcessorDocumentParsingTest { |[baz]: /url1 |[bar]: /url2 """ - .trimMargin(), + .trimMargin() ) /* @@ -12325,7 +11011,7 @@ class MarkdownProcessorDocumentParsingTest { Paragraph( Link(destination = "/url2", title = null, Text("foo")), Link(destination = "/url1", title = null, Text("baz")), - ), + ) ) } @@ -12339,19 +11025,14 @@ class MarkdownProcessorDocumentParsingTest { |[baz]: /url1 |[foo]: /url2 """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    [foo]bar

    */ - parsed.assertEquals( - Paragraph( - Text("[foo]"), - Link(destination = "/url1", title = null, Text("bar")), - ), - ) + parsed.assertEquals(Paragraph(Text("[foo]"), Link(destination = "/url1", title = null, Text("bar")))) } @Test @@ -12362,11 +11043,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Image(source = "/url", alt = "foo", title = "title", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Image(source = "/url", alt = "foo", title = "title", Text("foo")))) } @Test @@ -12378,7 +11055,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo *bar*]: train.jpg "train & tracks" """ - .trimMargin(), + .trimMargin() ) /* @@ -12393,8 +11070,8 @@ class MarkdownProcessorDocumentParsingTest { title = "train & tracks", Text("foo "), Emphasis("*", Text("bar")), - ), - ), + ) + ) ) } @@ -12414,8 +11091,8 @@ class MarkdownProcessorDocumentParsingTest { title = null, Text("foo "), Image(source = "/url", alt = "bar", title = null, Text("bar")), - ), - ), + ) + ) ) } @@ -12435,8 +11112,8 @@ class MarkdownProcessorDocumentParsingTest { title = null, Text("foo "), Link(destination = "/url", title = null, Text("bar")), - ), - ), + ) + ) ) } @@ -12449,7 +11126,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo *bar*]: train.jpg "train & tracks" """ - .trimMargin(), + .trimMargin() ) /* @@ -12464,8 +11141,8 @@ class MarkdownProcessorDocumentParsingTest { title = "train & tracks", Text("foo "), Emphasis("*", Text("bar")), - ), - ), + ) + ) ) } @@ -12478,7 +11155,7 @@ class MarkdownProcessorDocumentParsingTest { | |[FOOBAR]: train.jpg "train & tracks" """ - .trimMargin(), + .trimMargin() ) /* @@ -12493,8 +11170,8 @@ class MarkdownProcessorDocumentParsingTest { title = "train & tracks", Text("foo "), Emphasis("*", Text("bar")), - ), - ), + ) + ) ) } @@ -12506,11 +11183,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Image(source = "train.jpg", alt = "foo", title = null, Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Image(source = "train.jpg", alt = "foo", title = null, Text("foo")))) } @Test @@ -12525,7 +11198,7 @@ class MarkdownProcessorDocumentParsingTest { Paragraph( Text("My "), Image(source = "/path/to/train.jpg", alt = "foo bar", title = "title", Text("foo bar")), - ), + ) ) } @@ -12537,11 +11210,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Image(source = "url", alt = "foo", title = null, Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Image(source = "url", alt = "foo", title = null, Text("foo")))) } @Test @@ -12564,7 +11233,7 @@ class MarkdownProcessorDocumentParsingTest { | |[bar]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -12583,7 +11252,7 @@ class MarkdownProcessorDocumentParsingTest { | |[BAR]: /url """ - .trimMargin(), + .trimMargin() ) /* @@ -12602,7 +11271,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12621,7 +11290,7 @@ class MarkdownProcessorDocumentParsingTest { | |[*foo* bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12630,14 +11299,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( Paragraph( - Image( - source = "/url", - alt = "foo bar", - title = "title", - Emphasis("*", Text("foo")), - Text(" bar"), - ), - ), + Image(source = "/url", alt = "foo bar", title = "title", Emphasis("*", Text("foo")), Text(" bar")) + ) ) } @@ -12650,7 +11313,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12670,7 +11333,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12684,7 +11347,7 @@ class MarkdownProcessorDocumentParsingTest { Text(""), // This looks wrong but it's correct SoftLineBreak, Text("[]"), - ), + ) ) } @@ -12697,7 +11360,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12716,7 +11379,7 @@ class MarkdownProcessorDocumentParsingTest { | |[*foo* bar]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12725,14 +11388,8 @@ class MarkdownProcessorDocumentParsingTest { */ parsed.assertEquals( Paragraph( - Image( - source = "/url", - alt = "foo bar", - title = "title", - Emphasis("*", Text("foo")), - Text(" bar"), - ), - ), + Image(source = "/url", alt = "foo bar", title = "title", Emphasis("*", Text("foo")), Text(" bar")) + ) ) } @@ -12745,7 +11402,7 @@ class MarkdownProcessorDocumentParsingTest { | |[[foo]]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12753,10 +11410,7 @@ class MarkdownProcessorDocumentParsingTest { *

    ![[foo]]

    *

    [[foo]]: /url "title"

    */ - parsed.assertEquals( - paragraph("![[foo]]"), - paragraph("[[foo]]: /url \"title\""), - ) + parsed.assertEquals(paragraph("![[foo]]"), paragraph("[[foo]]: /url \"title\"")) } @Test @@ -12768,7 +11422,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12787,7 +11441,7 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* @@ -12806,19 +11460,14 @@ class MarkdownProcessorDocumentParsingTest { | |[foo]: /url "title" """ - .trimMargin(), + .trimMargin() ) /* * Expected HTML: *

    !foo

    */ - parsed.assertEquals( - Paragraph( - Text("!"), - Link(destination = "/url", title = "title", Text("foo")), - ), - ) + parsed.assertEquals(Paragraph(Text("!"), Link(destination = "/url", title = "title", Text("foo")))) } @Test @@ -12830,9 +11479,7 @@ class MarkdownProcessorDocumentParsingTest { *

    http://foo.bar.baz

    */ parsed.assertEquals( - Paragraph( - Link(destination = "http://foo.bar.baz", title = null, Text("http://foo.bar.baz")), - ), + Paragraph(Link(destination = "http://foo.bar.baz", title = null, Text("http://foo.bar.baz"))) ) } @@ -12850,8 +11497,8 @@ class MarkdownProcessorDocumentParsingTest { destination = "https://foo.bar.baz/test?q=hello&id=22&boolean", title = null, Text("https://foo.bar.baz/test?q=hello&id=22&boolean"), - ), - ), + ) + ) ) } @@ -12864,13 +11511,7 @@ class MarkdownProcessorDocumentParsingTest { *

    irc://foo.bar:2233/baz

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "irc://foo.bar:2233/baz", - title = null, - Text("irc://foo.bar:2233/baz"), - ), - ), + Paragraph(Link(destination = "irc://foo.bar:2233/baz", title = null, Text("irc://foo.bar:2233/baz"))) ) } @@ -12883,13 +11524,7 @@ class MarkdownProcessorDocumentParsingTest { *

    MAILTO:FOO@BAR.BAZ

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "MAILTO:FOO@BAR.BAZ", - title = null, - Text("MAILTO:FOO@BAR.BAZ"), - ), - ), + Paragraph(Link(destination = "MAILTO:FOO@BAR.BAZ", title = null, Text("MAILTO:FOO@BAR.BAZ"))) ) } @@ -12901,15 +11536,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    a+b+c:d

    */ - parsed.assertEquals( - Paragraph( - Link( - destination = "a+b+c:d", - title = null, - Text("a+b+c:d"), - ), - ), - ) + parsed.assertEquals(Paragraph(Link(destination = "a+b+c:d", title = null, Text("a+b+c:d")))) } @Test @@ -12921,13 +11548,7 @@ class MarkdownProcessorDocumentParsingTest { *

    made-up-scheme://foo,bar

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "made-up-scheme://foo,bar", - title = null, - Text("made-up-scheme://foo,bar"), - ), - ), + Paragraph(Link(destination = "made-up-scheme://foo,bar", title = null, Text("made-up-scheme://foo,bar"))) ) } @@ -12939,15 +11560,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    https://../

    */ - parsed.assertEquals( - Paragraph( - Link( - destination = "https://../", - title = null, - Text("https://../"), - ), - ), - ) + parsed.assertEquals(Paragraph(Link(destination = "https://../", title = null, Text("https://../")))) } @Test @@ -12959,13 +11572,7 @@ class MarkdownProcessorDocumentParsingTest { *

    localhost:5001/foo

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "localhost:5001/foo", - title = null, - Text("localhost:5001/foo"), - ), - ), + Paragraph(Link(destination = "localhost:5001/foo", title = null, Text("localhost:5001/foo"))) ) } @@ -12989,13 +11596,7 @@ class MarkdownProcessorDocumentParsingTest { *

    https://example.com/\[\

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "https://example.com/\\[\\", - title = null, - Text("https://example.com/\\[\\"), - ), - ), + Paragraph(Link(destination = "https://example.com/\\[\\", title = null, Text("https://example.com/\\[\\"))) ) } @@ -13008,13 +11609,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo@bar.example.com

    */ parsed.assertEquals( - Paragraph( - Link( - destination = "mailto:foo@bar.example.com", - title = null, - Text("foo@bar.example.com"), - ), - ), + Paragraph(Link(destination = "mailto:foo@bar.example.com", title = null, Text("foo@bar.example.com"))) ) } @@ -13032,8 +11627,8 @@ class MarkdownProcessorDocumentParsingTest { destination = "mailto:foo+special@Bar.baz-bar0.com", title = null, Text("foo+special@Bar.baz-bar0.com"), - ), - ), + ) + ) ) } @@ -13122,13 +11717,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    */ - parsed.assertEquals( - Paragraph( - HtmlInline(""), - HtmlInline(""), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(HtmlInline(""), HtmlInline(""), HtmlInline(""))) } @Test @@ -13139,12 +11728,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    */ - parsed.assertEquals( - Paragraph( - HtmlInline(""), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(HtmlInline(""), HtmlInline(""))) } @Test @@ -13155,7 +11739,7 @@ class MarkdownProcessorDocumentParsingTest { | """ - .trimMargin(), + .trimMargin() ) /* @@ -13163,12 +11747,7 @@ class MarkdownProcessorDocumentParsingTest { *

    */ - parsed.assertEquals( - Paragraph( - HtmlInline(""), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(HtmlInline(""), HtmlInline(""))) } @Test @@ -13179,7 +11758,7 @@ class MarkdownProcessorDocumentParsingTest { | """ - .trimMargin(), + .trimMargin() ) /* @@ -13188,9 +11767,7 @@ class MarkdownProcessorDocumentParsingTest { * _boolean zoop:33=zoop:33 />

    */ parsed.assertEquals( - Paragraph( - HtmlInline("
    "), - ), + Paragraph(HtmlInline("")) ) } @@ -13202,12 +11779,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    Foo

    */ - parsed.assertEquals( - Paragraph( - Text("Foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("Foo "), HtmlInline(""))) } @Test @@ -13253,7 +11825,7 @@ class MarkdownProcessorDocumentParsingTest { | """ - .trimMargin(), + .trimMargin() ) /* @@ -13272,7 +11844,7 @@ class MarkdownProcessorDocumentParsingTest { Text(""), - ), + ) ) } @@ -13295,12 +11867,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    */ - parsed.assertEquals( - Paragraph( - HtmlInline(""), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(HtmlInline(""), HtmlInline(""))) } @Test @@ -13322,7 +11889,7 @@ class MarkdownProcessorDocumentParsingTest { |foo """ - .trimMargin(), + .trimMargin() ) /* @@ -13330,12 +11897,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline(""))) } @Test @@ -13347,7 +11909,7 @@ class MarkdownProcessorDocumentParsingTest { | |foo foo --> """ - .trimMargin(), + .trimMargin() ) /* @@ -13356,16 +11918,8 @@ class MarkdownProcessorDocumentParsingTest { *

    foo foo -->

    */ parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - Text(" foo -->"), - ), - Paragraph( - Text("foo "), - HtmlInline(""), - Text(" foo -->"), - ), + Paragraph(Text("foo "), HtmlInline(""), Text(" foo -->")), + Paragraph(Text("foo "), HtmlInline(""), Text(" foo -->")), ) } @@ -13377,12 +11931,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline(""))) } @Test @@ -13393,12 +11942,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline(""))) } @Test @@ -13409,12 +11953,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo &<]]>

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline("&<]]>"), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline("&<]]>"))) } @Test @@ -13425,12 +11964,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline(""))) } @Test @@ -13441,12 +11975,7 @@ class MarkdownProcessorDocumentParsingTest { * Expected HTML: *

    foo

    */ - parsed.assertEquals( - Paragraph( - Text("foo "), - HtmlInline(""), - ), - ) + parsed.assertEquals(Paragraph(Text("foo "), HtmlInline(""))) } @Test @@ -13468,7 +11997,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -13487,7 +12016,7 @@ class MarkdownProcessorDocumentParsingTest { |foo\ |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -13506,7 +12035,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -13525,7 +12054,7 @@ class MarkdownProcessorDocumentParsingTest { |foo | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -13544,7 +12073,7 @@ class MarkdownProcessorDocumentParsingTest { |foo\ | bar """ - .trimMargin(), + .trimMargin() ) /* @@ -13563,7 +12092,7 @@ class MarkdownProcessorDocumentParsingTest { |*foo |bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -13571,9 +12100,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo
    * bar

    */ - parsed.assertEquals( - Paragraph(Emphasis("*", Text("foo"), HardLineBreak, Text("bar"))), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo"), HardLineBreak, Text("bar")))) } @Test @@ -13584,7 +12111,7 @@ class MarkdownProcessorDocumentParsingTest { |*foo\ |bar* """ - .trimMargin(), + .trimMargin() ) /* @@ -13592,9 +12119,7 @@ class MarkdownProcessorDocumentParsingTest { *

    foo
    * bar

    */ - parsed.assertEquals( - Paragraph(Emphasis("*", Text("foo"), HardLineBreak, Text("bar"))), - ) + parsed.assertEquals(Paragraph(Emphasis("*", Text("foo"), HardLineBreak, Text("bar")))) } @Test @@ -13605,7 +12130,7 @@ class MarkdownProcessorDocumentParsingTest { |`code |span` """ - .trimMargin(), + .trimMargin() ) /* @@ -13623,7 +12148,7 @@ class MarkdownProcessorDocumentParsingTest { |`code\ |span` """ - .trimMargin(), + .trimMargin() ) /* @@ -13641,7 +12166,7 @@ class MarkdownProcessorDocumentParsingTest { |
    """ - .trimMargin(), + .trimMargin() ) /* @@ -13660,7 +12185,7 @@ class MarkdownProcessorDocumentParsingTest { | """ - .trimMargin(), + .trimMargin() ) /* @@ -13723,7 +12248,7 @@ class MarkdownProcessorDocumentParsingTest { |foo |baz """ - .trimMargin(), + .trimMargin() ) /* @@ -13742,7 +12267,7 @@ class MarkdownProcessorDocumentParsingTest { |foo | baz """ - .trimMargin(), + .trimMargin() ) /* diff --git a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/TestUtils.kt b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/TestUtils.kt index 7a49e2590..a0795e8d6 100755 --- a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/TestUtils.kt +++ b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/TestUtils.kt @@ -17,48 +17,37 @@ import org.junit.Assert.assertTrue fun List.assertEquals(vararg expected: MarkdownBlock) { val differences = findDifferences(expected.toList(), indentSize = 0) assertTrue( - "The following differences were found:\n\n" + - "${differences.joinToString("\n").replace('\t', '→')}\n\n", + "The following differences were found:\n\n" + "${differences.joinToString("\n").replace('\t', '→')}\n\n", differences.isEmpty(), ) } -fun List.findDifferences( - expected: List, - indentSize: Int, -): List = - buildList { - val indent = " ".repeat(indentSize) - val thisSize = this@findDifferences.size - if (expected.size != thisSize) { - add("$indent * Content size mismatch. Was $thisSize, but we expected ${expected.size}") - add("$indent Actual: ${this@findDifferences}") - add("$indent Expected: $expected\n") - add("$indent ℹ️ Note: skipping cells comparison as it's meaningless") - return@buildList - } +fun List.findDifferences(expected: List, indentSize: Int): List = buildList { + val indent = " ".repeat(indentSize) + val thisSize = this@findDifferences.size + if (expected.size != thisSize) { + add("$indent * Content size mismatch. Was $thisSize, but we expected ${expected.size}") + add("$indent Actual: ${this@findDifferences}") + add("$indent Expected: $expected\n") + add("$indent ℹ️ Note: skipping cells comparison as it's meaningless") + return@buildList + } - for ((i, item) in this@findDifferences.withIndex()) { - val difference = item.findDifferenceWith(expected[i], indentSize + 2) - if (difference.isNotEmpty()) { - add( - "$indent * Item #$i is not the same as the expected value.\n\n" + - "${difference.joinToString("\n")}\n", - ) - } + for ((i, item) in this@findDifferences.withIndex()) { + val difference = item.findDifferenceWith(expected[i], indentSize + 2) + if (difference.isNotEmpty()) { + add("$indent * Item #$i is not the same as the expected value.\n\n" + "${difference.joinToString("\n")}\n") } } +} -private fun MarkdownBlock.findDifferenceWith( - expected: MarkdownBlock, - indentSize: Int, -): List { +private fun MarkdownBlock.findDifferenceWith(expected: MarkdownBlock, indentSize: Int): List { val indent = " ".repeat(indentSize) if (this.javaClass != expected.javaClass) { return listOf( "$indent * Block type mismatch.\n\n" + "$indent Actual: ${javaClass.name}\n" + - "$indent Expected: ${expected.javaClass.name}\n", + "$indent Expected: ${expected.javaClass.name}\n" ) } @@ -76,44 +65,32 @@ private fun MarkdownBlock.findDifferenceWith( } } -private fun diffParagraph( - actual: Paragraph, - expected: MarkdownBlock, - indent: String, -) = buildList { +private fun diffParagraph(actual: Paragraph, expected: MarkdownBlock, indent: String) = buildList { if (actual != expected) { add( "$indent * Paragraph raw content mismatch.\n\n" + "$indent Actual: $actual\n" + - "$indent Expected: $expected\n", + "$indent Expected: $expected\n" ) } } -private fun diffHtmlBlock( - actual: HtmlBlock, - expected: MarkdownBlock, - indent: String, -) = buildList { +private fun diffHtmlBlock(actual: HtmlBlock, expected: MarkdownBlock, indent: String) = buildList { if (actual.content != (expected as HtmlBlock).content) { add( "$indent * HTML block content mismatch.\n\n" + "$indent Actual: ${actual.content}\n" + - "$indent Expected: ${expected.content}\n", + "$indent Expected: ${expected.content}\n" ) } } -private fun diffFencedCodeBlock( - actual: FencedCodeBlock, - expected: MarkdownBlock, - indent: String, -) = buildList { +private fun diffFencedCodeBlock(actual: FencedCodeBlock, expected: MarkdownBlock, indent: String) = buildList { if (actual.mimeType != (expected as FencedCodeBlock).mimeType) { add( "$indent * Fenced code block mime type mismatch.\n\n" + "$indent Actual: ${actual.mimeType}\n" + - "$indent Expected: ${expected.mimeType}", + "$indent Expected: ${expected.mimeType}" ) } @@ -121,52 +98,39 @@ private fun diffFencedCodeBlock( add( "$indent * Fenced code block content mismatch.\n\n" + "$indent Actual: ${actual.content}\n" + - "$indent Expected: ${expected.content}", + "$indent Expected: ${expected.content}" ) } } -private fun diffIndentedCodeBlock( - actual: CodeBlock, - expected: MarkdownBlock, - indent: String, -) = buildList { +private fun diffIndentedCodeBlock(actual: CodeBlock, expected: MarkdownBlock, indent: String) = buildList { if (actual.content != (expected as IndentedCodeBlock).content) { add( "$indent * Indented code block content mismatch.\n\n" + "$indent Actual: ${actual.content}\n" + - "$indent Expected: ${expected.content}", + "$indent Expected: ${expected.content}" ) } } -private fun diffHeading( - actual: Heading, - expected: MarkdownBlock, - indent: String, -) = buildList { +private fun diffHeading(actual: Heading, expected: MarkdownBlock, indent: String) = buildList { if (actual != expected) { add( "$indent * Heading raw content mismatch.\n\n" + "$indent Actual: $actual\n" + - "$indent Expected: $expected", + "$indent Expected: $expected" ) } } -private fun diffList( - actual: ListBlock, - expected: MarkdownBlock, - indentSize: Int, - indent: String, -) = buildList { +private fun diffList(actual: ListBlock, expected: MarkdownBlock, indentSize: Int, indent: String) = buildList { addAll(actual.children.findDifferences((expected as ListBlock).children, indentSize)) if (actual.isTight != expected.isTight) { add( "$indent * List isTight mismatch.\n\n" + "$indent Actual: ${actual.isTight}\n" + - "$indent Expected: ${expected.isTight}", + "$indent Expected: ${expected.isTight}" ) } @@ -176,7 +140,7 @@ private fun diffList( add( "$indent * List startFrom mismatch.\n\n" + "$indent Actual: ${actual.startFrom}\n" + - "$indent Expected: ${expected.startFrom}", + "$indent Expected: ${expected.startFrom}" ) } @@ -184,7 +148,7 @@ private fun diffList( add( "$indent * List delimiter mismatch.\n\n" + "$indent Actual: ${actual.delimiter}\n" + - "$indent Expected: ${expected.delimiter}", + "$indent Expected: ${expected.delimiter}" ) } } @@ -194,7 +158,7 @@ private fun diffList( add( "$indent * List bulletMarker mismatch.\n\n" + "$indent Actual: ${actual.marker}\n" + - "$indent Expected: ${expected.marker}", + "$indent Expected: ${expected.marker}" ) } } @@ -203,32 +167,19 @@ private fun diffList( fun paragraph(content: String) = Paragraph(InlineMarkdown.Text(content)) -fun heading( - level: Int, - vararg inlineContent: InlineMarkdown, -) = Heading(inlineContent = inlineContent, level = level) +fun heading(level: Int, vararg inlineContent: InlineMarkdown) = Heading(inlineContent = inlineContent, level = level) fun indentedCodeBlock(content: String) = IndentedCodeBlock(content) -fun fencedCodeBlock( - content: String, - mimeType: MimeType? = null, -) = FencedCodeBlock(content, mimeType) +fun fencedCodeBlock(content: String, mimeType: MimeType? = null) = FencedCodeBlock(content, mimeType) fun blockQuote(vararg contents: MarkdownBlock) = BlockQuote(contents.toList()) -fun unorderedList( - vararg items: ListItem, - isTight: Boolean = true, - marker: String = "-", -) = UnorderedList(items.toList(), isTight, marker) - -fun orderedList( - vararg items: ListItem, - isTight: Boolean = true, - startFrom: Int = 1, - delimiter: String = ".", -) = OrderedList(items.toList(), isTight, startFrom, delimiter) +fun unorderedList(vararg items: ListItem, isTight: Boolean = true, marker: String = "-") = + UnorderedList(items.toList(), isTight, marker) + +fun orderedList(vararg items: ListItem, isTight: Boolean = true, startFrom: Int = 1, delimiter: String = ".") = + OrderedList(items.toList(), isTight, startFrom, delimiter) fun listItem(vararg items: MarkdownBlock) = ListItem(*items) diff --git a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessorOptimizeEditsTest.kt b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessorOptimizeEditsTest.kt index e54329ebe..3bbf7236f 100644 --- a/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessorOptimizeEditsTest.kt +++ b/markdown/core/src/test/kotlin/org/jetbrains/jewel/markdown/processing/MarkdownProcessorOptimizeEditsTest.kt @@ -35,10 +35,11 @@ private val rawMarkdown = Paragraph 8 continue p8 - """.trimIndent() + """ + .trimIndent() @Suppress( - "LargeClass", // Detekt triggers on files > 600 lines + "LargeClass" // Detekt triggers on files > 600 lines ) class MarkdownProcessorOptimizeEditsTest { private val htmlRenderer = HtmlRenderer.builder().build() @@ -57,7 +58,8 @@ class MarkdownProcessorOptimizeEditsTest { * list item 3-1 * list item 3-2 - """.trimIndent(), + """ + .trimIndent() ) assertSame(firstRun[0], secondRun[0]) assertSame(firstRun[1], secondRun[1]) @@ -73,7 +75,8 @@ class MarkdownProcessorOptimizeEditsTest {
  • list item 3-2
  • - """.trimIndent(), + """ + .trimIndent(), secondRun, ) } @@ -104,7 +107,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -126,7 +130,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertNotSame(firstRun[0], secondRun[0]) @@ -161,7 +166,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph *CHANGE* continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -184,7 +190,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph CHANGE continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[5], secondRun[5]) @@ -220,7 +227,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -243,7 +251,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[0], secondRun[0]) @@ -280,7 +289,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 7 Paragraph 8 continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -303,7 +313,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[5], secondRun[5]) @@ -337,7 +348,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -360,7 +372,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[3], secondRun[3]) @@ -391,7 +404,8 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8 - """.trimIndent(), + """ + .trimIndent() ) assertHtmlEquals( """ @@ -411,7 +425,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[2], secondRun[2]) @@ -451,11 +466,9 @@ class MarkdownProcessorOptimizeEditsTest { Paragraph 8 continue p8 - """.trimIndent() - val secondRun = - processor.processWithQuickEdits( - secondDocument, - ) + """ + .trimIndent() + val secondRun = processor.processWithQuickEdits(secondDocument) assertHtmlEquals( """

    Paragraph 0 @@ -478,7 +491,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[2], secondRun[2]) @@ -515,7 +529,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertSame(firstRun[0], secondRun[0]) @@ -547,7 +562,8 @@ class MarkdownProcessorOptimizeEditsTest {

    Paragraph 8 continue p8

    - """.trimIndent(), + """ + .trimIndent(), secondRun, ) assertNotSame(firstRun[0], secondRun[0]) @@ -562,7 +578,8 @@ class MarkdownProcessorOptimizeEditsTest { val secondRun = processor.processWithQuickEdits("") assertHtmlEquals( """ - """.trimIndent(), + """ + .trimIndent(), secondRun, ) processor.processWithQuickEdits(rawMarkdown) @@ -588,7 +605,8 @@ class MarkdownProcessorOptimizeEditsTest { # Header 8 # Header 9 - """.trimIndent(), + """ + .trimIndent() ) processor.processWithQuickEdits( """ @@ -605,7 +623,8 @@ class MarkdownProcessorOptimizeEditsTest { # Header 8 # Header 9 - """.trimIndent(), + """ + .trimIndent() ) val forthRun = processor.processWithQuickEdits( @@ -620,7 +639,8 @@ class MarkdownProcessorOptimizeEditsTest { # Header 8 # Header 9 - """.trimIndent(), + """ + .trimIndent() ) val fifthDocument = """ @@ -638,11 +658,9 @@ class MarkdownProcessorOptimizeEditsTest { # Header 8 # Header 9 - """.trimIndent() - val fifthRun = - processor.processWithQuickEdits( - fifthDocument, - ) + """ + .trimIndent() + val fifthRun = processor.processWithQuickEdits(fifthDocument) assertIndexesEqual(fifthDocument, processor.getCurrentIndexesInTest()) @@ -666,15 +684,13 @@ class MarkdownProcessorOptimizeEditsTest {

    Header 8

    Header 9

    - """.trimIndent(), + """ + .trimIndent(), fifthRun, ) } - private fun assertHtmlEquals( - @Language("html") text: String, - actual: List, - ) { + private fun assertHtmlEquals(@Language("html") text: String, actual: List) { assertEquals(text, actual.joinToString("") { htmlRenderer.render(it) }) } } @@ -689,19 +705,13 @@ private fun Node.children(): List { } } -private fun assertIndexesEqual( - lastProcessedDocument: String, - currentIndexes: List>, -) { +private fun assertIndexesEqual(lastProcessedDocument: String, currentIndexes: List>) { val commonmarkDocument = - Parser.builder().includeSourceSpans(IncludeSourceSpans.BLOCKS).build() - .parse(lastProcessedDocument) as Document + Parser.builder().includeSourceSpans(IncludeSourceSpans.BLOCKS).build().parse(lastProcessedDocument) as Document val expected = - (commonmarkDocument).children().map { - it.sourceSpans.first().lineIndex to it.sourceSpans.last().lineIndex - }.toTypedArray() - assertArrayEquals( - expected, - currentIndexes.toTypedArray(), - ) + (commonmarkDocument) + .children() + .map { it.sourceSpans.first().lineIndex to it.sourceSpans.last().lineIndex } + .toTypedArray() + assertArrayEquals(expected, currentIndexes.toTypedArray()) } diff --git a/markdown/extension/autolink/src/main/kotlin/org/jetbrains/jewel/markdown/extension/autolink/AutolinkProcessorExtension.kt b/markdown/extension/autolink/src/main/kotlin/org/jetbrains/jewel/markdown/extension/autolink/AutolinkProcessorExtension.kt index 8e57aefa9..1d786e127 100644 --- a/markdown/extension/autolink/src/main/kotlin/org/jetbrains/jewel/markdown/extension/autolink/AutolinkProcessorExtension.kt +++ b/markdown/extension/autolink/src/main/kotlin/org/jetbrains/jewel/markdown/extension/autolink/AutolinkProcessorExtension.kt @@ -5,6 +5,5 @@ import org.commonmark.parser.Parser.ParserExtension import org.jetbrains.jewel.markdown.extensions.MarkdownProcessorExtension public object AutolinkProcessorExtension : MarkdownProcessorExtension { - override val parserExtension: ParserExtension = - AutolinkExtension.create() as ParserExtension + override val parserExtension: ParserExtension = AutolinkExtension.create() as ParserExtension } diff --git a/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockRenderer.kt b/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockRenderer.kt index 38ea0fa22..234bf5084 100755 --- a/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockRenderer.kt +++ b/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockRenderer.kt @@ -32,10 +32,8 @@ import org.jetbrains.jewel.markdown.rendering.MarkdownStyling import org.jetbrains.jewel.ui.component.Icon import org.jetbrains.jewel.ui.component.Text -public class GitHubAlertBlockRenderer( - private val styling: AlertStyling, - private val rootStyling: MarkdownStyling, -) : MarkdownBlockRendererExtension { +public class GitHubAlertBlockRenderer(private val styling: AlertStyling, private val rootStyling: MarkdownStyling) : + MarkdownBlockRendererExtension { override fun canRender(block: CustomBlock): Boolean = block is Alert @Composable @@ -49,8 +47,7 @@ public class GitHubAlertBlockRenderer( ) { // Smart cast doesn't work in this case, and then the detection for redundant suppression is // also borked - @Suppress("MoveVariableDeclarationIntoWhen", "RedundantSuppression") - val alert = block as? Alert + @Suppress("MoveVariableDeclarationIntoWhen", "RedundantSuppression") val alert = block as? Alert when (alert) { is Caution -> Alert(alert, styling.caution, enabled, blockRenderer, onUrlClick, onTextClick) @@ -73,26 +70,23 @@ public class GitHubAlertBlockRenderer( ) { Column( Modifier.drawBehind { - val isLtr = layoutDirection == Ltr - val lineWidthPx = styling.lineWidth.toPx() - val x = if (isLtr) lineWidthPx / 2 else size.width - lineWidthPx / 2 + val isLtr = layoutDirection == Ltr + val lineWidthPx = styling.lineWidth.toPx() + val x = if (isLtr) lineWidthPx / 2 else size.width - lineWidthPx / 2 - drawLine( - styling.lineColor, - Offset(x, 0f), - Offset(x, size.height), - lineWidthPx, - styling.strokeCap, - styling.pathEffect, - ) - } + drawLine( + styling.lineColor, + Offset(x, 0f), + Offset(x, size.height), + lineWidthPx, + styling.strokeCap, + styling.pathEffect, + ) + } .padding(styling.padding), verticalArrangement = Arrangement.spacedBy(rootStyling.blockVerticalSpacing), ) { - Row( - horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { val titleIconProvider = styling.titleIconKey if (titleIconProvider != null) { val colorFilter = @@ -113,8 +107,7 @@ public class GitHubAlertBlockRenderer( } CompositionLocalProvider( - LocalContentColor provides - styling.titleTextStyle.color.takeOrElse { LocalContentColor.current }, + LocalContentColor provides styling.titleTextStyle.color.takeOrElse { LocalContentColor.current } ) { Text( text = block.javaClass.simpleName, @@ -124,7 +117,7 @@ public class GitHubAlertBlockRenderer( } } CompositionLocalProvider( - LocalContentColor provides styling.textColor.takeOrElse { LocalContentColor.current }, + LocalContentColor provides styling.textColor.takeOrElse { LocalContentColor.current } ) { blockRenderer.render(block.content, enabled, onUrlClick, onTextClick) } diff --git a/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertProcessorExtension.kt b/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertProcessorExtension.kt index 97acfd6b5..225c9ebf6 100755 --- a/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertProcessorExtension.kt +++ b/markdown/extension/gfm-alerts/src/main/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertProcessorExtension.kt @@ -30,8 +30,7 @@ import org.jetbrains.jewel.markdown.rendering.MarkdownStyling public object GitHubAlertProcessorExtension : MarkdownProcessorExtension { override val parserExtension: ParserExtension = GitHubAlertCommonMarkExtension - override val textRendererExtension: TextContentRendererExtension = - GitHubAlertCommonMarkExtension + override val textRendererExtension: TextContentRendererExtension = GitHubAlertCommonMarkExtension override val blockProcessorExtension: MarkdownBlockProcessorExtension = GitHubAlertProcessorExtension @@ -58,17 +57,13 @@ public object GitHubAlertProcessorExtension : MarkdownProcessorExtension { } } -public class GitHubAlertRendererExtension( - alertStyling: AlertStyling, - rootStyling: MarkdownStyling, -) : MarkdownRendererExtension { - override val blockRenderer: MarkdownBlockRendererExtension = - GitHubAlertBlockRenderer(alertStyling, rootStyling) +public class GitHubAlertRendererExtension(alertStyling: AlertStyling, rootStyling: MarkdownStyling) : + MarkdownRendererExtension { + override val blockRenderer: MarkdownBlockRendererExtension = GitHubAlertBlockRenderer(alertStyling, rootStyling) } private object GitHubAlertCommonMarkExtension : ParserExtension, TextContentRendererExtension { - private val AlertStartRegex = - ">\\s+\\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)]\\s*".toRegex(RegexOption.IGNORE_CASE) + private val AlertStartRegex = ">\\s+\\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)]\\s*".toRegex(RegexOption.IGNORE_CASE) override fun extend(parserBuilder: Builder) { parserBuilder.customBlockParserFactory { state, _ -> @@ -77,8 +72,7 @@ private object GitHubAlertCommonMarkExtension : ParserExtension, TextContentRend if (matchResult != null) { val type = matchResult.groupValues[1] - BlockStart.of(AlertParser(type)) - .atColumn(state.column + state.indent + matchResult.value.length) + BlockStart.of(AlertParser(type)).atColumn(state.column + state.indent + matchResult.value.length) } else { BlockStart.none() } @@ -128,8 +122,7 @@ private class AlertParser(type: String) : AbstractBlockParser() { } } -private class AlertTextContentNodeRenderer(private val context: TextContentNodeRendererContext) : - NodeRenderer { +private class AlertTextContentNodeRenderer(private val context: TextContentNodeRendererContext) : NodeRenderer { private val writer = context.writer override fun getNodeTypes(): Set> = setOf(AlertBlock::class.java) diff --git a/markdown/extension/gfm-alerts/src/test/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockExtensionTest.kt b/markdown/extension/gfm-alerts/src/test/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockExtensionTest.kt index de4e03aa5..8f5884cf0 100755 --- a/markdown/extension/gfm-alerts/src/test/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockExtensionTest.kt +++ b/markdown/extension/gfm-alerts/src/test/kotlin/org/jetbrains/jewel/markdown/extensions/github/alerts/GitHubAlertBlockExtensionTest.kt @@ -16,15 +16,10 @@ import org.junit.Assert.assertTrue import org.junit.Test class GitHubAlertBlockExtensionTest { - private val parser = - Parser.builder() - .extensions(listOf(GitHubAlertProcessorExtension.parserExtension)) - .build() + private val parser = Parser.builder().extensions(listOf(GitHubAlertProcessorExtension.parserExtension)).build() private val renderer = - TextContentRenderer.builder() - .extensions(listOf(GitHubAlertProcessorExtension.textRendererExtension)) - .build() + TextContentRenderer.builder().extensions(listOf(GitHubAlertProcessorExtension.textRendererExtension)).build() @Test fun `should parse note alert`() { @@ -42,10 +37,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Note node, but was ${firstChild.javaClass.name}", - firstChild is Note, - ) + assertTrue("Parsed node should be a Note node, but was ${firstChild.javaClass.name}", firstChild is Note) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -71,7 +63,7 @@ class GitHubAlertBlockExtensionTest { |> [!TIP] |> Optional information to help a user be more successful. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -80,10 +72,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Tip node, but was ${firstChild.javaClass.name}", - firstChild is Tip, - ) + assertTrue("Parsed node should be a Tip node, but was ${firstChild.javaClass.name}", firstChild is Tip) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -108,7 +97,7 @@ class GitHubAlertBlockExtensionTest { |> [!IMPORTANT] |> Crucial information necessary for users to succeed. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -145,7 +134,7 @@ class GitHubAlertBlockExtensionTest { |> [!WARNING] |> Critical content demanding immediate user attention due to potential risks. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -154,10 +143,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Warning node, but was ${firstChild.javaClass.name}", - firstChild is Warning, - ) + assertTrue("Parsed node should be a Warning node, but was ${firstChild.javaClass.name}", firstChild is Warning) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -182,7 +168,7 @@ class GitHubAlertBlockExtensionTest { |> [!CAUTION] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -191,10 +177,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", - firstChild is Caution, - ) + assertTrue("Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", firstChild is Caution) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -219,7 +202,7 @@ class GitHubAlertBlockExtensionTest { |> [!note] |> Highlights information that users should take into account, even when skimming. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -228,10 +211,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Note node, but was ${firstChild.javaClass.name}", - firstChild is Note, - ) + assertTrue("Parsed node should be a Note node, but was ${firstChild.javaClass.name}", firstChild is Note) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -256,7 +236,7 @@ class GitHubAlertBlockExtensionTest { |> [!tip] |> Optional information to help a user be more successful. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -265,10 +245,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Tip node, but was ${firstChild.javaClass.name}", - firstChild is Tip, - ) + assertTrue("Parsed node should be a Tip node, but was ${firstChild.javaClass.name}", firstChild is Tip) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -293,7 +270,7 @@ class GitHubAlertBlockExtensionTest { |> [!important] |> Crucial information necessary for users to succeed. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -330,7 +307,7 @@ class GitHubAlertBlockExtensionTest { |> [!warning] |> Critical content demanding immediate user attention due to potential risks. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -339,10 +316,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Warning node, but was ${firstChild.javaClass.name}", - firstChild is Warning, - ) + assertTrue("Parsed node should be a Warning node, but was ${firstChild.javaClass.name}", firstChild is Warning) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -367,7 +341,7 @@ class GitHubAlertBlockExtensionTest { |> [!caution] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -376,10 +350,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", - firstChild is Caution, - ) + assertTrue("Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", firstChild is Caution) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -406,7 +377,7 @@ class GitHubAlertBlockExtensionTest { |> Negative potential consequences of an action. |> """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -415,10 +386,7 @@ class GitHubAlertBlockExtensionTest { assertEquals("Parsed document should only have one direct child", 1, children.size) val firstChild = children.first() - assertTrue( - "Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", - firstChild is Caution, - ) + assertTrue("Parsed node should be a Caution node, but was ${firstChild.javaClass.name}", firstChild is Caution) val contents = firstChild.children assertEquals("Parsed node should only have one direct child", 1, contents.size) @@ -443,7 +411,7 @@ class GitHubAlertBlockExtensionTest { |> [! CAUTION] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -467,7 +435,7 @@ class GitHubAlertBlockExtensionTest { |> [! CAUTION] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -490,7 +458,7 @@ class GitHubAlertBlockExtensionTest { |> [ !CAUTION] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -513,7 +481,7 @@ class GitHubAlertBlockExtensionTest { |> [!CAUTION ] |> Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -535,7 +503,7 @@ class GitHubAlertBlockExtensionTest { """ |> [!CAUTION] Negative potential consequences of an action. """ - .trimMargin(), + .trimMargin() ) assertTrue("Parse result is not a document", parsed is Document) @@ -552,11 +520,10 @@ class GitHubAlertBlockExtensionTest { } private val Node.children: List - get() = - buildList { - var nextChild = firstChild - while (nextChild != null) { - add(nextChild) - nextChild = nextChild.next - } + get() = buildList { + var nextChild = firstChild + while (nextChild != null) { + add(nextChild) + nextChild = nextChild.next } + } diff --git a/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/BridgeProvideMarkdownStyling.kt b/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/BridgeProvideMarkdownStyling.kt index 7e2762aaa..fb1185832 100644 --- a/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/BridgeProvideMarkdownStyling.kt +++ b/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/BridgeProvideMarkdownStyling.kt @@ -20,11 +20,7 @@ public fun ProvideMarkdownStyling( markdownStyling: MarkdownStyling = remember(themeName) { MarkdownStyling.create() }, markdownProcessor: MarkdownProcessor = remember { MarkdownProcessor() }, markdownBlockRenderer: MarkdownBlockRenderer = - remember(markdownStyling) { - MarkdownBlockRenderer.create( - markdownStyling, - ) - }, + remember(markdownStyling) { MarkdownBlockRenderer.create(markdownStyling) }, content: @Composable () -> Unit, ) { CompositionLocalProvider( diff --git a/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/styling/BridgeMarkdownStyling.kt b/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/styling/BridgeMarkdownStyling.kt index b1b99cf9d..d429e6fa5 100644 --- a/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/styling/BridgeMarkdownStyling.kt +++ b/markdown/ide-laf-bridge-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/bridge/styling/BridgeMarkdownStyling.kt @@ -61,19 +61,10 @@ public fun MarkdownStyling.Companion.create( thematicBreak: ThematicBreak = ThematicBreak.create(), htmlBlock: HtmlBlock = HtmlBlock.create(editorTextStyle), ): MarkdownStyling = - MarkdownStyling( - blockVerticalSpacing, - paragraph, - heading, - blockQuote, - code, - list, - image, - thematicBreak, - htmlBlock, - ) + MarkdownStyling(blockVerticalSpacing, paragraph, heading, blockQuote, code, list, image, thematicBreak, htmlBlock) -public fun Paragraph.Companion.create(inlinesStyling: InlinesStyling = InlinesStyling.create()): Paragraph = Paragraph(inlinesStyling) +public fun Paragraph.Companion.create(inlinesStyling: InlinesStyling = InlinesStyling.create()): Paragraph = + Paragraph(inlinesStyling) public fun Heading.Companion.create( baseTextStyle: TextStyle = defaultTextStyle, @@ -83,7 +74,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize * 2, lineHeight = baseTextStyle.fontSize * 2 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h2: Heading.H2 = Heading.H2.create( @@ -91,7 +82,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize * 1.5, lineHeight = baseTextStyle.fontSize * 1.5 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h3: Heading.H3 = Heading.H3.create( @@ -99,7 +90,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize * 1.25, lineHeight = baseTextStyle.fontSize * 1.25 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h4: Heading.H4 = Heading.H4.create( @@ -107,7 +98,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize, lineHeight = baseTextStyle.fontSize * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h5: Heading.H5 = Heading.H5.create( @@ -115,7 +106,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize * .875, lineHeight = baseTextStyle.fontSize * .875 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h6: Heading.H6 = Heading.H6.create( @@ -124,7 +115,7 @@ public fun Heading.Companion.create( fontSize = baseTextStyle.fontSize * .85, lineHeight = baseTextStyle.fontSize * .85 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), ): Heading = Heading(h1, h2, h3, h4, h5, h6) @@ -136,7 +127,7 @@ public fun Heading.H1.Companion.create( fontSize = baseTextStyle.fontSize * 2, lineHeight = baseTextStyle.fontSize * 2 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 1.dp, underlineColor: Color = dividerColor, @@ -152,7 +143,7 @@ public fun Heading.H2.Companion.create( fontSize = baseTextStyle.fontSize * 1.5, lineHeight = baseTextStyle.fontSize * 1.5 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 1.dp, underlineColor: Color = dividerColor, @@ -169,7 +160,7 @@ public fun Heading.H3.Companion.create( fontSize = baseTextStyle.fontSize * 1.25, lineHeight = baseTextStyle.fontSize * 1.25 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 0.dp, underlineColor: Color = Color.Unspecified, @@ -186,7 +177,7 @@ public fun Heading.H4.Companion.create( fontSize = baseTextStyle.fontSize, lineHeight = baseTextStyle.fontSize * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 0.dp, underlineColor: Color = Color.Unspecified, @@ -203,7 +194,7 @@ public fun Heading.H5.Companion.create( fontSize = baseTextStyle.fontSize * .875, lineHeight = baseTextStyle.fontSize * .875 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 0.dp, underlineColor: Color = Color.Unspecified, @@ -221,7 +212,7 @@ public fun Heading.H6.Companion.create( fontSize = baseTextStyle.fontSize * .85, lineHeight = baseTextStyle.fontSize * .85 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), underlineWidth: Dp = 0.dp, underlineColor: Color = Color.Unspecified, @@ -270,15 +261,7 @@ public fun Unordered.Companion.create( itemVerticalSpacing: Dp = 16.dp, itemVerticalSpacingTight: Dp = 4.dp, padding: PaddingValues = PaddingValues(start = 16.dp), -): Unordered = - Unordered( - bullet, - bulletStyle, - bulletContentGap, - itemVerticalSpacing, - itemVerticalSpacingTight, - padding, - ) +): Unordered = Unordered(bullet, bulletStyle, bulletContentGap, itemVerticalSpacing, itemVerticalSpacingTight, padding) public fun Code.Companion.create( editorTextStyle: TextStyle = defaultEditorTextStyle, @@ -295,17 +278,7 @@ public fun Indented.Companion.create( borderColor: Color = Color.Unspecified, fillWidth: Boolean = true, scrollsHorizontally: Boolean = true, -): Indented = - Indented( - textStyle, - padding, - shape, - background, - borderWidth, - borderColor, - fillWidth, - scrollsHorizontally, - ) +): Indented = Indented(textStyle, padding, shape, background, borderWidth, borderColor, fillWidth, scrollsHorizontally) public fun Fenced.Companion.create( textStyle: TextStyle = defaultEditorTextStyle, @@ -367,10 +340,12 @@ public fun InlinesStyling.Companion.create( .copy(fontSize = textStyle.fontSize * .85, background = inlineCodeBackgroundColor) .toSpanStyle(), link: SpanStyle = - textStyle.copy( - color = JBUI.CurrentTheme.Link.Foreground.ENABLED.toComposeColor(), - textDecoration = TextDecoration.Underline, - ).toSpanStyle(), + textStyle + .copy( + color = JBUI.CurrentTheme.Link.Foreground.ENABLED.toComposeColor(), + textDecoration = TextDecoration.Underline, + ) + .toSpanStyle(), linkDisabled: SpanStyle = link.copy(color = JBUI.CurrentTheme.Link.Foreground.DISABLED.toComposeColor()), linkHovered: SpanStyle = link.copy(color = JBUI.CurrentTheme.Link.Foreground.HOVERED.toComposeColor()), linkFocused: SpanStyle = diff --git a/markdown/int-ui-standalone-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/standalone/styling/IntUiMarkdownStyling.kt b/markdown/int-ui-standalone-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/standalone/styling/IntUiMarkdownStyling.kt index 8a3373a65..bc7727e9a 100755 --- a/markdown/int-ui-standalone-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/standalone/styling/IntUiMarkdownStyling.kt +++ b/markdown/int-ui-standalone-styling/src/main/kotlin/org/jetbrains/jewel/intui/markdown/standalone/styling/IntUiMarkdownStyling.kt @@ -59,17 +59,7 @@ public fun MarkdownStyling.Companion.light( thematicBreak: ThematicBreak = ThematicBreak.light(), htmlBlock: HtmlBlock = HtmlBlock.light(editorTextStyle.copy(color = blockContentColorLight)), ): MarkdownStyling = - MarkdownStyling( - blockVerticalSpacing, - paragraph, - heading, - blockQuote, - code, - list, - image, - thematicBreak, - htmlBlock, - ) + MarkdownStyling(blockVerticalSpacing, paragraph, heading, blockQuote, code, list, image, thematicBreak, htmlBlock) public fun MarkdownStyling.Companion.dark( baseTextStyle: TextStyle = defaultTextStyle, @@ -91,21 +81,13 @@ public fun MarkdownStyling.Companion.dark( thematicBreak: ThematicBreak = ThematicBreak.dark(), htmlBlock: HtmlBlock = HtmlBlock.dark(editorTextStyle.copy(color = blockContentColorLight)), ): MarkdownStyling = - MarkdownStyling( - blockVerticalSpacing, - paragraph, - heading, - blockQuote, - code, - list, - image, - thematicBreak, - htmlBlock, - ) + MarkdownStyling(blockVerticalSpacing, paragraph, heading, blockQuote, code, list, image, thematicBreak, htmlBlock) -public fun Paragraph.Companion.light(inlinesStyling: InlinesStyling = InlinesStyling.light()): Paragraph = Paragraph(inlinesStyling) +public fun Paragraph.Companion.light(inlinesStyling: InlinesStyling = InlinesStyling.light()): Paragraph = + Paragraph(inlinesStyling) -public fun Paragraph.Companion.dark(inlinesStyling: InlinesStyling = InlinesStyling.dark()): Paragraph = Paragraph(inlinesStyling) +public fun Paragraph.Companion.dark(inlinesStyling: InlinesStyling = InlinesStyling.dark()): Paragraph = + Paragraph(inlinesStyling) public fun Heading.Companion.light( baseTextStyle: TextStyle = defaultTextStyle, @@ -115,7 +97,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize * 2, lineHeight = baseTextStyle.fontSize * 2 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h2: Heading.H2 = Heading.H2.light( @@ -123,7 +105,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize * 1.5, lineHeight = baseTextStyle.fontSize * 1.5 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h3: Heading.H3 = Heading.H3.light( @@ -131,7 +113,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize * 1.25, lineHeight = baseTextStyle.fontSize * 1.25 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h4: Heading.H4 = Heading.H4.light( @@ -139,7 +121,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize, lineHeight = baseTextStyle.fontSize * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h5: Heading.H5 = Heading.H5.light( @@ -147,7 +129,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize * .875, lineHeight = baseTextStyle.fontSize * .875 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h6: Heading.H6 = Heading.H6.light( @@ -156,7 +138,7 @@ public fun Heading.Companion.light( fontSize = baseTextStyle.fontSize * .85, lineHeight = baseTextStyle.fontSize * .85 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), ): Heading = Heading(h1, h2, h3, h4, h5, h6) @@ -168,7 +150,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize * 2, lineHeight = baseTextStyle.fontSize * 2 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h2: Heading.H2 = Heading.H2.light( @@ -176,7 +158,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize * 1.5, lineHeight = baseTextStyle.fontSize * 1.5 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h3: Heading.H3 = Heading.H3.light( @@ -184,7 +166,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize * 1.25, lineHeight = baseTextStyle.fontSize * 1.25 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h4: Heading.H4 = Heading.H4.light( @@ -192,7 +174,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize, lineHeight = baseTextStyle.fontSize * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h5: Heading.H5 = Heading.H5.light( @@ -200,7 +182,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize * .875, lineHeight = baseTextStyle.fontSize * .875 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), h6: Heading.H6 = Heading.H6.light( @@ -209,7 +191,7 @@ public fun Heading.Companion.dark( fontSize = baseTextStyle.fontSize * .85, lineHeight = baseTextStyle.fontSize * .85 * 1.25, fontWeight = FontWeight.SemiBold, - ), + ) ), ): Heading = Heading(h1, h2, h3, h4, h5, h6) @@ -466,15 +448,7 @@ public fun Unordered.Companion.light( itemVerticalSpacing: Dp = 16.dp, itemVerticalSpacingTight: Dp = 4.dp, padding: PaddingValues = PaddingValues(start = 16.dp), -): Unordered = - Unordered( - bullet, - bulletStyle, - bulletContentGap, - itemVerticalSpacing, - itemVerticalSpacingTight, - padding, - ) +): Unordered = Unordered(bullet, bulletStyle, bulletContentGap, itemVerticalSpacing, itemVerticalSpacingTight, padding) public fun Unordered.Companion.dark( bullet: Char? = '•', @@ -483,15 +457,7 @@ public fun Unordered.Companion.dark( itemVerticalSpacing: Dp = 16.dp, itemVerticalSpacingTight: Dp = 4.dp, padding: PaddingValues = PaddingValues(start = 16.dp), -): Unordered = - Unordered( - bullet, - bulletStyle, - bulletContentGap, - itemVerticalSpacing, - itemVerticalSpacingTight, - padding, - ) +): Unordered = Unordered(bullet, bulletStyle, bulletContentGap, itemVerticalSpacing, itemVerticalSpacingTight, padding) public fun Code.Companion.light( editorTextStyle: TextStyle = defaultEditorTextStyle.copy(color = blockContentColorLight), @@ -515,16 +481,7 @@ public fun Indented.Companion.light( fillWidth: Boolean = true, scrollsHorizontally: Boolean = true, ): Indented = - Indented( - editorTextStyle, - padding, - shape, - background, - borderWidth, - borderColor, - fillWidth, - scrollsHorizontally, - ) + Indented(editorTextStyle, padding, shape, background, borderWidth, borderColor, fillWidth, scrollsHorizontally) public fun Indented.Companion.dark( editorTextStyle: TextStyle = defaultEditorTextStyle.copy(color = blockContentColorDark), @@ -536,16 +493,7 @@ public fun Indented.Companion.dark( fillWidth: Boolean = true, scrollsHorizontally: Boolean = true, ): Indented = - Indented( - editorTextStyle, - padding, - shape, - background, - borderWidth, - borderColor, - fillWidth, - scrollsHorizontally, - ) + Indented(editorTextStyle, padding, shape, background, borderWidth, borderColor, fillWidth, scrollsHorizontally) public fun Fenced.Companion.light( editorTextStyle: TextStyle = defaultEditorTextStyle.copy(color = blockContentColorLight), @@ -650,10 +598,7 @@ public fun InlinesStyling.Companion.light( .copy(fontSize = textStyle.fontSize * .85, background = inlineCodeBackgroundColorLight) .toSpanStyle(), link: SpanStyle = - textStyle.copy( - color = IntUiLightTheme.colors.blue(2), - textDecoration = TextDecoration.Underline, - ).toSpanStyle(), + textStyle.copy(color = IntUiLightTheme.colors.blue(2), textDecoration = TextDecoration.Underline).toSpanStyle(), linkDisabled: SpanStyle = link.copy(color = IntUiLightTheme.colors.gray(8)), linkHovered: SpanStyle = link, linkFocused: SpanStyle = link.copy(background = Color(0x12000000)), @@ -686,10 +631,7 @@ public fun InlinesStyling.Companion.dark( .copy(fontSize = textStyle.fontSize * .85, background = inlineCodeBackgroundColorDark) .toSpanStyle(), link: SpanStyle = - textStyle.copy( - color = IntUiDarkTheme.colors.blue(9), - textDecoration = TextDecoration.Underline, - ).toSpanStyle(), + textStyle.copy(color = IntUiDarkTheme.colors.blue(9), textDecoration = TextDecoration.Underline).toSpanStyle(), linkDisabled: SpanStyle = link.copy(color = IntUiDarkTheme.colors.gray(8)), linkHovered: SpanStyle = link, linkFocused: SpanStyle = link.copy(background = Color(0x16FFFFFF)), @@ -724,20 +666,10 @@ private val blockContentColorDark = Color(0xFFBCBEC4) private val defaultTextSize = 13.sp private val defaultTextStyle - get() = - JewelTheme.createDefaultTextStyle( - fontSize = defaultTextSize, - lineHeight = defaultTextSize * 1.5, - ) + get() = JewelTheme.createDefaultTextStyle(fontSize = defaultTextSize, lineHeight = defaultTextSize * 1.5) private val defaultEditorTextStyle - get() = - JewelTheme.createEditorTextStyle( - fontSize = defaultTextSize, - lineHeight = defaultTextSize * 1.2, - ) + get() = JewelTheme.createEditorTextStyle(fontSize = defaultTextSize, lineHeight = defaultTextSize * 1.2) -private val inlineCodeBackgroundColorLight = - Color(red = 212, green = 222, blue = 231, alpha = 255 / 4) -private val inlineCodeBackgroundColorDark = - Color(red = 212, green = 222, blue = 231, alpha = 25) +private val inlineCodeBackgroundColorLight = Color(red = 212, green = 222, blue = 231, alpha = 255 / 4) +private val inlineCodeBackgroundColorDark = Color(red = 212, green = 222, blue = 231, alpha = 25) diff --git a/samples/ide-plugin/build.gradle.kts b/samples/ide-plugin/build.gradle.kts index 7efbb61cf..9a6380e43 100644 --- a/samples/ide-plugin/build.gradle.kts +++ b/samples/ide-plugin/build.gradle.kts @@ -22,13 +22,9 @@ repositories { } dependencies { - implementation(projects.ideLafBridge) { - exclude(group = "org.jetbrains.kotlinx") - } + implementation(projects.ideLafBridge) { exclude(group = "org.jetbrains.kotlinx") } - implementation(projects.markdown.ideLafBridgeStyling) { - exclude(group = "org.jetbrains.kotlinx") - } + implementation(projects.markdown.ideLafBridgeStyling) { exclude(group = "org.jetbrains.kotlinx") } implementation(compose.desktop.currentOs) { exclude(group = "org.jetbrains.compose.material") @@ -38,12 +34,10 @@ dependencies { tasks { // We don't have any settings in the demo plugin - buildSearchableOptions { - enabled = false - } + buildSearchableOptions { enabled = false } runIde { systemProperties["org.jetbrains.jewel.debug"] = "true" jvmArgs = listOf("-Xmx3g") } -} +} \ No newline at end of file diff --git a/samples/ide-plugin/src/main/kotlin/icons/JewelIcons.kt b/samples/ide-plugin/src/main/kotlin/icons/JewelIcons.kt index 20c51dbb0..2fe3233a3 100644 --- a/samples/ide-plugin/src/main/kotlin/icons/JewelIcons.kt +++ b/samples/ide-plugin/src/main/kotlin/icons/JewelIcons.kt @@ -3,6 +3,5 @@ package icons import com.intellij.openapi.util.IconLoader object JewelIcons { - @JvmField - val ToolWindowIcon = IconLoader.getIcon("/icons/jewel-tool-window.svg", javaClass) + @JvmField val ToolWindowIcon = IconLoader.getIcon("/icons/jewel-tool-window.svg", javaClass) } diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ComponentShowcaseTab.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ComponentShowcaseTab.kt index c23cc9bfc..1873eaa9d 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ComponentShowcaseTab.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ComponentShowcaseTab.kt @@ -78,8 +78,7 @@ internal fun ComponentShowcaseTab() { VerticallyScrollableContainer { Row( modifier = - Modifier - .trackComponentActivation(LocalComponent.current) + Modifier.trackComponentActivation(LocalComponent.current) .fillMaxSize() .background(bgColor) .padding(16.dp), @@ -93,69 +92,45 @@ internal fun ComponentShowcaseTab() { @Composable private fun RowScope.ColumnOne() { - Column( - Modifier.trackActivation().weight(1f), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { + Column(Modifier.trackActivation().weight(1f), verticalArrangement = Arrangement.spacedBy(16.dp)) { var activated by remember { mutableStateOf(false) } Text( "Here is a selection of our finest components(activated: $activated):", - Modifier.onActivated { - activated = it - }, + Modifier.onActivated { activated = it }, style = Typography.h3TextStyle(), ) var selectedItem by remember { mutableIntStateOf(-1) } Dropdown( menuContent = { - selectableItem(selectedItem == 0, onClick = { selectedItem = 0 }) { - Text("Hello") - } + selectableItem(selectedItem == 0, onClick = { selectedItem = 0 }) { Text("Hello") } separator() - selectableItem(selectedItem == 1, onClick = { selectedItem = 1 }) { - Text("World") - } - }, + selectableItem(selectedItem == 1, onClick = { selectedItem = 1 }) { Text("World") } + } ) { Text("Selected item $selectedItem") } - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) { var clicks1 by remember { mutableIntStateOf(0) } - OutlinedButton({ clicks1++ }) { - Text("Outlined: $clicks1") - } - OutlinedButton({ }, enabled = false) { - Text("Outlined") - } + OutlinedButton({ clicks1++ }) { Text("Outlined: $clicks1") } + OutlinedButton({}, enabled = false) { Text("Outlined") } var clicks2 by remember { mutableIntStateOf(0) } - DefaultButton({ clicks2++ }) { - Text("Default: $clicks2") - } - DefaultButton({ }, enabled = false) { - Text("Default") - } + DefaultButton({ clicks2++ }) { Text("Default: $clicks2") } + DefaultButton({}, enabled = false) { Text("Default") } } val state = rememberTextFieldState("") TextField( state = state, modifier = - Modifier - .width(200.dp) - .provideData { - set(ActionSystemTestAction.COMPONENT_DATA_KEY.name, "TextField") - lazy(ActionSystemTestAction.COMPONENT_DATA_KEY.name) { - Math.random().toString() - } - }, + Modifier.width(200.dp).provideData { + set(ActionSystemTestAction.COMPONENT_DATA_KEY.name, "TextField") + lazy(ActionSystemTestAction.COMPONENT_DATA_KEY.name) { Math.random().toString() } + }, placeholder = { Text("Write something...") }, ) @@ -168,62 +143,43 @@ private fun RowScope.ColumnOne() { checked = checked, onCheckedChange = { checked = it }, outline = outline, - modifier = - Modifier.provideData { - set(ActionSystemTestAction.COMPONENT_DATA_KEY.name, "Checkbox") - }, + modifier = Modifier.provideData { set(ActionSystemTestAction.COMPONENT_DATA_KEY.name, "Checkbox") }, ) { Text("Hello, I am a themed checkbox") } - CheckboxRow(checked = validated, onCheckedChange = { validated = it }) { - Text("Show validation") - } + CheckboxRow(checked = validated, onCheckedChange = { validated = it }) { Text("Show validation") } } Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { var index by remember { mutableIntStateOf(0) } - RadioButtonRow( - selected = index == 0, - onClick = { index = 0 }, - outline = outline, - ) { + RadioButtonRow(selected = index == 0, onClick = { index = 0 }, outline = outline) { Text("I am number one") } - RadioButtonRow( - selected = index == 1, - onClick = { index = 1 }, - outline = outline, - ) { - Text("Sad second") - } + RadioButtonRow(selected = index == 1, onClick = { index = 1 }, outline = outline) { Text("Sad second") } } IconsShowcase() - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text("Circular progress small:") CircularProgressIndicator() } - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { Text("Circular progress big:") CircularProgressIndicatorBig() } Row(verticalAlignment = Alignment.CenterVertically) { - Tooltip(tooltip = { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Icon(AllIconsKeys.General.ShowInfos, contentDescription = null) - Text("This is a tooltip") + Tooltip( + tooltip = { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Icon(AllIconsKeys.General.ShowInfos, contentDescription = null) + Text("This is a tooltip") + } } - }) { + ) { Text( modifier = Modifier.border(1.dp, JewelTheme.globalColors.borders.normal).padding(12.dp, 8.dp), text = "Hover Me!", @@ -294,14 +250,12 @@ private fun IconsShowcase() { ) } - IconButton(onClick = { }, Modifier.size(24.dp)) { - PlatformIcon(AllIconsKeys.Actions.Close, "Close") - } + IconButton(onClick = {}, Modifier.size(24.dp)) { PlatformIcon(AllIconsKeys.Actions.Close, "Close") } IconActionButton( AllIconsKeys.Actions.AddList, "Close", - onClick = { }, + onClick = {}, modifier = Modifier.size(24.dp), hints = arrayOf(Size(24)), tooltip = { Text("Hello there") }, @@ -311,51 +265,40 @@ private fun IconsShowcase() { @Composable private fun RowScope.ColumnTwo() { - Column( - Modifier.trackActivation().weight(1f), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { + Column(Modifier.trackActivation().weight(1f), verticalArrangement = Arrangement.spacedBy(16.dp)) { MarkdownExample() Divider(Orientation.Horizontal) var activated by remember { mutableStateOf(false) } - Text( - "activated: $activated", - Modifier.onActivated { - activated = it - }, - ) + Text("activated: $activated", Modifier.onActivated { activated = it }) - val tree = - remember { - buildTree { - addNode("root 1") { - addLeaf("leaf 1") - addLeaf("leaf 2") - } - addNode("root 2") { - addLeaf("leaf 1") - addNode("node 1") { - addLeaf("leaf 1") - addLeaf("leaf 2") - } - } - addNode("root 3") { + val tree = remember { + buildTree { + addNode("root 1") { + addLeaf("leaf 1") + addLeaf("leaf 2") + } + addNode("root 2") { + addLeaf("leaf 1") + addNode("node 1") { addLeaf("leaf 1") addLeaf("leaf 2") } } + addNode("root 3") { + addLeaf("leaf 1") + addLeaf("leaf 2") + } } + } LazyTree( tree = tree, modifier = Modifier.height(200.dp).fillMaxWidth(), onElementClick = {}, onElementDoubleClick = {}, ) { element -> - Box(Modifier.fillMaxWidth()) { - Text(element.data, Modifier.padding(2.dp)) - } + Box(Modifier.fillMaxWidth()) { Text(element.data, Modifier.padding(2.dp)) } } } } @@ -381,19 +324,12 @@ private fun MarkdownExample() { |```kotlin |fun hello() = "World" |``` - """.trimMargin(), - Modifier - .fillMaxWidth() - .background( - JBUI.CurrentTheme.Banner.INFO_BACKGROUND - .toComposeColor(), - RoundedCornerShape(8.dp), - ).border( - 1.dp, - JBUI.CurrentTheme.Banner.INFO_BORDER_COLOR - .toComposeColor(), - RoundedCornerShape(8.dp), - ).padding(8.dp), + """ + .trimMargin(), + Modifier.fillMaxWidth() + .background(JBUI.CurrentTheme.Banner.INFO_BACKGROUND.toComposeColor(), RoundedCornerShape(8.dp)) + .border(1.dp, JBUI.CurrentTheme.Banner.INFO_BORDER_COLOR.toComposeColor(), RoundedCornerShape(8.dp)) + .padding(8.dp), enabled = enabled, onUrlClick = { url -> BrowserUtil.open(url) }, ) diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/JewelDemoToolWindowFactory.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/JewelDemoToolWindowFactory.kt index 6021ac6ec..816ad43e9 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/JewelDemoToolWindowFactory.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/JewelDemoToolWindowFactory.kt @@ -7,6 +7,7 @@ import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts.TabTitle import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory +import javax.swing.JComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -14,34 +15,21 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import org.jetbrains.jewel.bridge.addComposeTab import org.jetbrains.jewel.samples.ideplugin.releasessample.ReleasesSampleCompose -import javax.swing.JComponent @Suppress("unused") @ExperimentalCoroutinesApi internal class JewelDemoToolWindowFactory : ToolWindowFactory, DumbAware { - override fun createToolWindowContent( - project: Project, - toolWindow: ToolWindow, - ) { - toolWindow.addComposeTab("Components") { - ComponentShowcaseTab() - } + override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { + toolWindow.addComposeTab("Components") { ComponentShowcaseTab() } - toolWindow.addComposeTab("Releases Demo") { - ReleasesSampleCompose(project) - } + toolWindow.addComposeTab("Releases Demo") { ReleasesSampleCompose(project) } toolWindow.addSwingTab(SwingComparisonTabPanel(), "Swing Comparison") - toolWindow.addComposeTab("Scrollbars Sample") { - ScrollbarsShowcaseTab() - } + toolWindow.addComposeTab("Scrollbars Sample") { ScrollbarsShowcaseTab() } } - private fun ToolWindow.addSwingTab( - component: JComponent, - @TabTitle title: String, - ) { + private fun ToolWindow.addSwingTab(component: JComponent, @TabTitle title: String) { val manager = contentManager val tabContent = manager.factory.createContent(component, title, true) tabContent.isCloseable = false diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ScrollbarsShowcaseTab.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ScrollbarsShowcaseTab.kt index 06c9dd123..75853f440 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ScrollbarsShowcaseTab.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/ScrollbarsShowcaseTab.kt @@ -21,6 +21,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import java.util.Locale import org.jetbrains.jewel.bridge.LocalComponent import org.jetbrains.jewel.foundation.modifier.trackActivation import org.jetbrains.jewel.foundation.modifier.trackComponentActivation @@ -31,7 +32,6 @@ import org.jetbrains.jewel.ui.component.Text import org.jetbrains.jewel.ui.component.TextArea import org.jetbrains.jewel.ui.component.VerticallyScrollableContainer import org.jetbrains.jewel.ui.component.scrollbarContentSafePadding -import java.util.Locale @Composable internal fun ScrollbarsShowcaseTab() { diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/SwingComparisonTabPanel.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/SwingComparisonTabPanel.kt index 39416df4c..e80525d7f 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/SwingComparisonTabPanel.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/SwingComparisonTabPanel.kt @@ -47,19 +47,20 @@ import org.jetbrains.jewel.ui.theme.textAreaStyle internal class SwingComparisonTabPanel : BorderLayoutPanel() { private val mainContent = panel { - buttonsRow() - separator() - labelsRows() - separator() - iconsRow() - separator() - textFieldsRow() - separator() - textAreasRow() - }.apply { - border = JBUI.Borders.empty(0, 10) - isOpaque = false - } + buttonsRow() + separator() + labelsRows() + separator() + iconsRow() + separator() + textFieldsRow() + separator() + textAreasRow() + } + .apply { + border = JBUI.Borders.empty(0, 10) + isOpaque = false + } private val scrollingContainer = JBScrollPane( @@ -77,84 +78,90 @@ internal class SwingComparisonTabPanel : BorderLayoutPanel() { private fun Panel.buttonsRow() { row("Buttons:") { - button("Swing Button") {}.align(AlignY.CENTER) - compose { OutlinedButton({}) { Text("Compose Button") } } + button("Swing Button") {}.align(AlignY.CENTER) + compose { OutlinedButton({}) { Text("Compose Button") } } - button("Default Swing Button") {}.align(AlignY.CENTER) - .applyToComponent { putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, true) } - compose { DefaultButton({}) { Text("Default Compose Button") } } - }.layout(RowLayout.PARENT_GRID) + button("Default Swing Button") {} + .align(AlignY.CENTER) + .applyToComponent { putClientProperty(DarculaButtonUI.DEFAULT_STYLE_KEY, true) } + compose { DefaultButton({}) { Text("Default Compose Button") } } + } + .layout(RowLayout.PARENT_GRID) } private fun Panel.labelsRows() { row("Labels:") { - label("Swing label").align(AlignY.CENTER) - compose { Text("Compose label") } - }.layout(RowLayout.PARENT_GRID) + label("Swing label").align(AlignY.CENTER) + compose { Text("Compose label") } + } + .layout(RowLayout.PARENT_GRID) row("Comments:") { - comment("Swing comment").align(AlignY.CENTER) - compose { - Text("Compose comment", style = Typography.medium(), color = JewelTheme.globalColors.text.info) + comment("Swing comment").align(AlignY.CENTER) + compose { + Text("Compose comment", style = Typography.medium(), color = JewelTheme.globalColors.text.info) + } } - }.layout(RowLayout.PARENT_GRID) + .layout(RowLayout.PARENT_GRID) } private fun Panel.iconsRow() { row("Icons:") { - cell( - JBLabel(JewelIcons.ToolWindowIcon).apply { border = JBUI.Borders.customLine(JBColor.RED) }, - ).align(AlignY.CENTER) - - compose { - Icon( - key = IdeSampleIconKeys.jewelToolWindow, - contentDescription = null, - modifier = Modifier.border(1.dp, Color.Red), - ) + cell(JBLabel(JewelIcons.ToolWindowIcon).apply { border = JBUI.Borders.customLine(JBColor.RED) }) + .align(AlignY.CENTER) + + compose { + Icon( + key = IdeSampleIconKeys.jewelToolWindow, + contentDescription = null, + modifier = Modifier.border(1.dp, Color.Red), + ) + } } - }.layout(RowLayout.PARENT_GRID) + .layout(RowLayout.PARENT_GRID) } private fun Panel.textFieldsRow() { row("Text fields:") { - textField().align(AlignY.CENTER) + textField().align(AlignY.CENTER) - compose { - val state = rememberTextFieldState("") - TextField(state) + compose { + val state = rememberTextFieldState("") + TextField(state) + } } - }.layout(RowLayout.PARENT_GRID) + .layout(RowLayout.PARENT_GRID) } private fun Panel.textAreasRow() { row("Text areas:") { - textArea().align(AlignY.CENTER).applyToComponent { rows = 3 } - - compose { - val metrics = remember(JBFont.label(), LocalDensity.current) { getFontMetrics(JBFont.label()) } - val charWidth = - remember(metrics.widths) { - // Same logic as in JTextArea - metrics.charWidth('m') - } - val lineHeight = metrics.height - - val width = remember(charWidth) { (COLUMNS_SHORT * charWidth) } - val height = remember(lineHeight) { (3 * lineHeight) } - - val contentPadding = JewelTheme.textAreaStyle.metrics.contentPadding - val state = rememberTextFieldState("Hello") - TextArea( - state = state, - modifier = - Modifier.size( - width = width.dp + contentPadding.horizontal(LocalLayoutDirection.current), - height = height.dp + contentPadding.vertical(), - ), - ) + textArea().align(AlignY.CENTER).applyToComponent { rows = 3 } + + compose { + val metrics = remember(JBFont.label(), LocalDensity.current) { getFontMetrics(JBFont.label()) } + val charWidth = + remember(metrics.widths) { + // Same logic as in JTextArea + metrics.charWidth('m') + } + val lineHeight = metrics.height + + val width = remember(charWidth) { (COLUMNS_SHORT * charWidth) } + val height = remember(lineHeight) { (3 * lineHeight) } + + val contentPadding = JewelTheme.textAreaStyle.metrics.contentPadding + val state = rememberTextFieldState("Hello") + TextArea( + state = state, + modifier = + Modifier.size( + width = width.dp + contentPadding.horizontal(LocalLayoutDirection.current), + height = height.dp + contentPadding.vertical(), + ), + ) + } } - }.layout(RowLayout.PARENT_GRID) + .layout(RowLayout.PARENT_GRID) } private fun PaddingValues.vertical(): Dp = calculateTopPadding() + calculateBottomPadding() @@ -163,9 +170,5 @@ internal class SwingComparisonTabPanel : BorderLayoutPanel() { calculateStartPadding(layoutDirection) + calculateEndPadding(layoutDirection) private fun Row.compose(content: @Composable () -> Unit) = - cell( - JewelComposePanel { - Box(Modifier.padding(8.dp)) { content() } - }.apply { isOpaque = false }, - ) + cell(JewelComposePanel { Box(Modifier.padding(8.dp)) { content() } }.apply { isOpaque = false }) } diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/JewelDemoAction.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/JewelDemoAction.kt index e0140f355..1d5143f2f 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/JewelDemoAction.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/JewelDemoAction.kt @@ -18,6 +18,7 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -27,12 +28,8 @@ import kotlinx.coroutines.launch import org.jetbrains.jewel.ui.component.CheckboxRow import org.jetbrains.jewel.ui.component.Text import org.jetbrains.jewel.ui.component.Typography -import kotlin.time.Duration.Companion.seconds -@Service(Service.Level.PROJECT) -private class ProjectScopeProviderService( - val scope: CoroutineScope, -) +@Service(Service.Level.PROJECT) private class ProjectScopeProviderService(val scope: CoroutineScope) internal class JewelDemoAction : DumbAwareAction() { override fun actionPerformed(event: AnActionEvent) { @@ -41,17 +38,16 @@ internal class JewelDemoAction : DumbAwareAction() { scope.launch(Dispatchers.EDT) { WizardDialogWrapper( - project = project, - title = "Jewel Demo wizard", - pages = listOf(FirstPage(project), SecondPage()), - ).showAndGet() + project = project, + title = "Jewel Demo wizard", + pages = listOf(FirstPage(project), SecondPage()), + ) + .showAndGet() } } } -private class FirstPage( - private val project: Project, -) : WizardPage { +private class FirstPage(private val project: Project) : WizardPage { override val canGoBackwards: StateFlow = MutableStateFlow(true) private val checkboxChecked = MutableStateFlow(false) diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/WizardDialogWrapper.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/WizardDialogWrapper.kt index 6bd143014..966f0a746 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/WizardDialogWrapper.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/dialog/WizardDialogWrapper.kt @@ -8,6 +8,10 @@ import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.util.ui.JBDimension +import java.awt.event.ActionEvent +import javax.swing.Action +import javax.swing.JComponent +import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope @@ -20,10 +24,6 @@ import org.jetbrains.annotations.Nls import org.jetbrains.jewel.bridge.JewelComposePanel import org.jetbrains.jewel.foundation.ExperimentalJewelApi import org.jetbrains.jewel.foundation.enableNewSwingCompositing -import java.awt.event.ActionEvent -import javax.swing.Action -import javax.swing.JComponent -import kotlin.coroutines.CoroutineContext internal class WizardDialogWrapper( project: Project, @@ -33,8 +33,7 @@ internal class WizardDialogWrapper( ) : DialogWrapper(project), CoroutineScope { private val logger = thisLogger() - override val coroutineContext: CoroutineContext = - SupervisorJob() + Dispatchers.EDT + CoroutineName("ComposeWizard") + override val coroutineContext: CoroutineContext = SupervisorJob() + Dispatchers.EDT + CoroutineName("ComposeWizard") private val currentPageIndex = mutableIntStateOf(0) @@ -75,8 +74,7 @@ internal class WizardDialogWrapper( newScope.launch(defaultDispatcher) { page.canGoForward.collect { canGoForward -> logger.info("CanGoForward: $canGoForward") - nextAction.isEnabled = - pageIndex < pages.lastIndex && canGoForward + nextAction.isEnabled = pageIndex < pages.lastIndex && canGoForward finishAction.isEnabled = pageIndex == pages.lastIndex && canGoForward } } @@ -87,11 +85,10 @@ internal class WizardDialogWrapper( enableNewSwingCompositing() return JewelComposePanel { - val index by currentPageIndex - pages[index].PageContent() - }.apply { - minimumSize = JBDimension(400, 400) - } + val index by currentPageIndex + pages[index].PageContent() + } + .apply { minimumSize = JBDimension(400, 400) } } override fun createActions(): Array = arrayOf(cancelAction, backAction, nextAction, finishAction) @@ -126,10 +123,7 @@ internal class WizardDialogWrapper( } } - private inner class WizardAction( - @Nls name: String, - private val onAction: () -> Unit, - ) : DialogWrapperAction(name) { + private inner class WizardAction(@Nls name: String, private val onAction: () -> Unit) : DialogWrapperAction(name) { override fun doAction(e: ActionEvent?) { onAction() } @@ -137,8 +131,7 @@ internal class WizardDialogWrapper( } interface WizardPage { - @Composable - fun PageContent() + @Composable fun PageContent() val canGoForward: StateFlow val canGoBackwards: StateFlow diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/AndroidStudioReleases.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/AndroidStudioReleases.kt index e30d8fbd6..098efdb84 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/AndroidStudioReleases.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/AndroidStudioReleases.kt @@ -1,5 +1,6 @@ // Generated by the Jewel Android Studio Releases Generator -// Generated from https://jb.gg/android-studio-releases-list.json on 2024-08-07T12:44:17.265182+02:00[Europe/Rome] +// Generated from https://jb.gg/android-studio-releases-list.json on +// 2024-08-07T12:44:17.265182+02:00[Europe/Rome] package org.jetbrains.jewel.samples.ideplugin.releasessample import kotlinx.datetime.LocalDate diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentItem.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentItem.kt index 43d42b6ac..1683dbc4e 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentItem.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentItem.kt @@ -4,8 +4,7 @@ import kotlinx.datetime.LocalDate import org.jetbrains.annotations.Nls sealed class ContentItem { - @get:Nls - abstract val displayText: String + @get:Nls abstract val displayText: String abstract val imagePath: String? abstract val versionName: String abstract val releaseDate: LocalDate? diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentSource.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentSource.kt index 3158507ce..caa4fbf83 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentSource.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ContentSource.kt @@ -21,10 +21,8 @@ abstract class ContentSource { } } -data class FilteredContentSource( - override val items: List, - val original: ContentSource<*>, -) : ContentSource() { +data class FilteredContentSource(override val items: List, val original: ContentSource<*>) : + ContentSource() { override val displayName: String get() = original.displayName } diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/FoilModifier.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/FoilModifier.kt index cc72ce0de..076b07505 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/FoilModifier.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/FoilModifier.kt @@ -9,7 +9,8 @@ import org.jetbrains.skia.RuntimeEffect import org.jetbrains.skia.RuntimeShaderBuilder @Language("GLSL") // Technically, SkSL -private const val FOIL_SHADER_CODE = """ +private const val FOIL_SHADER_CODE = + """ const float SCALE = 1.8; // Effect scale (> 1 means smaller rainbow) const float SATURATION = 0.9; // Color saturation (0.0 = grayscale, 1.0 = full color) const float LIGHTNESS = 0.65; // Color lightness (0.0 = black, 1.0 = white) @@ -74,20 +75,18 @@ vec4 main(float2 fragCoord) { private val runtimeEffect = RuntimeEffect.makeForShader(FOIL_SHADER_CODE) private val shaderBuilder = RuntimeShaderBuilder(runtimeEffect) -internal fun Modifier.holoFoil( - offset: Float, - intensity: Float = 1f, -) = graphicsLayer { +internal fun Modifier.holoFoil(offset: Float, intensity: Float = 1f) = graphicsLayer { shaderBuilder.uniform("resolution", size.width, size.height) shaderBuilder.uniform("offset", 0f, offset) shaderBuilder.uniform("intensity", intensity * .65f) renderEffect = ImageFilter.makeRuntimeShader( - runtimeShaderBuilder = shaderBuilder, - shaderNames = arrayOf("content"), - inputs = arrayOf(null), - ).asComposeRenderEffect() + runtimeShaderBuilder = shaderBuilder, + shaderNames = arrayOf("content"), + inputs = arrayOf(null), + ) + .asComposeRenderEffect() rotationX = offset * 4f * intensity rotationY = offset * 10f * intensity diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleaseChannel.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleaseChannel.kt index 0ec1fe5a4..172257acb 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleaseChannel.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleaseChannel.kt @@ -4,10 +4,7 @@ import com.intellij.ui.JBColor import java.awt.Color @Suppress("UnregisteredNamedColor") // They exist at runtime -enum class ReleaseChannel( - val background: Color, - val foreground: Color, -) { +enum class ReleaseChannel(val background: Color, val foreground: Color) { Stable( background = JBColor( diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleCompose.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleCompose.kt index 27f9c6ef4..d557197c9 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleCompose.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleCompose.kt @@ -59,6 +59,9 @@ import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.ui.JBUI import icons.JewelIcons +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.datetime.toJavaLocalDate @@ -86,9 +89,6 @@ import org.jetbrains.jewel.ui.icons.AllIconsKeys import org.jetbrains.jewel.ui.painter.rememberResourcePainterProvider import org.jetbrains.jewel.ui.theme.iconButtonStyle import org.jetbrains.jewel.ui.util.thenIf -import java.time.format.DateTimeFormatter -import java.time.format.FormatStyle -import kotlin.time.Duration.Companion.seconds @Composable fun ReleasesSampleCompose(project: Project) { @@ -101,12 +101,7 @@ fun ReleasesSampleCompose(project: Project) { onSelectedItemChange = { selectedItem = it }, ) }, - second = { modifier -> - RightColumn( - selectedItem = selectedItem, - modifier = modifier.fillMaxSize(), - ) - }, + second = { modifier -> RightColumn(selectedItem = selectedItem, modifier = modifier.fillMaxSize()) }, Modifier.fillMaxSize(), initialDividerPosition = 400.dp, minRatio = .15f, @@ -115,20 +110,13 @@ fun ReleasesSampleCompose(project: Project) { } @Composable -private fun LeftColumn( - project: Project, - modifier: Modifier = Modifier, - onSelectedItemChange: (ContentItem?) -> Unit, -) { +private fun LeftColumn(project: Project, modifier: Modifier = Modifier, onSelectedItemChange: (ContentItem?) -> Unit) { val service = remember(project) { project.service() } val currentContentSource by service.content.collectAsState() Column(modifier) { Row( - modifier = - Modifier.fillMaxWidth() - .height(IntrinsicSize.Min) - .padding(4.dp, 6.dp), + modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(4.dp, 6.dp), verticalAlignment = Alignment.CenterVertically, ) { Text("Filter elements:") @@ -139,9 +127,7 @@ private fun LeftColumn( Spacer(Modifier.width(4.dp)) - OverflowMenu(currentContentSource) { - service.setContentSource(it) - } + OverflowMenu(currentContentSource) { service.setContentSource(it) } } val listState = rememberSelectableLazyListState() @@ -171,9 +157,7 @@ private fun LeftColumn( } }, ) { - ContentItemRow(it, isSelected, isActive) { newFilter -> - service.filterContent(newFilter) - } + ContentItemRow(it, isSelected, isActive) { newFilter -> service.filterContent(newFilter) } } } } @@ -181,12 +165,7 @@ private fun LeftColumn( } @Composable -private fun ContentItemRow( - item: ContentItem, - isSelected: Boolean, - isActive: Boolean, - onTagClick: (String) -> Unit, -) { +private fun ContentItemRow(item: ContentItem, isSelected: Boolean, isActive: Boolean, onTagClick: (String) -> Unit) { val color = when { isSelected && isActive -> retrieveColorOrUnspecified("List.selectionBackground") @@ -202,12 +181,7 @@ private fun ContentItemRow( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), ) { - Text( - text = item.displayText, - modifier = Modifier.weight(1f), - overflow = TextOverflow.Ellipsis, - maxLines = 1, - ) + Text(text = item.displayText, modifier = Modifier.weight(1f), overflow = TextOverflow.Ellipsis, maxLines = 1) val pointerModifier = Modifier.pointerHoverIcon(PointerIcon.Hand) when (item) { @@ -246,10 +220,7 @@ private fun ItemTag( text = text, style = Typography.medium(), color = foregroundColor, - modifier = - modifier - .background(backgroundColor, shape) - .padding(padding), + modifier = modifier.background(backgroundColor, shape).padding(padding), ) } @@ -259,29 +230,19 @@ private enum class ItemType { } @Composable -private fun SearchBar( - service: ReleasesSampleService, - modifier: Modifier = Modifier, -) { +private fun SearchBar(service: ReleasesSampleService, modifier: Modifier = Modifier) { val filterText by service.filter.collectAsState() val focusRequester = remember { FocusRequester() } - LaunchedEffect(Unit) { - focusRequester.requestFocus() - } + LaunchedEffect(Unit) { focusRequester.requestFocus() } val state = rememberTextFieldState(filterText) - LaunchedEffect(state) { - snapshotFlow { state.text } - .collect { service.filterContent(it.toString()) } - } + LaunchedEffect(state) { snapshotFlow { state.text }.collect { service.filterContent(it.toString()) } } TextField( state = state, modifier = modifier.focusRequester(focusRequester), - leadingIcon = { - Icon(AllIconsKeys.Actions.Find, contentDescription = null, Modifier.padding(end = 8.dp)) - }, + leadingIcon = { Icon(AllIconsKeys.Actions.Find, contentDescription = null, Modifier.padding(end = 8.dp)) }, trailingIcon = { if (filterText.isNotBlank()) { CloseIconButton(service) @@ -308,21 +269,18 @@ private fun CloseIconButton(service: ReleasesSampleService) { key = if (hovered) AllIconsKeys.Actions.CloseHovered else AllIconsKeys.Actions.Close, contentDescription = "Clear", modifier = - Modifier - .pointerHoverIcon(PointerIcon.Default) - .clickable( - interactionSource = interactionSource, - indication = null, - role = Role.Button, - ) { service.resetFilter() }, + Modifier.pointerHoverIcon(PointerIcon.Default).clickable( + interactionSource = interactionSource, + indication = null, + role = Role.Button, + ) { + service.resetFilter() + }, ) } @Composable -private fun OverflowMenu( - currentContentSource: ContentSource<*>, - onContentSourceChange: (ContentSource<*>) -> Unit, -) { +private fun OverflowMenu(currentContentSource: ContentSource<*>, onContentSourceChange: (ContentSource<*>) -> Unit) { val interactionSource = remember { MutableInteractionSource() } var hovered by remember { mutableStateOf(false) } var pressed by remember { mutableStateOf(false) } @@ -333,7 +291,8 @@ private fun OverflowMenu( is HoverInteraction.Enter -> hovered = true is HoverInteraction.Exit -> hovered = false is PressInteraction.Press -> pressed = true - is PressInteraction.Release, is PressInteraction.Cancel -> pressed = false + is PressInteraction.Release, + is PressInteraction.Cancel -> pressed = false } } } @@ -343,26 +302,23 @@ private fun OverflowMenu( // Emulates Swing actions that pop up menus — they stay pressed while the menu is open IconButton( modifier = - Modifier.fillMaxHeight() - .thenIf(menuVisible) { - background( + Modifier.fillMaxHeight().thenIf(menuVisible) { + background( color = JewelTheme.iconButtonStyle.colors.backgroundPressed, shape = RoundedCornerShape(JewelTheme.iconButtonStyle.metrics.cornerSize), - ).border( + ) + .border( width = JewelTheme.iconButtonStyle.metrics.borderWidth, color = JewelTheme.iconButtonStyle.colors.backgroundPressed, shape = RoundedCornerShape(JewelTheme.iconButtonStyle.metrics.cornerSize), ) - }, + }, onClick = { menuVisible = !menuVisible }, ) { Icon(key = AllIconsKeys.Ide.Notification.Gear, contentDescription = "Select data source") } - val contentSources = - remember { - listOf(AndroidStudioReleases, AndroidReleases) - } + val contentSources = remember { listOf(AndroidStudioReleases, AndroidReleases) } if (menuVisible) { PopupMenu( @@ -401,20 +357,14 @@ private fun OverflowMenu( } @Composable -private fun RightColumn( - selectedItem: ContentItem?, - modifier: Modifier, -) { +private fun RightColumn(selectedItem: ContentItem?, modifier: Modifier) { if (selectedItem == null) { Box(modifier, contentAlignment = Alignment.Center) { Text("Nothing to see here", color = JBUI.CurrentTheme.Label.disabledForeground().toComposeColor()) } } else { VerticallyScrollableContainer(modifier = modifier) { - Column( - verticalArrangement = Arrangement.Top, - horizontalAlignment = Alignment.Start, - ) { + Column(verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start) { val imagePath = selectedItem.imagePath if (imagePath != null) { ReleaseImage(imagePath) @@ -431,16 +381,17 @@ private fun ReleaseImage(imagePath: String) { val painterProvider = rememberResourcePainterProvider(imagePath, JewelIcons::class.java) val painter by painterProvider.getPainter() val transition = rememberInfiniteTransition("HoloFoil") - val offset by transition.animateFloat( - initialValue = -1f, - targetValue = 1f, - animationSpec = - infiniteRepeatable( - tween(durationMillis = 2.seconds.inWholeMilliseconds.toInt(), easing = FastOutSlowInEasing), - repeatMode = RepeatMode.Reverse, - ), - "holoFoil offset", - ) + val offset by + transition.animateFloat( + initialValue = -1f, + targetValue = 1f, + animationSpec = + infiniteRepeatable( + tween(durationMillis = 2.seconds.inWholeMilliseconds.toInt(), easing = FastOutSlowInEasing), + repeatMode = RepeatMode.Reverse, + ), + "holoFoil offset", + ) var isHovered by remember { mutableStateOf(false) } var applyModifier by remember { mutableStateOf(false) } val intensity by animateFloatAsState(if (isHovered) 1f else 0f, animationSpec = tween(300)) @@ -467,14 +418,10 @@ private fun ReleaseImage(imagePath: String) { @Composable private fun ItemDetailsText(selectedItem: ContentItem) { - Column( - Modifier.padding(horizontal = 20.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(6.dp), - ) { + Column(Modifier.padding(horizontal = 20.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { Text(selectedItem.displayText, style = Typography.h1TextStyle()) - val formatter = - remember(Locale.current) { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) } + val formatter = remember(Locale.current) { DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM) } val releaseDate = selectedItem.releaseDate if (releaseDate != null) { Text( @@ -510,10 +457,7 @@ private fun AndroidStudioReleaseDetails(item: ContentItem.AndroidStudio) { } @Composable -private fun TextWithLabel( - labelText: String, - valueText: String, -) { +private fun TextWithLabel(labelText: String, valueText: String) { Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { Text(labelText) Text(valueText, style = Typography.regular().copy(fontWeight = FontWeight.Bold)) diff --git a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleService.kt b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleService.kt index 78338a2b0..56c9b4519 100644 --- a/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleService.kt +++ b/samples/ide-plugin/src/main/kotlin/org/jetbrains/jewel/samples/ideplugin/releasessample/ReleasesSampleService.kt @@ -31,15 +31,13 @@ internal class ReleasesSampleService : CoroutineScope, Disposable { init { combine(originalContentSource, filter) { source, filter -> - val normalizedFilter = filter.trim() - if (normalizedFilter.isBlank()) return@combine source + val normalizedFilter = filter.trim() + if (normalizedFilter.isBlank()) return@combine source - val filteredContentItems = - source.items - .filter { it.matches(normalizedFilter) } + val filteredContentItems = source.items.filter { it.matches(normalizedFilter) } - FilteredContentSource(filteredContentItems, source) - } + FilteredContentSource(filteredContentItems, source) + } .onEach { filteredContent.emit(it) } .launchIn(this) } diff --git a/samples/standalone/build.gradle.kts b/samples/standalone/build.gradle.kts index 37786fb6d..5923eaf6f 100755 --- a/samples/standalone/build.gradle.kts +++ b/samples/standalone/build.gradle.kts @@ -15,13 +15,12 @@ dependencies { implementation(projects.markdown.intUiStandaloneStyling) implementation(projects.markdown.extension.gfmAlerts) implementation(projects.markdown.extension.autolink) - implementation(compose.desktop.currentOs) { - exclude(group = "org.jetbrains.compose.material") - } + implementation(compose.desktop.currentOs) { exclude(group = "org.jetbrains.compose.material") } implementation(libs.intellijPlatform.icons) } val jdkLevel = project.property("jdk.level") as String + kotlin { jvmToolchain { languageVersion = JavaLanguageVersion.of(jdkLevel) @@ -55,11 +54,8 @@ tasks { // afterEvaluate is needed because the Compose Gradle Plugin // register the task in the afterEvaluate block afterEvaluate { - javaLauncher = - project.javaToolchains.launcherFor { - languageVersion = JavaLanguageVersion.of(jdkLevel) - } + javaLauncher = project.javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(jdkLevel) } setExecutable(javaLauncher.map { it.executablePath.asFile.absolutePath }.get()) } } -} +} \ No newline at end of file diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/IntUiThemes.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/IntUiThemes.kt index 254590eb3..4feb4cc88 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/IntUiThemes.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/IntUiThemes.kt @@ -7,8 +7,7 @@ enum class IntUiThemes { Light, LightWithLightHeader, Dark, - System, - ; + System; fun isDark() = (if (this == System) fromSystemTheme(currentSystemTheme) else this) == Dark diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/Main.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/Main.kt index f25a49f04..4c3875e66 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/Main.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/Main.kt @@ -12,6 +12,7 @@ import androidx.compose.ui.res.loadSvgPainter import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.Density import androidx.compose.ui.window.application +import java.io.InputStream import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.foundation.util.JewelLogger import org.jetbrains.jewel.intui.standalone.Inter @@ -32,12 +33,9 @@ import org.jetbrains.jewel.samples.standalone.viewmodel.MainViewModel.currentVie import org.jetbrains.jewel.ui.ComponentStyling import org.jetbrains.jewel.window.DecoratedWindow import org.jetbrains.jewel.window.styling.TitleBarStyle -import java.io.InputStream fun main() { - JewelLogger - .getInstance("StandaloneSample") - .info("Starting Jewel Standalone sample") + JewelLogger.getInstance("StandaloneSample").info("Starting Jewel Standalone sample") val icon = svgResource("icons/jewel-logo.svg") @@ -55,20 +53,21 @@ fun main() { IntUiTheme( theme = themeDefinition, styling = - ComponentStyling.default().decoratedWindow( - titleBarStyle = - when (MainViewModel.theme) { - IntUiThemes.Light -> TitleBarStyle.light() - IntUiThemes.LightWithLightHeader -> TitleBarStyle.lightWithLightHeader() - IntUiThemes.Dark -> TitleBarStyle.dark() - IntUiThemes.System -> - if (MainViewModel.theme.isDark()) { - TitleBarStyle.dark() - } else { - TitleBarStyle.light() - } - }, - ), + ComponentStyling.default() + .decoratedWindow( + titleBarStyle = + when (MainViewModel.theme) { + IntUiThemes.Light -> TitleBarStyle.light() + IntUiThemes.LightWithLightHeader -> TitleBarStyle.lightWithLightHeader() + IntUiThemes.Dark -> TitleBarStyle.dark() + IntUiThemes.System -> + if (MainViewModel.theme.isDark()) { + TitleBarStyle.dark() + } else { + TitleBarStyle.light() + } + } + ), swingCompatMode = MainViewModel.swingCompat, ) { DecoratedWindow( @@ -76,10 +75,7 @@ fun main() { title = "Jewel component catalog", icon = icon, onKeyEvent = { keyEvent -> - processKeyShortcuts( - keyEvent = keyEvent, - onNavigateTo = MainViewModel::onNavigateTo, - ) + processKeyShortcuts(keyEvent = keyEvent, onNavigateTo = MainViewModel::onNavigateTo) }, content = { TitleBarView() @@ -91,14 +87,11 @@ fun main() { } /* - Alt + W -> Welcome - Alt + M -> Markdown - Alt + C -> Components - */ -private fun processKeyShortcuts( - keyEvent: KeyEvent, - onNavigateTo: (String) -> Unit, -): Boolean { + Alt + W -> Welcome + Alt + M -> Markdown + Alt + C -> Components +*/ +private fun processKeyShortcuts(keyEvent: KeyEvent, onNavigateTo: (String) -> Unit): Boolean { if (!keyEvent.isAltPressed || keyEvent.type != KeyEventType.KeyDown) return false return when (keyEvent.key) { Key.W -> { @@ -120,12 +113,5 @@ private fun processKeyShortcuts( } } -private fun svgResource( - resourcePath: String, - loader: ResourceLoader = ResourceLoader.Default, -): Painter = - loader - .load(resourcePath) - .use { stream: InputStream -> - loadSvgPainter(stream, Density(1f)) - } +private fun svgResource(resourcePath: String, loader: ResourceLoader = ResourceLoader.Default): Painter = + loader.load(resourcePath).use { stream: InputStream -> loadSvgPainter(stream, Density(1f)) } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/StandaloneSampleIcons.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/StandaloneSampleIcons.kt index 227faef30..442d8d7d7 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/StandaloneSampleIcons.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/StandaloneSampleIcons.kt @@ -9,7 +9,8 @@ object StandaloneSampleIcons { val markdown = PathIconKey("icons/markdown.svg", StandaloneSampleIcons::class.java) val themeDark = PathIconKey("icons/darkTheme.svg", StandaloneSampleIcons::class.java) val themeLight = PathIconKey("icons/lightTheme.svg", StandaloneSampleIcons::class.java) - val themeLightWithLightHeader = PathIconKey("icons/lightWithLightHeaderTheme.svg", StandaloneSampleIcons::class.java) + val themeLightWithLightHeader = + PathIconKey("icons/lightWithLightHeaderTheme.svg", StandaloneSampleIcons::class.java) val themeSystem = PathIconKey("icons/systemTheme.svg", StandaloneSampleIcons::class.java) val welcome = PathIconKey("icons/meetNewUi.svg", StandaloneSampleIcons::class.java) diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/ComponentsView.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/ComponentsView.kt index 89df98189..797065605 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/ComponentsView.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/ComponentsView.kt @@ -16,6 +16,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import kotlin.time.Duration.Companion.milliseconds import org.jetbrains.jewel.foundation.modifier.trackActivation import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.samples.standalone.viewmodel.ComponentsViewModel @@ -29,7 +30,6 @@ import org.jetbrains.jewel.ui.component.styling.TooltipMetrics import org.jetbrains.jewel.ui.component.styling.TooltipStyle import org.jetbrains.jewel.ui.painter.hints.Size import org.jetbrains.jewel.ui.theme.tooltipStyle -import kotlin.time.Duration.Companion.milliseconds @Composable fun ComponentsView() { @@ -52,10 +52,7 @@ fun ComponentsToolBar() { modifier = Modifier.size(40.dp).padding(5.dp), tooltip = { Text(it.title) }, tooltipStyle = - TooltipStyle( - JewelTheme.tooltipStyle.colors, - TooltipMetrics.defaults(showDelay = 150.milliseconds), - ), + TooltipStyle(JewelTheme.tooltipStyle.colors, TooltipMetrics.defaults(showDelay = 150.milliseconds)), tooltipPlacement = TooltipPlacement.ComponentRect(Alignment.CenterEnd, Alignment.CenterEnd), extraHints = arrayOf(Size(20)), ) diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/MarkdownView.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/MarkdownView.kt index bf0d32a2c..e35cfa48b 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/MarkdownView.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/MarkdownView.kt @@ -19,16 +19,10 @@ import org.jetbrains.jewel.ui.component.Divider fun MarkdownDemo() { Row(Modifier.trackActivation().fillMaxSize().background(JewelTheme.globalColors.panelBackground)) { val editorState = rememberTextFieldState(JewelReadme) - MarkdownEditor( - state = editorState, - modifier = Modifier.fillMaxHeight().weight(1f), - ) + MarkdownEditor(state = editorState, modifier = Modifier.fillMaxHeight().weight(1f)) Divider(Orientation.Vertical, Modifier.fillMaxHeight()) - MarkdownPreview( - modifier = Modifier.fillMaxHeight().weight(1f), - rawMarkdown = editorState.text, - ) + MarkdownPreview(modifier = Modifier.fillMaxHeight().weight(1f), rawMarkdown = editorState.text) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/TitleBarView.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/TitleBarView.kt index 2274a5f7d..699f680da 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/TitleBarView.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/TitleBarView.kt @@ -9,6 +9,8 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp +import java.awt.Desktop +import java.net.URI import org.jetbrains.jewel.samples.standalone.IntUiThemes import org.jetbrains.jewel.samples.standalone.StandaloneSampleIcons import org.jetbrains.jewel.samples.standalone.viewmodel.MainViewModel @@ -22,30 +24,31 @@ import org.jetbrains.jewel.ui.painter.hints.Size import org.jetbrains.jewel.window.DecoratedWindowScope import org.jetbrains.jewel.window.TitleBar import org.jetbrains.jewel.window.newFullscreenControls -import java.awt.Desktop -import java.net.URI @Composable fun DecoratedWindowScope.TitleBarView() { TitleBar(Modifier.newFullscreenControls(), gradientStartColor = MainViewModel.projectColor) { Row(Modifier.align(Alignment.Start)) { - Dropdown(Modifier.height(30.dp), menuContent = { - MainViewModel.views.forEach { - selectableItem( - selected = MainViewModel.currentView == it, - onClick = { MainViewModel.currentView = it }, - keybinding = it.keyboardShortcut?.forCurrentOs(), - ) { - Row( - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically, + Dropdown( + Modifier.height(30.dp), + menuContent = { + MainViewModel.views.forEach { + selectableItem( + selected = MainViewModel.currentView == it, + onClick = { MainViewModel.currentView = it }, + keybinding = it.keyboardShortcut?.forCurrentOs(), ) { - Icon(it.iconKey, null, modifier = Modifier.size(20.dp), hint = Size(20)) - Text(it.title) + Row( + horizontalArrangement = Arrangement.spacedBy(4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(it.iconKey, null, modifier = Modifier.size(20.dp), hint = Size(20)) + Text(it.title) + } } } - } - }) { + }, + ) { Row( horizontalArrangement = Arrangement.spacedBy(3.dp), verticalAlignment = Alignment.CenterVertically, @@ -64,12 +67,11 @@ fun DecoratedWindowScope.TitleBarView() { Text(title) Row(Modifier.align(Alignment.End)) { - Tooltip({ - Text("Open Jewel Github repository") - }) { - IconButton({ - Desktop.getDesktop().browse(URI.create("https://github.com/JetBrains/jewel")) - }, Modifier.size(40.dp).padding(5.dp)) { + Tooltip({ Text("Open Jewel Github repository") }) { + IconButton( + { Desktop.getDesktop().browse(URI.create("https://github.com/JetBrains/jewel")) }, + Modifier.size(40.dp).padding(5.dp), + ) { Icon(StandaloneSampleIcons.gitHub, "Github") } } @@ -78,17 +80,22 @@ fun DecoratedWindowScope.TitleBarView() { when (MainViewModel.theme) { IntUiThemes.Light -> Text("Switch to light theme with light header") IntUiThemes.LightWithLightHeader -> Text("Switch to dark theme") - IntUiThemes.Dark, IntUiThemes.System -> Text("Switch to light theme") + IntUiThemes.Dark, + IntUiThemes.System -> Text("Switch to light theme") } }) { - IconButton({ - MainViewModel.theme = - when (MainViewModel.theme) { - IntUiThemes.Light -> IntUiThemes.LightWithLightHeader - IntUiThemes.LightWithLightHeader -> IntUiThemes.Dark - IntUiThemes.Dark, IntUiThemes.System -> IntUiThemes.Light - } - }, Modifier.size(40.dp).padding(5.dp)) { + IconButton( + { + MainViewModel.theme = + when (MainViewModel.theme) { + IntUiThemes.Light -> IntUiThemes.LightWithLightHeader + IntUiThemes.LightWithLightHeader -> IntUiThemes.Dark + IntUiThemes.Dark, + IntUiThemes.System -> IntUiThemes.Light + } + }, + Modifier.size(40.dp).padding(5.dp), + ) { when (MainViewModel.theme) { IntUiThemes.Light -> Icon( diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/WelcomeView.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/WelcomeView.kt index 94546760c..0b7920903 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/WelcomeView.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/WelcomeView.kt @@ -31,17 +31,10 @@ import org.jetbrains.jewel.ui.painter.hints.Selected fun WelcomeView() { Column( modifier = - Modifier.trackActivation() - .fillMaxSize() - .background(JewelTheme.globalColors.panelBackground) - .padding(24.dp), + Modifier.trackActivation().fillMaxSize().background(JewelTheme.globalColors.panelBackground).padding(24.dp), verticalArrangement = Arrangement.spacedBy(24.dp), ) { - Icon( - key = StandaloneSampleIcons.jewelLogo, - contentDescription = null, - modifier = Modifier.size(200.dp), - ) + Icon(key = StandaloneSampleIcons.jewelLogo, contentDescription = null, modifier = Modifier.size(200.dp)) Text("Meet Jewel", fontSize = 20.sp) @@ -80,11 +73,7 @@ fun WelcomeView() { } @Composable -fun ThemeSelectionChip( - theme: IntUiThemes, - name: String, - iconKey: IconKey, -) { +fun ThemeSelectionChip(theme: IntUiThemes, name: String, iconKey: IconKey) { RadioButtonChip( selected = MainViewModel.theme == theme, onClick = { MainViewModel.theme = theme }, diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Borders.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Borders.kt index 7da47a8c4..a119e14c8 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Borders.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Borders.kt @@ -36,10 +36,7 @@ internal fun Borders() { GroupHeader("Border alignment/expand") var borderAlignment by remember { mutableStateOf(Stroke.Alignment.Center) } - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { RadioButtonRow( text = "Inside", selected = borderAlignment == Stroke.Alignment.Inside, @@ -58,89 +55,37 @@ internal fun Borders() { } var width by remember { mutableStateOf(1.dp) } var expand by remember { mutableStateOf(0.dp) } - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - OutlinedButton({ - width += 1.dp - }) { - Text("+width") - } - OutlinedButton({ - width -= 1.dp - }, enabled = width > 1.dp) { - Text("-width") - } - OutlinedButton({ - expand += 1.dp - }) { - Text("+expand") - } - OutlinedButton({ - expand -= 1.dp - }) { - Text("-expand") - } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + OutlinedButton({ width += 1.dp }) { Text("+width") } + OutlinedButton({ width -= 1.dp }, enabled = width > 1.dp) { Text("-width") } + OutlinedButton({ expand += 1.dp }) { Text("+expand") } + OutlinedButton({ expand -= 1.dp }) { Text("-expand") } } - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { val isDark = JewelTheme.isDark val colorPalette = JewelTheme.colorPalette - val borderColor = - remember(isDark) { - if (isDark) colorPalette.blue(6) else colorPalette.blue(4) - } - val backgroundColor = - remember(isDark) { - if (isDark) colorPalette.gray(4) else colorPalette.gray(11) - } + val borderColor = remember(isDark) { if (isDark) colorPalette.blue(6) else colorPalette.blue(4) } + val backgroundColor = remember(isDark) { if (isDark) colorPalette.gray(4) else colorPalette.gray(11) } Box( Modifier.size(28.dp, 28.dp) .background(backgroundColor, shape = CircleShape) - .border( - borderAlignment, - width, - borderColor, - CircleShape, - expand, - ), + .border(borderAlignment, width, borderColor, CircleShape, expand) ) Box( Modifier.size(72.dp, 28.dp) .background(backgroundColor, shape = RectangleShape) - .border( - borderAlignment, - width, - borderColor, - RectangleShape, - expand, - ), + .border(borderAlignment, width, borderColor, RectangleShape, expand) ) Box( Modifier.size(72.dp, 28.dp) .background(backgroundColor, shape = RoundedCornerShape(4.dp)) - .border( - borderAlignment, - width, - borderColor, - RoundedCornerShape(4.dp), - expand, - ), + .border(borderAlignment, width, borderColor, RoundedCornerShape(4.dp), expand) ) Box( Modifier.size(72.dp, 28.dp) .background(backgroundColor, shape = RoundedCornerShape(4.dp, 0.dp, 4.dp, 0.dp)) - .border( - borderAlignment, - width, - borderColor, - RoundedCornerShape(4.dp, 0.dp, 4.dp, 0.dp), - expand, - ), + .border(borderAlignment, width, borderColor, RoundedCornerShape(4.dp, 0.dp, 4.dp, 0.dp), expand) ) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Buttons.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Buttons.kt index 24d6edc27..a63439e07 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Buttons.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Buttons.kt @@ -32,9 +32,7 @@ import org.jetbrains.jewel.ui.painter.hints.Stroke @Composable fun Buttons() { - Column( - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { + Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { NormalButtons() var selectedIndex by remember { mutableIntStateOf(0) } @@ -52,29 +50,18 @@ private fun NormalButtons() { horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically, ) { - OutlinedButton(onClick = { }) { - Text("Outlined") - } + OutlinedButton(onClick = {}) { Text("Outlined") } - OutlinedButton(onClick = {}, enabled = false) { - Text("Outlined Disabled") - } + OutlinedButton(onClick = {}, enabled = false) { Text("Outlined Disabled") } - DefaultButton(onClick = {}) { - Text("Default") - } + DefaultButton(onClick = {}) { Text("Default") } - DefaultButton(onClick = {}, enabled = false) { - Text("Default disabled") - } + DefaultButton(onClick = {}, enabled = false) { Text("Default disabled") } } } @Composable -private fun IconButtons( - selected: Boolean, - onSelectableClick: () -> Unit, -) { +private fun IconButtons(selected: Boolean, onSelectableClick: () -> Unit) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), @@ -84,9 +71,7 @@ private fun IconButtons( Text("Focusable:") - IconButton(onClick = {}) { - PlatformIcon(AllIconsKeys.Actions.Close, contentDescription = "IconButton") - } + IconButton(onClick = {}) { PlatformIcon(AllIconsKeys.Actions.Close, contentDescription = "IconButton") } Text("Not focusable:") @@ -120,10 +105,7 @@ private fun IconButtons( } @Composable -private fun IconActionButtons( - selected: Boolean, - onSelectableClick: () -> Unit, -) { +private fun IconActionButtons(selected: Boolean, onSelectableClick: () -> Unit) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), @@ -169,14 +151,10 @@ private fun ActionButtons() { Text("With tooltip:") - ActionButton(onClick = {}, tooltip = { Text("I am a tooltip") }) { - Text("Hover me!") - } + ActionButton(onClick = {}, tooltip = { Text("I am a tooltip") }) { Text("Hover me!") } Text("Without tooltip:") - ActionButton(onClick = {}) { - Text("Do something") - } + ActionButton(onClick = {}) { Text("Do something") } } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Checkboxes.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Checkboxes.kt index 9166884da..8f729ff19 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Checkboxes.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Checkboxes.kt @@ -15,35 +15,46 @@ import org.jetbrains.jewel.ui.component.TriStateCheckboxRow @Composable fun Checkboxes() { - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { var checked by remember { mutableStateOf(ToggleableState.On) } - TriStateCheckboxRow("Checkbox", checked, { - checked = - when (checked) { - ToggleableState.On -> ToggleableState.Off - ToggleableState.Off -> ToggleableState.Indeterminate - ToggleableState.Indeterminate -> ToggleableState.On - } - }) - TriStateCheckboxRow("Error", checked, { - checked = - when (checked) { - ToggleableState.On -> ToggleableState.Off - ToggleableState.Off -> ToggleableState.Indeterminate - ToggleableState.Indeterminate -> ToggleableState.On - } - }, outline = Outline.Error) - TriStateCheckboxRow("Warning", checked, { - checked = - when (checked) { - ToggleableState.On -> ToggleableState.Off - ToggleableState.Off -> ToggleableState.Indeterminate - ToggleableState.Indeterminate -> ToggleableState.On - } - }, outline = Outline.Warning) + TriStateCheckboxRow( + "Checkbox", + checked, + { + checked = + when (checked) { + ToggleableState.On -> ToggleableState.Off + ToggleableState.Off -> ToggleableState.Indeterminate + ToggleableState.Indeterminate -> ToggleableState.On + } + }, + ) + TriStateCheckboxRow( + "Error", + checked, + { + checked = + when (checked) { + ToggleableState.On -> ToggleableState.Off + ToggleableState.Off -> ToggleableState.Indeterminate + ToggleableState.Indeterminate -> ToggleableState.On + } + }, + outline = Outline.Error, + ) + TriStateCheckboxRow( + "Warning", + checked, + { + checked = + when (checked) { + ToggleableState.On -> ToggleableState.Off + ToggleableState.Off -> ToggleableState.Indeterminate + ToggleableState.Indeterminate -> ToggleableState.On + } + }, + outline = Outline.Warning, + ) TriStateCheckboxRow("Disabled", checked, {}, enabled = false) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ChipsAndTree.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ChipsAndTree.kt index e9641acc1..28666f988 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ChipsAndTree.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ChipsAndTree.kt @@ -26,6 +26,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import kotlin.random.Random import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import org.jetbrains.jewel.foundation.lazy.SelectableLazyColumn @@ -43,7 +44,6 @@ import org.jetbrains.jewel.ui.component.RadioButtonChip import org.jetbrains.jewel.ui.component.Text import org.jetbrains.jewel.ui.component.ToggleableChip import org.jetbrains.jewel.ui.theme.colorPalette -import kotlin.random.Random @Composable fun ChipsAndTrees() { @@ -67,22 +67,16 @@ fun ChipsAndTrees() { @Composable fun SelectableLazyColumnSample() { - var listOfItems by remember { - mutableStateOf(emptyList()) - } + var listOfItems by remember { mutableStateOf(emptyList()) } LaunchedEffect(Unit) { @Suppress("InjectDispatcher") // Ok for demo code - launch(Dispatchers.Default) { - listOfItems = List(5_000_000) { "Item $it" } - } + launch(Dispatchers.Default) { listOfItems = List(5_000_000) { "Item $it" } } } val interactionSource = remember { MutableInteractionSource() } val state = rememberSelectableLazyListState() - Box( - modifier = Modifier.size(200.dp, 200.dp), - ) { + Box(modifier = Modifier.size(200.dp, 200.dp)) { if (listOfItems.isEmpty()) { CircularProgressIndicator(Modifier.align(Alignment.Center)) } else { @@ -91,26 +85,19 @@ fun SelectableLazyColumnSample() { modifier = Modifier.focusable(interactionSource = interactionSource), state = state, content = { - items( - count = listOfItems.size, - key = { index -> listOfItems[index] }, - ) { index -> + items(count = listOfItems.size, key = { index -> listOfItems[index] }) { index -> Text( text = listOfItems[index], modifier = - Modifier - .fillMaxWidth() + Modifier.fillMaxWidth() .then( when { isSelected && isActive -> Modifier.background(Color.Blue) isSelected && !isActive -> Modifier.background(Color.Gray) else -> Modifier - }, - ).clickable { - JewelLogger - .getInstance("ChipsAndTree") - .info("Click on $index") - }, + } + ) + .clickable { JewelLogger.getInstance("ChipsAndTree").info("Click on $index") }, ) } }, @@ -129,59 +116,29 @@ fun ChipsSample(modifier: Modifier = Modifier) { Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { var selectedIndex by remember { mutableStateOf(-1) } - RadioButtonChip( - selected = selectedIndex == 0, - onClick = { selectedIndex = 0 }, - enabled = true, - ) { + RadioButtonChip(selected = selectedIndex == 0, onClick = { selectedIndex = 0 }, enabled = true) { Text("First") } - RadioButtonChip( - selected = selectedIndex == 1, - onClick = { selectedIndex = 1 }, - enabled = true, - ) { + RadioButtonChip(selected = selectedIndex == 1, onClick = { selectedIndex = 1 }, enabled = true) { Text("Second") } - RadioButtonChip( - selected = selectedIndex == 2, - onClick = { selectedIndex = 2 }, - enabled = true, - ) { + RadioButtonChip(selected = selectedIndex == 2, onClick = { selectedIndex = 2 }, enabled = true) { Text("Third") } } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { var isChecked by remember { mutableStateOf(false) } - ToggleableChip( - checked = isChecked, - onClick = { - isChecked = it - }, - enabled = true, - ) { - Text("Toggleable") - } + ToggleableChip(checked = isChecked, onClick = { isChecked = it }, enabled = true) { Text("Toggleable") } var count by remember { mutableStateOf(1) } - Chip( - enabled = true, - onClick = { count++ }, - ) { - Text("Clicks: $count") - } + Chip(enabled = true, onClick = { count++ }) { Text("Clicks: $count") } } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Chip( - enabled = false, - onClick = {}, - ) { - Text("Disabled") - } + Chip(enabled = false, onClick = {}) { Text("Disabled") } } } } @@ -206,18 +163,17 @@ fun TreeSample(modifier: Modifier = Modifier) { addLeaf("leaf 3.1") addLeaf("leaf 3.2") } - }, + } ) } OutlinedButton({ - tree = - buildTree { - addNode("root ${Random.nextInt()}") { - addLeaf("leaf 1") - addLeaf("leaf 2") - } + tree = buildTree { + addNode("root ${Random.nextInt()}") { + addLeaf("leaf 1") + addLeaf("leaf 2") } + } }) { Text("Update tree") } @@ -236,9 +192,7 @@ fun TreeSample(modifier: Modifier = Modifier) { onElementClick = {}, onElementDoubleClick = {}, ) { element -> - Box(Modifier.fillMaxWidth()) { - Text(element.data, Modifier.padding(2.dp)) - } + Box(Modifier.fillMaxWidth()) { Text(element.data, Modifier.padding(2.dp)) } } } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Dropdowns.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Dropdowns.kt index c21fc7421..81c73be1e 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Dropdowns.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Dropdowns.kt @@ -9,88 +9,61 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.unit.dp +import kotlin.random.Random import org.jetbrains.jewel.ui.Outline import org.jetbrains.jewel.ui.component.Dropdown import org.jetbrains.jewel.ui.component.Text import org.jetbrains.jewel.ui.component.separator import org.jetbrains.jewel.ui.component.styling.DropdownStyle import org.jetbrains.jewel.ui.icons.AllIconsKeys -import kotlin.random.Random @Composable fun Dropdowns() { - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - val items = - remember { - listOf( - "Light", - "Dark", - "---", - "High Contrast", - "Darcula", - "IntelliJ Light", - ) - } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { + val items = remember { listOf("Light", "Dark", "---", "High Contrast", "Darcula", "IntelliJ Light") } var selected by remember { mutableStateOf(items.first()) } - Dropdown( - enabled = false, - menuContent = {}, - ) { - Text("Disabled") - } + Dropdown(enabled = false, menuContent = {}) { Text("Disabled") } Dropdown( menuContent = { items.forEach { if (it == "---") { separator() } else { - selectableItem( - selected = selected == it, - onClick = { selected = it }, - ) { - Text(it) - } + selectableItem(selected = selected == it, onClick = { selected = it }) { Text(it) } } } separator() - submenu(submenu = { - items.forEach { - if (it == "---") { - separator() - } else { - selectableItem( - selected = selected == it, - onClick = { selected = it }, - ) { - Text(it) - } - } - } - separator() - submenu(submenu = { + submenu( + submenu = { items.forEach { if (it == "---") { separator() } else { - selectableItem( - selected = selected == it, - onClick = { selected = it }, - ) { - Text(it) + selectableItem(selected = selected == it, onClick = { selected = it }) { Text(it) } + } + } + separator() + submenu( + submenu = { + items.forEach { + if (it == "---") { + separator() + } else { + selectableItem(selected = selected == it, onClick = { selected = it }) { + Text(it) + } + } } } + ) { + Text("Submenu2") } - }) { - Text("Submenu2") } - }) { + ) { Text("Submenu") } - }, + } ) { Text(selected) } @@ -101,12 +74,7 @@ fun Dropdowns() { if (it == "---") { separator() } else { - selectableItem( - selected = selected == it, - onClick = { selected = it }, - ) { - Text(it) - } + selectableItem(selected = selected == it, onClick = { selected = it }) { Text(it) } } } }, @@ -126,42 +94,17 @@ fun Dropdowns() { if (Random.nextBoolean()) { null } else { - dropdownKeybindingsSample.shuffled() - .take(2) - .toSet() + dropdownKeybindingsSample.shuffled().take(2).toSet() }, selected = false, - onClick = { }, + onClick = {}, ) { Text(it) } } } - submenu(submenu = { - items.forEach { - if (it == "---") { - separator() - } else { - selectableItem( - iconKey = dropdownIconsSample.random(), - iconClass = DropdownStyle::class.java, - keybinding = - if (Random.nextBoolean()) { - null - } else { - dropdownKeybindingsSample.shuffled() - .take(2) - .toSet() - }, - selected = false, - onClick = { }, - ) { - Text(it) - } - } - } - separator() - submenu(submenu = { + submenu( + submenu = { items.forEach { if (it == "---") { separator() @@ -169,20 +112,45 @@ fun Dropdowns() { selectableItem( iconKey = dropdownIconsSample.random(), iconClass = DropdownStyle::class.java, + keybinding = + if (Random.nextBoolean()) { + null + } else { + dropdownKeybindingsSample.shuffled().take(2).toSet() + }, selected = false, - onClick = { }, + onClick = {}, ) { Text(it) } } } - }) { - Text("Submenu2") + separator() + submenu( + submenu = { + items.forEach { + if (it == "---") { + separator() + } else { + selectableItem( + iconKey = dropdownIconsSample.random(), + iconClass = DropdownStyle::class.java, + selected = false, + onClick = {}, + ) { + Text(it) + } + } + } + } + ) { + Text("Submenu2") + } } - }) { + ) { Text("Submenu") } - }, + } ) { Text("With icons") } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Links.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Links.kt index ad5beac09..22afcb4ca 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Links.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Links.kt @@ -32,56 +32,32 @@ fun Links() { } } - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { Link("Link", {}) Link("Always underlined", {}, style = alwaysUnderlinedStyle) ExternalLink("ExternalLink", {}) - val items = - remember { - listOf( - "Light", - "Dark", - "---", - "High Contrast", - "Darcula", - "IntelliJ Light", - ) - } + val items = remember { listOf("Light", "Dark", "---", "High Contrast", "Darcula", "IntelliJ Light") } var selected by remember { mutableStateOf(items.first()) } DropdownLink("DropdownLink") { items.forEach { if (it == "---") { separator() } else { - selectableItem( - selected = selected == it, - onClick = { - selected = it - }, - ) { - Text(it) - } + selectableItem(selected = selected == it, onClick = { selected = it }) { Text(it) } } } } } - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { Link("Link", {}, enabled = false) Link("Always underlined", {}, style = alwaysUnderlinedStyle, enabled = false) ExternalLink("ExternalLink", {}, enabled = false) - DropdownLink("DropdownLink", enabled = false) { - } + DropdownLink("DropdownLink", enabled = false) {} } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ProgressBar.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ProgressBar.kt index 9820b033f..44579af96 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ProgressBar.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/ProgressBar.kt @@ -27,19 +27,20 @@ import org.jetbrains.jewel.ui.component.Text @Composable fun ProgressBar() { val transition = rememberInfiniteTransition() - val currentOffset by transition.animateFloat( - initialValue = 0f, - targetValue = 1f, - animationSpec = - infiniteRepeatable( - animation = - keyframes { - durationMillis = 4000 - 0f at 1000 - 1f at 3000 - }, - ), - ) + val currentOffset by + transition.animateFloat( + initialValue = 0f, + targetValue = 1f, + animationSpec = + infiniteRepeatable( + animation = + keyframes { + durationMillis = 4000 + 0f at 1000 + 1f at 3000 + } + ), + ) var intermittentProgress by remember { mutableStateOf(0f) } LaunchedEffect(Unit) { while (true) { diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/RadioButtons.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/RadioButtons.kt index bb3c16b1f..4d5c40177 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/RadioButtons.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/RadioButtons.kt @@ -14,36 +14,14 @@ import org.jetbrains.jewel.ui.component.RadioButtonRow @Composable fun RadioButtons() { - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { var index by remember { mutableStateOf(0) } - RadioButtonRow( - text = "Default", - selected = index == 0, - onClick = { index = 0 }, - ) + RadioButtonRow(text = "Default", selected = index == 0, onClick = { index = 0 }) - RadioButtonRow( - text = "Error", - selected = index == 1, - onClick = { index = 1 }, - outline = Outline.Error, - ) + RadioButtonRow(text = "Error", selected = index == 1, onClick = { index = 1 }, outline = Outline.Error) - RadioButtonRow( - text = "Warning", - selected = index == 2, - onClick = { index = 2 }, - outline = Outline.Warning, - ) + RadioButtonRow(text = "Warning", selected = index == 2, onClick = { index = 2 }, outline = Outline.Warning) - RadioButtonRow( - text = "Disabled", - selected = index == 3, - onClick = { index = 3 }, - enabled = false, - ) + RadioButtonRow(text = "Disabled", selected = index == 3, onClick = { index = 3 }, enabled = false) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Scrollbars.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Scrollbars.kt index dd56a9a9f..a85e31d75 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Scrollbars.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Scrollbars.kt @@ -27,6 +27,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import java.util.Locale import org.jetbrains.jewel.foundation.Stroke import org.jetbrains.jewel.foundation.modifier.border import org.jetbrains.jewel.foundation.theme.JewelTheme @@ -49,7 +50,6 @@ import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior import org.jetbrains.jewel.ui.theme.textAreaStyle import org.jetbrains.skiko.OS import org.jetbrains.skiko.hostOs -import java.util.Locale @Composable fun Scrollbars() { @@ -78,7 +78,7 @@ fun Scrollbars() { trackClickBehavior = clickBehavior, scrollbarVisibility = ScrollbarVisibility.WhenScrolling.default(), ) - }, + } ) } @@ -127,10 +127,7 @@ private fun SettingsRow( } @Composable -private fun LazyColumnWithScrollbar( - style: ScrollbarStyle, - modifier: Modifier, -) { +private fun LazyColumnWithScrollbar(style: ScrollbarStyle, modifier: Modifier) { Column(modifier) { Text("LazyColumn", style = Typography.h2TextStyle()) @@ -172,10 +169,7 @@ private fun LazyColumnWithScrollbar( } @Composable -private fun ColumnWithScrollbar( - style: ScrollbarStyle, - modifier: Modifier, -) { +private fun ColumnWithScrollbar(style: ScrollbarStyle, modifier: Modifier) { Column(modifier) { Text("Column", fontSize = 18.sp) Spacer(Modifier.height(8.dp)) @@ -186,7 +180,7 @@ private fun ColumnWithScrollbar( modifier = Modifier.background(JewelTheme.textAreaStyle.colors.background) .verticalScroll(scrollState) - .align(Alignment.CenterStart), + .align(Alignment.CenterStart) ) { LIST_ITEMS.forEachIndexed { index, line -> Text( @@ -207,10 +201,7 @@ private fun ColumnWithScrollbar( } @Composable -private fun HorizontalScrollbarContent( - scrollbarStyle: ScrollbarStyle, - modifier: Modifier, -) { +private fun HorizontalScrollbarContent(scrollbarStyle: ScrollbarStyle, modifier: Modifier) { HorizontallyScrollableContainer( modifier = modifier.border(Stroke.Alignment.Outside, 1.dp, JewelTheme.globalColors.borders.normal), style = scrollbarStyle, diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/SegmentedControls.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/SegmentedControls.kt index 3529f45db..5ba8646f3 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/SegmentedControls.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/SegmentedControls.kt @@ -21,22 +21,14 @@ fun SegmentedControls() { buttonIds.map { index -> SegmentedControlButtonData( selected = index == selectedButtonIndex, - content = { _ -> - Text("Button ${index + 1}") - }, + content = { _ -> Text("Button ${index + 1}") }, onSelect = { selectedButtonIndex = index }, ) } } Column(verticalArrangement = Arrangement.spacedBy(16.dp)) { - SegmentedControl( - buttons = buttons, - enabled = true, - ) + SegmentedControl(buttons = buttons, enabled = true) - SegmentedControl( - buttons = buttons, - enabled = false, - ) + SegmentedControl(buttons = buttons, enabled = false) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Slider.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Slider.kt index ed127f2f0..7f428f04c 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Slider.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Slider.kt @@ -10,32 +10,14 @@ import org.jetbrains.jewel.ui.component.Slider @Composable fun Sliders() { var value1 by remember { mutableStateOf(.45f) } - Slider( - value = value1, - onValueChange = { value1 = it }, - ) + Slider(value = value1, onValueChange = { value1 = it }) var value2 by remember { mutableStateOf(.7f) } - Slider( - value = value2, - onValueChange = { value2 = it }, - enabled = false, - ) + Slider(value = value2, onValueChange = { value2 = it }, enabled = false) var value3 by remember { mutableStateOf(33f) } - Slider( - value = value3, - onValueChange = { value3 = it }, - steps = 10, - valueRange = 0f..100f, - ) + Slider(value = value3, onValueChange = { value3 = it }, steps = 10, valueRange = 0f..100f) var value4 by remember { mutableStateOf(23f) } - Slider( - value = value4, - onValueChange = { value4 = it }, - steps = 10, - valueRange = 0f..100f, - enabled = false, - ) + Slider(value = value4, onValueChange = { value4 = it }, steps = 10, valueRange = 0f..100f, enabled = false) } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tabs.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tabs.kt index 8625912dd..53d137659 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tabs.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tabs.kt @@ -20,6 +20,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import kotlin.math.max import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.samples.standalone.StandaloneSampleIcons import org.jetbrains.jewel.ui.component.Icon @@ -35,7 +36,6 @@ import org.jetbrains.jewel.ui.painter.rememberResourcePainterProvider import org.jetbrains.jewel.ui.theme.defaultTabStyle import org.jetbrains.jewel.ui.theme.editorTabStyle import org.jetbrains.jewel.ui.util.thenIf -import kotlin.math.max @Composable fun Tabs() { @@ -122,7 +122,7 @@ private fun EditorTabShowcase() { drawCircle(color = Color.Magenta.copy(alpha = .4f), radius = 6.dp.toPx()) } } - }, + } ) }, onClose = { @@ -147,11 +147,7 @@ private fun EditorTabShowcase() { } @Composable -private fun TabStripWithAddButton( - tabs: List, - style: TabStyle, - onAddClick: () -> Unit, -) { +private fun TabStripWithAddButton(tabs: List, style: TabStyle, onAddClick: () -> Unit) { Row(verticalAlignment = Alignment.CenterVertically) { TabStrip(tabs, style, modifier = Modifier.weight(1f)) diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextAreas.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextAreas.kt index 3930fa2ed..aae824e1e 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextAreas.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextAreas.kt @@ -35,10 +35,7 @@ fun TextAreas() { horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top, ) { - TextArea( - state = rememberTextFieldState(LOREM_IPSUM), - modifier = Modifier.weight(1f).fillMaxHeight(), - ) + TextArea(state = rememberTextFieldState(LOREM_IPSUM), modifier = Modifier.weight(1f).fillMaxHeight()) TextArea( state = rememberTextFieldState(LOREM_IPSUM), diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextFields.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextFields.kt index 3dd13e819..9fdac4e5b 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextFields.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/TextFields.kt @@ -38,22 +38,12 @@ import org.jetbrains.jewel.ui.painter.hints.Stateful @Composable fun TextFields() { - Row( - horizontalArrangement = Arrangement.spacedBy(10.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) { val state1 = rememberTextFieldState("TextField") - TextField( - state = state1, - modifier = Modifier.width(200.dp), - ) + TextField(state = state1, modifier = Modifier.width(200.dp)) val state2 = rememberTextFieldState("") - TextField( - state = state2, - placeholder = { Text("Placeholder") }, - modifier = Modifier.width(200.dp), - ) + TextField(state = state2, placeholder = { Text("Placeholder") }, modifier = Modifier.width(200.dp)) val state3 = rememberTextFieldState("") TextField( @@ -64,10 +54,7 @@ fun TextFields() { ) } - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) { val state1 = rememberTextFieldState("") TextField( state = state1, @@ -77,17 +64,10 @@ fun TextFields() { ) val state2 = rememberTextFieldState("Disabled") - TextField( - state = state2, - enabled = false, - modifier = Modifier.width(200.dp), - ) + TextField(state = state2, enabled = false, modifier = Modifier.width(200.dp)) } - Row( - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalAlignment = Alignment.Top, - ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) { val state1 = rememberTextFieldState("") TextField( state = state1, @@ -119,10 +99,7 @@ fun TextFields() { } @Composable -private fun CloseIconButton( - isVisible: Boolean, - onClick: () -> Unit, -) { +private fun CloseIconButton(isVisible: Boolean, onClick: () -> Unit) { Box(Modifier.size(16.dp)) { AnimatedVisibility( visible = isVisible, @@ -133,16 +110,9 @@ private fun CloseIconButton( val isDark = JewelTheme.isDark val colors = noBackgroundIconButtonColors(isDark) - val style = - remember(isDark, colors) { - IconButtonStyle(colors, IconButtonMetrics.defaults()) - } + val style = remember(isDark, colors) { IconButtonStyle(colors, IconButtonMetrics.defaults()) } - IconButton( - onClick, - style = style, - modifier = Modifier.pointerHoverIcon(PointerIcon.Default), - ) { state -> + IconButton(onClick, style = style, modifier = Modifier.pointerHoverIcon(PointerIcon.Default)) { state -> Icon(AllIconsKeys.Actions.Close, contentDescription = "Clear", hint = Stateful(state)) } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tooltips.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tooltips.kt index a79e2f7d6..d412cf266 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tooltips.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/component/Tooltips.kt @@ -11,9 +11,7 @@ import org.jetbrains.jewel.ui.component.Tooltip @Composable fun Tooltips() { - Tooltip(tooltip = { - Text("This is a tooltip") - }) { + Tooltip(tooltip = { Text("This is a tooltip") }) { Text(modifier = Modifier.border(1.dp, JewelTheme.globalColors.borders.normal).padding(4.dp), text = "Hover Me!") } } diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/JewelReadme.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/JewelReadme.kt index 4dea206e9..b49818137 100755 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/JewelReadme.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/JewelReadme.kt @@ -367,4 +367,5 @@ 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. ``` - """.trimIndent() + """ + .trimIndent() diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownEditor.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownEditor.kt index 51daef3c7..7fe77f42f 100755 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownEditor.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownEditor.kt @@ -33,37 +33,22 @@ import org.jetbrains.jewel.ui.component.TextArea import org.jetbrains.jewel.ui.icons.AllIconsKeys @Composable -internal fun MarkdownEditor( - state: TextFieldState, - modifier: Modifier = Modifier, -) { +internal fun MarkdownEditor(state: TextFieldState, modifier: Modifier = Modifier) { Column(modifier) { ControlsRow( modifier = Modifier.fillMaxWidth().background(JewelTheme.globalColors.panelBackground).padding(8.dp), onLoadMarkdown = { state.edit { replace(0, length, it) } }, ) Divider(orientation = Orientation.Horizontal) - Editor( - state = state, - modifier = Modifier.fillMaxWidth().weight(1f), - ) + Editor(state = state, modifier = Modifier.fillMaxWidth().weight(1f)) } } @Composable -private fun ControlsRow( - modifier: Modifier = Modifier, - onLoadMarkdown: (String) -> Unit, -) { - Row( - modifier.horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { +private fun ControlsRow(modifier: Modifier = Modifier, onLoadMarkdown: (String) -> Unit) { + Row(modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(16.dp)) { var showFilePicker by remember { mutableStateOf(false) } - OutlinedButton( - onClick = { showFilePicker = true }, - modifier = Modifier.padding(start = 2.dp), - ) { + OutlinedButton(onClick = { showFilePicker = true }, modifier = Modifier.padding(start = 2.dp)) { Text("Load file...") } @@ -90,10 +75,13 @@ private fun ControlsRow( if (showPresets) { var selected by remember { mutableStateOf("Jewel readme") } - PopupMenu(onDismissRequest = { - showPresets = false - false - }, horizontalAlignment = Alignment.Start) { + PopupMenu( + onDismissRequest = { + showPresets = false + false + }, + horizontalAlignment = Alignment.Start, + ) { selectableItem( selected = selected == "Jewel readme", onClick = { @@ -120,10 +108,7 @@ private fun ControlsRow( } @Composable -private fun Editor( - state: TextFieldState, - modifier: Modifier = Modifier, -) { +private fun Editor(state: TextFieldState, modifier: Modifier = Modifier) { Box(modifier) { TextArea( state = state, diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownPreview.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownPreview.kt index 9eaaacb0c..98f5ab893 100755 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownPreview.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/view/markdown/MarkdownPreview.kt @@ -12,6 +12,8 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import java.awt.Desktop +import java.net.URI import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.jewel.foundation.theme.JewelTheme @@ -33,18 +35,12 @@ import org.jetbrains.jewel.markdown.rendering.MarkdownBlockRenderer import org.jetbrains.jewel.markdown.rendering.MarkdownStyling import org.jetbrains.jewel.ui.component.VerticallyScrollableContainer import org.jetbrains.jewel.ui.component.scrollbarContentSafePadding -import java.awt.Desktop -import java.net.URI @Composable -internal fun MarkdownPreview( - modifier: Modifier = Modifier, - rawMarkdown: CharSequence, -) { +internal fun MarkdownPreview(modifier: Modifier = Modifier, rawMarkdown: CharSequence) { val isDark = JewelTheme.isDark - val markdownStyling = - remember(isDark) { if (isDark) MarkdownStyling.dark() else MarkdownStyling.light() } + val markdownStyling = remember(isDark) { if (isDark) MarkdownStyling.dark() else MarkdownStyling.light() } var markdownBlocks by remember { mutableStateOf(emptyList()) } val extensions = remember { listOf(GitHubAlertProcessorExtension, AutolinkProcessorExtension) } @@ -55,13 +51,11 @@ internal fun MarkdownPreview( val processor = remember { MarkdownProcessor(extensions, editorMode = true) } LaunchedEffect(rawMarkdown) { - // TODO you may want to debounce or drop on backpressure, in real usages. You should also not do this + // TODO you may want to debounce or drop on backpressure, in real usages. You should also + // not do this // in the UI to begin with. @Suppress("InjectDispatcher") // This should never go in the composable IRL - markdownBlocks = - withContext(Dispatchers.Default) { - processor.processMarkdownDocument(rawMarkdown.toString()) - } + markdownBlocks = withContext(Dispatchers.Default) { processor.processMarkdownDocument(rawMarkdown.toString()) } } val blockRenderer = diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/ComponentsViewModel.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/ComponentsViewModel.kt index c9a13c5db..7af0a80e9 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/ComponentsViewModel.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/ComponentsViewModel.kt @@ -30,26 +30,14 @@ object ComponentsViewModel { private val componentsMenuItems = mutableStateListOf( - ViewInfo( - title = "Buttons", - iconKey = StandaloneSampleIcons.Components.button, - content = { Buttons() }, - ), + ViewInfo(title = "Buttons", iconKey = StandaloneSampleIcons.Components.button, content = { Buttons() }), ViewInfo( title = "Radio Buttons", iconKey = StandaloneSampleIcons.Components.radioButton, content = { RadioButtons() }, ), - ViewInfo( - title = "Checkboxes", - iconKey = StandaloneSampleIcons.Components.checkbox, - content = { Checkboxes() }, - ), - ViewInfo( - title = "Dropdowns", - iconKey = StandaloneSampleIcons.Components.comboBox, - content = { Dropdowns() }, - ), + ViewInfo(title = "Checkboxes", iconKey = StandaloneSampleIcons.Components.checkbox, content = { Checkboxes() }), + ViewInfo(title = "Dropdowns", iconKey = StandaloneSampleIcons.Components.comboBox, content = { Dropdowns() }), ViewInfo( title = "Chips and trees", iconKey = StandaloneSampleIcons.Components.tree, @@ -60,54 +48,22 @@ private val componentsMenuItems = iconKey = StandaloneSampleIcons.Components.progressBar, content = { ProgressBar() }, ), - ViewInfo( - title = "Icons", - iconKey = StandaloneSampleIcons.Components.toolbar, - content = { Icons() }, - ), - ViewInfo( - title = "Links", - iconKey = StandaloneSampleIcons.Components.links, - content = { Links() }, - ), - ViewInfo( - title = "Borders", - iconKey = StandaloneSampleIcons.Components.borders, - content = { Borders() }, - ), + ViewInfo(title = "Icons", iconKey = StandaloneSampleIcons.Components.toolbar, content = { Icons() }), + ViewInfo(title = "Links", iconKey = StandaloneSampleIcons.Components.links, content = { Links() }), + ViewInfo(title = "Borders", iconKey = StandaloneSampleIcons.Components.borders, content = { Borders() }), ViewInfo( title = "Segmented Controls", iconKey = StandaloneSampleIcons.Components.segmentedControls, content = { SegmentedControls() }, ), - ViewInfo( - title = "Sliders", - iconKey = StandaloneSampleIcons.Components.slider, - content = { Sliders() }, - ), - ViewInfo( - title = "Tabs", - iconKey = StandaloneSampleIcons.Components.tabs, - content = { Tabs() }, - ), - ViewInfo( - title = "Tooltips", - iconKey = StandaloneSampleIcons.Components.tooltip, - content = { Tooltips() }, - ), - ViewInfo( - title = "TextAreas", - iconKey = StandaloneSampleIcons.Components.textArea, - content = { TextAreas() }, - ), + ViewInfo(title = "Sliders", iconKey = StandaloneSampleIcons.Components.slider, content = { Sliders() }), + ViewInfo(title = "Tabs", iconKey = StandaloneSampleIcons.Components.tabs, content = { Tabs() }), + ViewInfo(title = "Tooltips", iconKey = StandaloneSampleIcons.Components.tooltip, content = { Tooltips() }), + ViewInfo(title = "TextAreas", iconKey = StandaloneSampleIcons.Components.textArea, content = { TextAreas() }), ViewInfo( title = "TextFields", iconKey = StandaloneSampleIcons.Components.textField, content = { TextFields() }, ), - ViewInfo( - title = "Scrollbars", - iconKey = StandaloneSampleIcons.Components.scrollbar, - content = { Scrollbars() }, - ), + ViewInfo(title = "Scrollbars", iconKey = StandaloneSampleIcons.Components.scrollbar, content = { Scrollbars() }), ) diff --git a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/MainViewModel.kt b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/MainViewModel.kt index e7449031e..784de75fb 100644 --- a/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/MainViewModel.kt +++ b/samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/MainViewModel.kt @@ -50,7 +50,8 @@ private val mainMenuItems = ViewInfo( title = "Markdown", iconKey = StandaloneSampleIcons.markdown, - keyboardShortcut = KeyBinding(macOs = setOf("⌥", "M"), windows = setOf("Alt", "M"), linux = setOf("Alt", "M")), + keyboardShortcut = + KeyBinding(macOs = setOf("⌥", "M"), windows = setOf("Alt", "M"), linux = setOf("Alt", "M")), content = { MarkdownDemo() }, ), ) diff --git a/ui/build.gradle.kts b/ui/build.gradle.kts index 2d188b4cf..7a4d5010b 100644 --- a/ui/build.gradle.kts +++ b/ui/build.gradle.kts @@ -19,9 +19,7 @@ dependencies { iconGeneration(libs.intellijPlatform.util.ui) iconGeneration(libs.intellijPlatform.icons) testImplementation(compose.desktop.uiTestJUnit4) - testImplementation(compose.desktop.currentOs) { - exclude(group = "org.jetbrains.compose.material") - } + testImplementation(compose.desktop.currentOs) { exclude(group = "org.jetbrains.compose.material") } } intelliJIconKeysGenerator { @@ -37,4 +35,4 @@ tasks.withType { tasks.withType { include("src/**") // Excluding build/ doesn't work for some reason -} +} \ No newline at end of file diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/ComponentStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/ComponentStyling.kt index aaa4083b0..bb484ad80 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/ComponentStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/ComponentStyling.kt @@ -9,31 +9,30 @@ public interface ComponentStyling { return with(StaticComponentStyling(values = values)) } - public fun provide(provider: @Composable () -> Array>): ComponentStyling = with(LazyComponentStyling(provider)) + public fun provide(provider: @Composable () -> Array>): ComponentStyling = + with(LazyComponentStyling(provider)) public fun with(styling: ComponentStyling): ComponentStyling { if (styling is Companion) return this return CombinedComponentStyling(this, styling) } - public fun with(styling: @Composable () -> ComponentStyling): ComponentStyling = with(LazyComponentStyling { styling().styles() }) + public fun with(styling: @Composable () -> ComponentStyling): ComponentStyling = + with(LazyComponentStyling { styling().styles() }) - @Composable - public fun styles(): Array> + @Composable public fun styles(): Array> public companion object : ComponentStyling { override fun with(styling: ComponentStyling): ComponentStyling = styling - @Composable - override fun styles(): Array> = emptyArray() + @Composable override fun styles(): Array> = emptyArray() override fun toString(): String = "ComponentStyleProvider" } } private class StaticComponentStyling(private val values: Array>) : ComponentStyling { - @Composable - override fun styles(): Array> = values + @Composable override fun styles(): Array> = values override fun equals(other: Any?): Boolean = other is StaticComponentStyling && values.contentEquals(other.values) @@ -43,8 +42,7 @@ private class StaticComponentStyling(private val values: Array Array>) : ComponentStyling { - @Composable - override fun styles(): Array> = provider() + @Composable override fun styles(): Array> = provider() override fun equals(other: Any?): Boolean = other is LazyComponentStyling && provider == other.provider @@ -53,14 +51,14 @@ private class LazyComponentStyling(val provider: @Composable () -> Array> = (left.styles().toList() + right.styles().toList()).toTypedArray() + override fun styles(): Array> = + (left.styles().toList() + right.styles().toList()).toTypedArray() - override fun equals(other: Any?): Boolean = other is CombinedComponentStyling && left == other.left && right == other.right + override fun equals(other: Any?): Boolean = + other is CombinedComponentStyling && left == other.left && right == other.right override fun hashCode(): Int = left.hashCode() + 31 * right.hashCode() diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/Outline.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/Outline.kt index 8111cfdf7..4a338be61 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/Outline.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/Outline.kt @@ -13,14 +13,10 @@ import org.jetbrains.jewel.ui.util.thenIf public enum class Outline { None, Warning, - Error, - ; + Error; public companion object { - public fun of( - warning: Boolean, - error: Boolean, - ): Outline = + public fun of(warning: Boolean, error: Boolean): Outline = when { error -> Error warning -> Warning diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ActionButton.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ActionButton.kt index da681a15a..1c22571ec 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ActionButton.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ActionButton.kt @@ -42,17 +42,8 @@ public fun ActionButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { - CoreActionButton( - onClick, - enabled, - focusable, - style, - interactionSource, - modifier, - ) { - Box(Modifier.padding(contentPadding)) { - content() - } + CoreActionButton(onClick, enabled, focusable, style, interactionSource, modifier) { + Box(Modifier.padding(contentPadding)) { content() } } } @@ -70,12 +61,7 @@ public fun ActionButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit, ) { - Tooltip( - tooltip, - style = tooltipStyle, - tooltipPlacement = tooltipPlacement, - modifier = modifier, - ) { + Tooltip(tooltip, style = tooltipStyle, tooltipPlacement = tooltipPlacement, modifier = modifier) { CoreActionButton( onClick = onClick, enabled = enabled, @@ -83,9 +69,7 @@ public fun ActionButton( style = style, interactionSource = interactionSource, ) { - Box(Modifier.padding(contentPadding)) { - content() - } + Box(Modifier.padding(contentPadding)) { content() } } } } @@ -100,7 +84,5 @@ private fun CoreActionButton( modifier: Modifier = Modifier, content: @Composable () -> Unit, ) { - IconButton(onClick, modifier, enabled, focusable, style, interactionSource) { - content() - } + IconButton(onClick, modifier, enabled, focusable, style, interactionSource) { content() } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Button.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Button.kt index b29821842..1ba64f42e 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Button.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Button.kt @@ -94,9 +94,7 @@ private fun ButtonImpl( textStyle: TextStyle, content: @Composable RowScope.() -> Unit, ) { - var buttonState by remember(interactionSource) { - mutableStateOf(ButtonState.of(enabled = enabled)) - } + var buttonState by remember(interactionSource) { mutableStateOf(ButtonState.of(enabled = enabled)) } remember(enabled) { buttonState = buttonState.copy(enabled = enabled) } @@ -104,8 +102,8 @@ private fun ButtonImpl( interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> buttonState = buttonState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> - buttonState = buttonState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> buttonState = buttonState.copy(pressed = false) is HoverInteraction.Enter -> buttonState = buttonState.copy(hovered = true) is HoverInteraction.Exit -> buttonState = buttonState.copy(hovered = false) @@ -180,14 +178,7 @@ public value class ButtonState(public val state: ULong) : FocusableComponentStat pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): ButtonState = - of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): ButtonState = of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, isHovered=$isHovered, " + @@ -206,7 +197,7 @@ public value class ButtonState(public val state: ULong) : FocusableComponentStat (if (focused) Focused else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Checkbox.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Checkbox.kt index 38551a526..2adf1da86 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Checkbox.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Checkbox.kt @@ -269,13 +269,9 @@ private fun CheckboxImpl( verticalAlignment: Alignment.Vertical, content: (@Composable RowScope.() -> Unit)?, ) { - var checkboxState by remember { - mutableStateOf(CheckboxState.of(toggleableState = state, enabled = enabled)) - } + var checkboxState by remember { mutableStateOf(CheckboxState.of(toggleableState = state, enabled = enabled)) } - remember(state, enabled) { - checkboxState = checkboxState.copy(toggleableState = state, enabled = enabled) - } + remember(state, enabled) { checkboxState = checkboxState.copy(toggleableState = state, enabled = enabled) } val swingCompatMode = JewelTheme.isSwingCompatMode LaunchedEffect(interactionSource, swingCompatMode) { @@ -283,8 +279,7 @@ private fun CheckboxImpl( when (interaction) { is PressInteraction.Press -> checkboxState = checkboxState.copy(pressed = !swingCompatMode) is PressInteraction.Cancel, - is PressInteraction.Release, - -> checkboxState = checkboxState.copy(pressed = false) + is PressInteraction.Release -> checkboxState = checkboxState.copy(pressed = false) is HoverInteraction.Enter -> checkboxState = checkboxState.copy(hovered = !swingCompatMode) is HoverInteraction.Exit -> checkboxState = checkboxState.copy(hovered = false) @@ -305,25 +300,27 @@ private fun CheckboxImpl( ) val checkBoxImageModifier = Modifier.size(metrics.checkboxSize) - val outlineModifier = Modifier.size(metrics.outlineSize) - .offset(metrics.outlineOffset.x, metrics.outlineOffset.y) - .outline( - state = checkboxState, - outline = outline, - outlineShape = RoundedCornerShape(metrics.checkboxCornerSize), - alignment = Stroke.Alignment.Center, - ) + val outlineModifier = + Modifier.size(metrics.outlineSize) + .offset(metrics.outlineOffset.x, metrics.outlineOffset.y) + .outline( + state = checkboxState, + outline = outline, + outlineShape = RoundedCornerShape(metrics.checkboxCornerSize), + alignment = Stroke.Alignment.Center, + ) val painterProvider = rememberResourcePainterProvider(icons.checkbox) - val checkboxPainter by painterProvider.getPainter( - if (checkboxState.toggleableState == ToggleableState.Indeterminate) { - CheckBoxIndeterminate - } else { - PainterHint.None - }, - Selected(checkboxState.toggleableState == ToggleableState.On), - Stateful(checkboxState), - ) + val checkboxPainter by + painterProvider.getPainter( + if (checkboxState.toggleableState == ToggleableState.Indeterminate) { + CheckBoxIndeterminate + } else { + PainterHint.None + }, + Selected(checkboxState.toggleableState == ToggleableState.On), + Stateful(checkboxState), + ) if (content == null) { Box(wrapperModifier, contentAlignment = Alignment.TopStart) { @@ -346,9 +343,7 @@ private fun CheckboxImpl( LocalTextStyle provides textStyle.copy(color = contentColor.takeOrElse { textStyle.color }), LocalContentColor provides contentColor.takeOrElse { LocalContentColor.current }, ) { - Row(contentModifier) { - content() - } + Row(contentModifier) { content() } } } } @@ -360,11 +355,7 @@ private object CheckBoxIndeterminate : PainterSuffixHint() { } @Composable -private fun CheckBoxImage( - modifier: Modifier, - checkboxPainter: Painter, - checkBoxModifier: Modifier, -) { +private fun CheckBoxImage(modifier: Modifier, checkboxPainter: Painter, checkBoxModifier: Modifier) { Box(modifier, contentAlignment = Alignment.Center) { Image(checkboxPainter, contentDescription = null, modifier = checkBoxModifier) } @@ -430,7 +421,7 @@ public value class CheckboxState(private val state: ULong) : ToggleableComponent (if (pressed) Pressed else 0UL) or (if (toggleableState != ToggleableState.Off) Selected else 0UL) or (if (toggleableState == ToggleableState.Indeterminate) Indeterminate else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Chip.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Chip.kt index 249c31885..0fae3e25e 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Chip.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Chip.kt @@ -57,13 +57,13 @@ public fun Chip( selected = selected, style = style, modifier = - modifier.clickable( - onClick = onClick, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ), + modifier.clickable( + onClick = onClick, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ), content = content, ) } @@ -84,14 +84,14 @@ public fun ToggleableChip( selected = checked, style = style, modifier = - modifier.toggleable( - onValueChange = onClick, - enabled = enabled, - role = Role.Checkbox, - interactionSource = interactionSource, - indication = null, - value = checked, - ), + modifier.toggleable( + onValueChange = onClick, + enabled = enabled, + role = Role.Checkbox, + interactionSource = interactionSource, + indication = null, + value = checked, + ), content = content, ) } @@ -112,14 +112,14 @@ public fun RadioButtonChip( selected, style, modifier = - modifier.selectable( - onClick = onClick, - enabled = enabled, - role = Role.RadioButton, - interactionSource = interactionSource, - indication = null, - selected = selected, - ), + modifier.selectable( + onClick = onClick, + enabled = enabled, + role = Role.RadioButton, + interactionSource = interactionSource, + indication = null, + selected = selected, + ), content, ) } @@ -133,9 +133,8 @@ private fun ChipImpl( modifier: Modifier, content: @Composable () -> Unit, ) { - var chipState by remember(interactionSource) { - mutableStateOf(ChipState.of(enabled = enabled, selected = selected)) - } + var chipState by + remember(interactionSource) { mutableStateOf(ChipState.of(enabled = enabled, selected = selected)) } remember(enabled, selected) { chipState = chipState.copy(enabled = enabled, selected = selected) } @@ -143,7 +142,8 @@ private fun ChipImpl( interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> chipState = chipState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> chipState = chipState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> chipState = chipState.copy(pressed = false) is HoverInteraction.Enter -> chipState = chipState.copy(hovered = true) is HoverInteraction.Exit -> chipState = chipState.copy(hovered = false) is FocusInteraction.Focus -> chipState = chipState.copy(focused = true) @@ -165,28 +165,23 @@ private fun ChipImpl( Row( modifier = - modifier - .background(colors.backgroundFor(chipState).value, shape) - .thenIf(!chipState.isFocused) { border(Stroke.Alignment.Center, borderWidth, borderColor, shape) } - .focusOutline(chipState, shape) - .padding(style.metrics.padding), + modifier + .background(colors.backgroundFor(chipState).value, shape) + .thenIf(!chipState.isFocused) { border(Stroke.Alignment.Center, borderWidth, borderColor, shape) } + .focusOutline(chipState, shape) + .padding(style.metrics.padding), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { - val resolvedContentColor = - colors.contentFor(state = chipState).value - .takeOrElse { LocalContentColor.current } + val resolvedContentColor = colors.contentFor(state = chipState).value.takeOrElse { LocalContentColor.current } - CompositionLocalProvider(LocalContentColor provides resolvedContentColor) { - content() - } + CompositionLocalProvider(LocalContentColor provides resolvedContentColor) { content() } } } @Immutable @JvmInline -public value class ChipState(public val state: ULong) : - FocusableComponentState, SelectableComponentState { +public value class ChipState(public val state: ULong) : FocusableComponentState, SelectableComponentState { override val isActive: Boolean get() = state and Active != 0UL @@ -241,7 +236,7 @@ public value class ChipState(public val state: ULong) : (if (selected) Selected else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/CircularProgressIndicator.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/CircularProgressIndicator.kt index 991c1c973..473168bbf 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/CircularProgressIndicator.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/CircularProgressIndicator.kt @@ -38,9 +38,7 @@ public fun CircularProgressIndicator( iconSize = DpSize(16.dp, 16.dp), style = style, dispatcher = loadingDispatcher, - frameRetriever = { color -> - SpinnerProgressIconGenerator.Small.generateSvgFrames(color.toRgbaHexString()) - }, + frameRetriever = { color -> SpinnerProgressIconGenerator.Small.generateSvgFrames(color.toRgbaHexString()) }, ) } @@ -55,9 +53,7 @@ public fun CircularProgressIndicatorBig( iconSize = DpSize(32.dp, 32.dp), style = style, dispatcher = loadingDispatcher, - frameRetriever = { color -> - SpinnerProgressIconGenerator.Big.generateSvgFrames(color.toRgbaHexString()) - }, + frameRetriever = { color -> SpinnerProgressIconGenerator.Big.generateSvgFrames(color.toRgbaHexString()) }, ) } @@ -72,14 +68,15 @@ private fun CircularProgressIndicatorImpl( val defaultColor = if (JewelTheme.isDark) Color(0xFF6F737A) else Color(0xFFA8ADBD) val density = LocalDensity.current - val frames by produceState(emptyList(), density, style.color, defaultColor, dispatcher) { - value = - withContext(dispatcher) { - frameRetriever(style.color.takeOrElse { defaultColor }).map { - loadSvgPainter(it.byteInputStream(), density) + val frames by + produceState(emptyList(), density, style.color, defaultColor, dispatcher) { + value = + withContext(dispatcher) { + frameRetriever(style.color.takeOrElse { defaultColor }).map { + loadSvgPainter(it.byteInputStream(), density) + } } - } - } + } if (frames.isEmpty()) { Box(modifier.size(iconSize)) @@ -92,13 +89,13 @@ private fun CircularProgressIndicatorImpl( targetValue = framesCount, typeConverter = Int.VectorConverter, animationSpec = - InfiniteRepeatableSpec( - tween( - easing = LinearEasing, - durationMillis = (style.frameTime.inWholeMilliseconds * framesCount).toInt(), + InfiniteRepeatableSpec( + tween( + easing = LinearEasing, + durationMillis = (style.frameTime.inWholeMilliseconds * framesCount).toInt(), + ), + repeatMode = RepeatMode.Restart, ), - repeatMode = RepeatMode.Restart, - ), ) val currentPainter = frames[currentIndex] @@ -114,61 +111,65 @@ private object SpinnerProgressIconGenerator { private fun StringBuilder.openRoot(sizePx: Int) = append( "", + "xmlns=\"http://www.w3.org/2000/svg\">" ) - private fun generateSvgIcon( - size: Int, - opacityListShifted: List, - colorHex: String, - ) = buildString { + private fun generateSvgIcon(size: Int, opacityListShifted: List, colorHex: String) = buildString { openRoot(size) - elements( - colorHex = colorHex, - opacityList = opacityListShifted, - ) + elements(colorHex = colorHex, opacityList = opacityListShifted) closeRoot() } - private fun StringBuilder.elements( - colorHex: String, - opacityList: List, - ) { + private fun StringBuilder.elements(colorHex: String, opacityList: List) { appendLine() - appendLine(""" """) - appendLine(""" """ + ) + appendLine( + """ """) - appendLine(""" """) - appendLine(""" """ + ) + appendLine( + """ """) - appendLine(""" """) - appendLine(""" """ + ) + appendLine( + """ """) - appendLine(""" """) - appendLine(""" """ + ) + appendLine( + """ """) } object Small { - fun generateSvgFrames(colorHex: String): List = - buildList { - val opacityListShifted = opacityList.toMutableList() - repeat(opacityList.count()) { - add(generateSvgIcon(size = 16, colorHex = colorHex, opacityListShifted = opacityListShifted)) - opacityListShifted.shtr() - } + fun generateSvgFrames(colorHex: String): List = buildList { + val opacityListShifted = opacityList.toMutableList() + repeat(opacityList.count()) { + add(generateSvgIcon(size = 16, colorHex = colorHex, opacityListShifted = opacityListShifted)) + opacityListShifted.shtr() } + } } object Big { - fun generateSvgFrames(colorHex: String): List = - buildList { - val opacityListShifted = opacityList.toMutableList() - repeat(opacityList.count()) { - add(generateSvgIcon(size = 32, colorHex = colorHex, opacityListShifted = opacityListShifted)) - opacityListShifted.shtr() - } + fun generateSvgFrames(colorHex: String): List = buildList { + val opacityListShifted = opacityList.toMutableList() + repeat(opacityList.count()) { + add(generateSvgIcon(size = 32, colorHex = colorHex, opacityListShifted = opacityListShifted)) + opacityListShifted.shtr() } + } } private fun MutableList.shtr() { diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ContextMenu.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ContextMenu.kt index 8c6f5c37d..2182b165d 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ContextMenu.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ContextMenu.kt @@ -24,10 +24,7 @@ import org.jetbrains.jewel.ui.theme.menuStyle public object ContextMenuRepresentation : ContextMenuRepresentation { @Composable - override fun Representation( - state: ContextMenuState, - items: () -> List, - ) { + override fun Representation(state: ContextMenuState, items: () -> List) { val isOpen = state.status is ContextMenuState.Status.Open if (isOpen) { @@ -54,12 +51,7 @@ internal fun ContextMenu( ) { var focusManager: FocusManager? by mutableStateOf(null) var inputModeManager: InputModeManager? by mutableStateOf(null) - val menuManager = - remember(onDismissRequest) { - MenuManager( - onDismissRequest = onDismissRequest, - ) - } + val menuManager = remember(onDismissRequest) { MenuManager(onDismissRequest = onDismissRequest) } Popup( popupPositionProvider = rememberCursorPositionProvider(style.metrics.offset), @@ -68,21 +60,15 @@ internal fun ContextMenu( onPreviewKeyEvent = { false }, onKeyEvent = { val currentFocusManager = checkNotNull(focusManager) { "FocusManager must not be null" } - val currentInputModeManager = - checkNotNull(inputModeManager) { "InputModeManager must not be null" } + val currentInputModeManager = checkNotNull(inputModeManager) { "InputModeManager must not be null" } handlePopupMenuOnKeyEvent(it, currentFocusManager, currentInputModeManager, menuManager) }, ) { focusManager = LocalFocusManager.current inputModeManager = LocalInputModeManager.current - CompositionLocalProvider( - LocalMenuManager provides menuManager, - ) { - MenuContent( - modifier = modifier, - content = content, - ) + CompositionLocalProvider(LocalMenuManager provides menuManager) { + MenuContent(modifier = modifier, content = content) } } } @@ -97,12 +83,7 @@ private fun MenuScope.contextItems(items: () -> List) { submenu(submenu = { contextItems(item.submenu) }) { Text(item.label) } } else -> { - selectableItem( - selected = false, - onClick = item.onClick, - ) { - Text(item.label) - } + selectableItem(selected = false, onClick = item.onClick) { Text(item.label) } } } } @@ -110,7 +91,5 @@ private fun MenuScope.contextItems(items: () -> List) { public object ContextMenuDivider : ContextMenuItem("---", {}) -public class ContextSubmenu( - label: String, - public val submenu: () -> List, -) : ContextMenuItem(label, {}) +public class ContextSubmenu(label: String, public val submenu: () -> List) : + ContextMenuItem(label, {}) diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Divider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Divider.kt index 1bde7c9b8..9ae8e167b 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Divider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Divider.kt @@ -42,9 +42,5 @@ public fun Divider( } val lineColor = color.takeOrElse { style.color } - Box( - modifier.then(indentModifier) - .then(orientationModifier) - .background(color = lineColor), - ) + Box(modifier.then(indentModifier).then(orientationModifier).background(color = lineColor)) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Dropdown.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Dropdown.kt index 1aee93ea1..97752a185 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Dropdown.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Dropdown.kt @@ -63,9 +63,7 @@ public fun Dropdown( var expanded by remember { mutableStateOf(false) } var skipNextClick by remember { mutableStateOf(false) } - var dropdownState by remember(interactionSource) { - mutableStateOf(DropdownState.of(enabled = enabled)) - } + var dropdownState by remember(interactionSource) { mutableStateOf(DropdownState.of(enabled = enabled)) } remember(enabled) { dropdownState = dropdownState.copy(enabled = enabled) } @@ -74,8 +72,7 @@ public fun Dropdown( when (interaction) { is PressInteraction.Press -> dropdownState = dropdownState.copy(pressed = true) is PressInteraction.Cancel, - is PressInteraction.Release, - -> dropdownState = dropdownState.copy(pressed = false) + is PressInteraction.Release -> dropdownState = dropdownState.copy(pressed = false) is HoverInteraction.Enter -> dropdownState = dropdownState.copy(hovered = true) is HoverInteraction.Exit -> dropdownState = dropdownState.copy(hovered = false) is FocusInteraction.Focus -> dropdownState = dropdownState.copy(focused = true) @@ -95,37 +92,33 @@ public fun Dropdown( var componentWidth by remember { mutableIntStateOf(-1) } Box( modifier = - modifier - .clickable( - onClick = { - // TODO: Trick to skip click event when close menu by click dropdown - if (!skipNextClick) { - expanded = !expanded - } - skipNextClick = false - }, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ) - .background(colors.backgroundFor(dropdownState).value, shape) - .thenIf(hasNoOutline) { - border(Stroke.Alignment.Center, style.metrics.borderWidth, borderColor, shape) - } - .thenIf(outline == Outline.None) { focusOutline(dropdownState, shape) } - .outline(dropdownState, outline, shape) - .width(IntrinsicSize.Max) - .defaultMinSize(minSize.width, minSize.height.coerceAtLeast(arrowMinSize.height)) - .onSizeChanged { componentWidth = it.width }, + modifier + .clickable( + onClick = { + // TODO: Trick to skip click event when close menu by click dropdown + if (!skipNextClick) { + expanded = !expanded + } + skipNextClick = false + }, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ) + .background(colors.backgroundFor(dropdownState).value, shape) + .thenIf(hasNoOutline) { border(Stroke.Alignment.Center, style.metrics.borderWidth, borderColor, shape) } + .thenIf(outline == Outline.None) { focusOutline(dropdownState, shape) } + .outline(dropdownState, outline, shape) + .width(IntrinsicSize.Max) + .defaultMinSize(minSize.width, minSize.height.coerceAtLeast(arrowMinSize.height)) + .onSizeChanged { componentWidth = it.width }, contentAlignment = Alignment.CenterStart, ) { CompositionLocalProvider(LocalContentColor provides colors.contentFor(dropdownState).value) { Box( modifier = - Modifier.fillMaxWidth() - .padding(style.metrics.contentPadding) - .padding(end = arrowMinSize.width), + Modifier.fillMaxWidth().padding(style.metrics.contentPadding).padding(end = arrowMinSize.width), contentAlignment = Alignment.CenterStart, content = content, ) @@ -138,7 +131,7 @@ public fun Dropdown( key = style.icons.chevronDown, contentDescription = null, tint = colors.iconTintFor(dropdownState).value, - hint = Stateful(dropdownState) + hint = Stateful(dropdownState), ) } } @@ -154,8 +147,9 @@ public fun Dropdown( true }, modifier = - menuModifier.focusProperties { canFocus = true } - .defaultMinSize(minWidth = with(density) { componentWidth.toDp() }), + menuModifier + .focusProperties { canFocus = true } + .defaultMinSize(minWidth = with(density) { componentWidth.toDp() }), style = style.menuStyle, horizontalAlignment = Alignment.Start, content = menuContent, @@ -188,14 +182,7 @@ public value class DropdownState(public val state: ULong) : FocusableComponentSt pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): DropdownState = - of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): DropdownState = of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, " + @@ -214,7 +201,7 @@ public value class DropdownState(public val state: ULong) : FocusableComponentSt (if (focused) Focused else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Icon.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Icon.kt index 89c6d7b66..24e2db8cc 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Icon.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Icon.kt @@ -31,6 +31,7 @@ import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp +import java.io.InputStream import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.ui.icon.IconKey import org.jetbrains.jewel.ui.icon.newUiChecker @@ -38,7 +39,6 @@ import org.jetbrains.jewel.ui.painter.PainterHint import org.jetbrains.jewel.ui.painter.rememberResourcePainterProvider import org.jetbrains.jewel.ui.util.thenIf import org.xml.sax.InputSource -import java.io.InputStream @Deprecated( "Use the IconKey-based API instead", @@ -60,12 +60,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(resource, iconClass) val painter by painterProvider.getPainter(*hints) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - colorFilter = colorFilter, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, colorFilter = colorFilter) } @Deprecated( @@ -88,12 +83,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(resource, iconClass) val painter by painterProvider.getPainter(hint) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - colorFilter = colorFilter, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, colorFilter = colorFilter) } @Deprecated( @@ -116,12 +106,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(resource, iconClass) val painter by painterProvider.getPainter(*hints) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - tint = tint, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, tint = tint) } @Deprecated( @@ -144,12 +129,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(resource, iconClass) val painter by painterProvider.getPainter(hint) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - tint = tint, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, tint = tint) } @Composable @@ -166,12 +146,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(path, iconClass) val painter by painterProvider.getPainter(*hints) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - tint = tint, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, tint = tint) } @Composable @@ -189,12 +164,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(path, iconClass) val painter by painterProvider.getPainter(hint) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - tint = tint, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, tint = tint) } @Composable @@ -211,12 +181,7 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(path, iconClass) val painter by painterProvider.getPainter(hint) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - colorFilter = colorFilter, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, colorFilter = colorFilter) } @Composable @@ -233,26 +198,18 @@ public fun Icon( val painterProvider = rememberResourcePainterProvider(path, iconClass) val painter by painterProvider.getPainter(*hints) - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - colorFilter = colorFilter, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, colorFilter = colorFilter) } /** - * Icon component that draws [imageVector] using [tint], defaulting to - * [Color.Unspecified]. + * Icon component that draws [imageVector] using [tint], defaulting to [Color.Unspecified]. * * @param imageVector [ImageVector] to draw inside this Icon - * @param contentDescription text used by accessibility services to - * describe what this icon represents. This should always be provided - * unless this icon is used for decorative purposes, and does not - * represent a meaningful action that a user can take. + * @param contentDescription text used by accessibility services to describe what this icon represents. This should + * always be provided unless this icon is used for decorative purposes, and does not represent a meaningful action + * that a user can take. * @param modifier optional [Modifier] for this Icon - * @param tint tint to be applied to [imageVector]. If [Color.Unspecified] - * is provided, then no tint is applied + * @param tint tint to be applied to [imageVector]. If [Color.Unspecified] is provided, then no tint is applied */ @Composable public fun Icon( @@ -270,17 +227,14 @@ public fun Icon( } /** - * Icon component that draws [bitmap] using [tint], defaulting to - * [Color.Unspecified]. + * Icon component that draws [bitmap] using [tint], defaulting to [Color.Unspecified]. * * @param bitmap [ImageBitmap] to draw inside this Icon - * @param contentDescription text used by accessibility services to - * describe what this icon represents. This should always be provided - * unless this icon is used for decorative purposes, and does not - * represent a meaningful action that a user can take. + * @param contentDescription text used by accessibility services to describe what this icon represents. This should + * always be provided unless this icon is used for decorative purposes, and does not represent a meaningful action + * that a user can take. * @param modifier optional [Modifier] for this Icon - * @param tint tint to be applied to [bitmap]. If [Color.Unspecified] is - * provided, then no tint is applied + * @param tint tint to be applied to [bitmap]. If [Color.Unspecified] is provided, then no tint is applied */ @Composable public fun Icon( @@ -290,26 +244,18 @@ public fun Icon( tint: Color = Color.Unspecified, ) { val painter = remember(bitmap) { BitmapPainter(bitmap) } - Icon( - painter = painter, - contentDescription = contentDescription, - modifier = modifier, - tint = tint, - ) + Icon(painter = painter, contentDescription = contentDescription, modifier = modifier, tint = tint) } /** - * Icon component that draws a [painter] using [tint], defaulting to - * [Color.Unspecified] + * Icon component that draws a [painter] using [tint], defaulting to [Color.Unspecified] * * @param painter [Painter] to draw inside this Icon - * @param contentDescription text used by accessibility services to - * describe what this icon represents. This should always be provided - * unless this icon is used for decorative purposes, and does not - * represent a meaningful action that a user can take. + * @param contentDescription text used by accessibility services to describe what this icon represents. This should + * always be provided unless this icon is used for decorative purposes, and does not represent a meaningful action + * that a user can take. * @param modifier optional [Modifier] for this Icon - * @param tint tint to be applied to [painter]. If [Color.Unspecified] is - * provided, then no tint is applied + * @param tint tint to be applied to [painter]. If [Color.Unspecified] is provided, then no tint is applied */ @Composable public fun Icon( @@ -326,10 +272,9 @@ public fun Icon( * Icon component that draws a [painter] using a [colorFilter] * * @param painter [Painter] to draw inside this Icon - * @param contentDescription text used by accessibility services to - * describe what this icon represents. This should always be provided - * unless this icon is used for decorative purposes, and does not - * represent a meaningful action that a user can take. + * @param contentDescription text used by accessibility services to describe what this icon represents. This should + * always be provided unless this icon is used for decorative purposes, and does not represent a meaningful action + * that a user can take. * @param colorFilter color filter to be applied to [painter] * @param modifier optional [Modifier] for this Icon */ @@ -354,19 +299,13 @@ public fun Icon( modifier .toolingGraphicsLayer() .defaultSizeFor(painter) - .paint( - painter, - colorFilter = colorFilter, - contentScale = ContentScale.Fit, - ).then(semantics), + .paint(painter, colorFilter = colorFilter, contentScale = ContentScale.Fit) + .then(semantics) ) } @Composable -public fun painterResource( - resourcePath: String, - loader: ResourceLoader, -): Painter = +public fun painterResource(resourcePath: String, loader: ResourceLoader): Painter = when (resourcePath.substringAfterLast(".").lowercase()) { "svg" -> rememberSvgResource(resourcePath, loader) "xml" -> rememberVectorXmlResource(resourcePath, loader) @@ -374,21 +313,13 @@ public fun painterResource( } @Composable -private fun rememberSvgResource( - resourcePath: String, - loader: ResourceLoader = ResourceLoader.Default, -): Painter { +private fun rememberSvgResource(resourcePath: String, loader: ResourceLoader = ResourceLoader.Default): Painter { val density = LocalDensity.current - return remember(resourcePath, density, loader) { - useResource(resourcePath, loader) { loadSvgPainter(it, density) } - } + return remember(resourcePath, density, loader) { useResource(resourcePath, loader) { loadSvgPainter(it, density) } } } @Composable -private fun rememberVectorXmlResource( - resourcePath: String, - loader: ResourceLoader = ResourceLoader.Default, -): Painter { +private fun rememberVectorXmlResource(resourcePath: String, loader: ResourceLoader = ResourceLoader.Default): Painter { val density = LocalDensity.current val image = remember(resourcePath, density, loader) { @@ -398,24 +329,16 @@ private fun rememberVectorXmlResource( } @Composable -private fun rememberBitmapResource( - resourcePath: String, - loader: ResourceLoader = ResourceLoader.Default, -): Painter { +private fun rememberBitmapResource(resourcePath: String, loader: ResourceLoader = ResourceLoader.Default): Painter { val image = remember(resourcePath) { useResource(resourcePath, loader, ::loadImageBitmap) } return BitmapPainter(image) } -private inline fun useResource( - resourcePath: String, - loader: ResourceLoader, - block: (InputStream) -> T, -): T = loader.load(resourcePath).use(block) +private inline fun useResource(resourcePath: String, loader: ResourceLoader, block: (InputStream) -> T): T = + loader.load(resourcePath).use(block) private fun Modifier.defaultSizeFor(painter: Painter) = - thenIf(painter.intrinsicSize == Size.Unspecified || painter.intrinsicSize.isInfinite()) { - DefaultIconSizeModifier - } + thenIf(painter.intrinsicSize == Size.Unspecified || painter.intrinsicSize.isInfinite()) { DefaultIconSizeModifier } private fun Size.isInfinite() = width.isInfinite() && height.isInfinite() diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconActionButton.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconActionButton.kt index e6f4cf52d..3ba4b27e4 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconActionButton.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconActionButton.kt @@ -77,12 +77,7 @@ public fun IconActionButton( iconClass: Class<*> = key::class.java, tooltip: @Composable () -> Unit, ) { - Tooltip( - tooltip, - style = tooltipStyle, - modifier = tooltipModifier, - tooltipPlacement = tooltipPlacement, - ) { + Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) { CoreIconActionButton( key = key, modifier = modifier, @@ -163,12 +158,7 @@ public fun SelectableIconActionButton( iconClass: Class<*> = key::class.java, tooltip: @Composable () -> Unit, ) { - Tooltip( - tooltip, - style = tooltipStyle, - modifier = tooltipModifier, - tooltipPlacement = tooltipPlacement, - ) { + Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) { CoreSelectableIconActionButton( key = key, modifier = modifier, @@ -252,12 +242,7 @@ public fun ToggleableIconActionButton( iconClass: Class<*> = key::class.java, tooltip: @Composable () -> Unit, ) { - Tooltip( - tooltip, - style = tooltipStyle, - modifier = tooltipModifier, - tooltipPlacement = tooltipPlacement, - ) { + Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) { CoreToggleableIconActionButton( key = key, modifier = modifier, @@ -305,16 +290,7 @@ public fun IconActionButton( style: IconButtonStyle = JewelTheme.iconButtonStyle, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { - CoreIconActionButton( - painter, - contentDescription, - enabled, - focusable, - style, - interactionSource, - modifier, - onClick, - ) + CoreIconActionButton(painter, contentDescription, enabled, focusable, style, interactionSource, modifier, onClick) } @Composable @@ -332,12 +308,7 @@ public fun IconActionButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, tooltip: @Composable () -> Unit, ) { - Tooltip( - tooltip, - style = tooltipStyle, - modifier = tooltipModifier, - tooltipPlacement = tooltipPlacement, - ) { + Tooltip(tooltip, style = tooltipStyle, modifier = tooltipModifier, tooltipPlacement = tooltipPlacement) { CoreIconActionButton( painter = painter, modifier = modifier, @@ -362,7 +333,5 @@ private fun CoreIconActionButton( modifier: Modifier = Modifier, onClick: () -> Unit, ) { - IconButton(onClick, modifier, enabled, focusable, style, interactionSource) { - Icon(painter, contentDescription) - } + IconButton(onClick, modifier, enabled, focusable, style, interactionSource) { Icon(painter, contentDescription) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconButton.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconButton.kt index 66840fd3d..9055f7381 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconButton.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/IconButton.kt @@ -53,9 +53,7 @@ public fun IconButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable (BoxScope.(IconButtonState) -> Unit), ) { - var buttonState by remember(interactionSource) { - mutableStateOf(IconButtonState.of(enabled = enabled)) - } + var buttonState by remember(interactionSource) { mutableStateOf(IconButtonState.of(enabled = enabled)) } remember(enabled) { buttonState = buttonState.copy(enabled = enabled) } @@ -64,8 +62,7 @@ public fun IconButton( when (interaction) { is PressInteraction.Press -> buttonState = buttonState.copy(pressed = true) is PressInteraction.Cancel, - is PressInteraction.Release, - -> buttonState = buttonState.copy(pressed = false) + is PressInteraction.Release -> buttonState = buttonState.copy(pressed = false) is HoverInteraction.Enter -> buttonState = buttonState.copy(hovered = true) is HoverInteraction.Exit -> buttonState = buttonState.copy(hovered = false) @@ -81,20 +78,19 @@ public fun IconButton( Box( modifier = - Modifier - .thenIf(!focusable) { focusProperties { canFocus = false } } - .then(modifier) - .clickable( - onClick = onClick, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ) - .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) - .padding(style.metrics.padding) - .background(background, shape) - .border(style.metrics.borderWidth, border, shape), + Modifier.thenIf(!focusable) { focusProperties { canFocus = false } } + .then(modifier) + .clickable( + onClick = onClick, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ) + .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) + .padding(style.metrics.padding) + .background(background, shape) + .border(style.metrics.borderWidth, border, shape), contentAlignment = Alignment.Center, content = { content(buttonState) }, ) @@ -111,21 +107,16 @@ public fun SelectableIconButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable (BoxScope.(SelectableIconButtonState) -> Unit), ) { - var buttonState by remember(interactionSource) { - mutableStateOf(SelectableIconButtonState.of(enabled = enabled)) - } + var buttonState by remember(interactionSource) { mutableStateOf(SelectableIconButtonState.of(enabled = enabled)) } - remember(enabled, selected) { - buttonState = buttonState.copy(enabled = enabled, selected = selected) - } + remember(enabled, selected) { buttonState = buttonState.copy(enabled = enabled, selected = selected) } LaunchedEffect(key1 = interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> buttonState = buttonState.copy(pressed = true) is PressInteraction.Cancel, - is PressInteraction.Release, - -> buttonState = buttonState.copy(pressed = false) + is PressInteraction.Release -> buttonState = buttonState.copy(pressed = false) is HoverInteraction.Enter -> buttonState = buttonState.copy(hovered = true) is HoverInteraction.Exit -> buttonState = buttonState.copy(hovered = false) @@ -141,24 +132,21 @@ public fun SelectableIconButton( Box( modifier = - Modifier - .thenIf(!focusable) { focusProperties { canFocus = false } } - .then(modifier) - .selectable( - onClick = onClick, - enabled = enabled, - role = Role.RadioButton, - interactionSource = interactionSource, - indication = null, - selected = selected, - ) - .onActivated(enabled = enabled) { - buttonState = buttonState.copy(active = it) - } - .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) - .padding(style.metrics.padding) - .background(background, shape) - .border(style.metrics.borderWidth, border, shape), + Modifier.thenIf(!focusable) { focusProperties { canFocus = false } } + .then(modifier) + .selectable( + onClick = onClick, + enabled = enabled, + role = Role.RadioButton, + interactionSource = interactionSource, + indication = null, + selected = selected, + ) + .onActivated(enabled = enabled) { buttonState = buttonState.copy(active = it) } + .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) + .padding(style.metrics.padding) + .background(background, shape) + .border(style.metrics.borderWidth, border, shape), contentAlignment = Alignment.Center, content = { content(buttonState) }, ) @@ -175,9 +163,7 @@ public fun ToggleableIconButton( interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable (BoxScope.(ToggleableIconButtonState) -> Unit), ) { - var buttonState by remember(interactionSource) { - mutableStateOf(ToggleableIconButtonState.of(enabled = enabled)) - } + var buttonState by remember(interactionSource) { mutableStateOf(ToggleableIconButtonState.of(enabled = enabled)) } remember(enabled, value) { buttonState = buttonState.copy(enabled = enabled, toggleableState = ToggleableState(value)) @@ -188,8 +174,7 @@ public fun ToggleableIconButton( when (interaction) { is PressInteraction.Press -> buttonState = buttonState.copy(pressed = true) is PressInteraction.Cancel, - is PressInteraction.Release, - -> buttonState = buttonState.copy(pressed = false) + is PressInteraction.Release -> buttonState = buttonState.copy(pressed = false) is HoverInteraction.Enter -> buttonState = buttonState.copy(hovered = true) is HoverInteraction.Exit -> buttonState = buttonState.copy(hovered = false) @@ -205,24 +190,21 @@ public fun ToggleableIconButton( Box( modifier = - Modifier - .thenIf(!focusable) { focusProperties { canFocus = false } } - .then(modifier) - .toggleable( - onValueChange = onValueChange, - enabled = enabled, - role = Role.Checkbox, - interactionSource = interactionSource, - indication = null, - value = buttonState.toggleableState == ToggleableState.On, - ) - .onActivated(enabled = enabled) { - buttonState = buttonState.copy(active = it) - } - .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) - .padding(style.metrics.padding) - .background(background, shape) - .border(style.metrics.borderWidth, border, shape), + Modifier.thenIf(!focusable) { focusProperties { canFocus = false } } + .then(modifier) + .toggleable( + onValueChange = onValueChange, + enabled = enabled, + role = Role.Checkbox, + interactionSource = interactionSource, + indication = null, + value = buttonState.toggleableState == ToggleableState.On, + ) + .onActivated(enabled = enabled) { buttonState = buttonState.copy(active = it) } + .defaultMinSize(style.metrics.minSize.width, style.metrics.minSize.height) + .padding(style.metrics.padding) + .background(background, shape) + .border(style.metrics.borderWidth, border, shape), contentAlignment = Alignment.Center, content = { content(buttonState) }, ) @@ -252,14 +234,7 @@ public value class IconButtonState(public val state: ULong) : FocusableComponent pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): IconButtonState = - of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): IconButtonState = of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, isHovered=$isHovered, " + @@ -278,14 +253,15 @@ public value class IconButtonState(public val state: ULong) : FocusableComponent (if (focused) Focused else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } @Immutable @JvmInline -public value class ToggleableIconButtonState(public val state: ULong) : FocusableComponentState, ToggleableComponentState { +public value class ToggleableIconButtonState(public val state: ULong) : + FocusableComponentState, ToggleableComponentState { override val toggleableState: ToggleableState get() = state.readToggleableState() @@ -341,14 +317,15 @@ public value class ToggleableIconButtonState(public val state: ULong) : Focusabl (if (pressed) Pressed else 0UL) or (if (active) Active else 0UL) or (if (toggleableState != ToggleableState.Off) Selected else 0UL) or - (if (toggleableState == ToggleableState.Indeterminate) Indeterminate else 0UL), + (if (toggleableState == ToggleableState.Indeterminate) Indeterminate else 0UL) ) } } @Immutable @JvmInline -public value class SelectableIconButtonState(public val state: ULong) : FocusableComponentState, SelectableComponentState { +public value class SelectableIconButtonState(public val state: ULong) : + FocusableComponentState, SelectableComponentState { override val isSelected: Boolean get() = state and Selected != 0UL @@ -404,7 +381,7 @@ public value class SelectableIconButtonState(public val state: ULong) : Focusabl (if (focused) Focused else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/InputField.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/InputField.kt index 5b74c97f8..a9e77425a 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/InputField.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/InputField.kt @@ -105,11 +105,7 @@ internal fun InputField( modifier .then(backgroundModifier) .thenIf(!undecorated && hasNoOutline) { - focusOutline( - state = inputFieldState, - outlineShape = shape, - alignment = Stroke.Alignment.Center, - ) + focusOutline(state = inputFieldState, outlineShape = shape, alignment = Stroke.Alignment.Center) } .then(borderModifier) .outline(inputFieldState, outline, shape, Stroke.Alignment.Center), diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LazyTree.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LazyTree.kt index 74bc2dd2f..8cd7e7d1f 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LazyTree.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LazyTree.kt @@ -60,10 +60,9 @@ public fun LazyTree( val resolvedContentColor = style.colors .contentFor(TreeElementState.of(focused = isActive, selected = isSelected, expanded = false)) - .value.takeOrElse { LocalContentColor.current } + .value + .takeOrElse { LocalContentColor.current } - CompositionLocalProvider(LocalContentColor provides resolvedContentColor) { - nodeContent(it) - } + CompositionLocalProvider(LocalContentColor provides resolvedContentColor) { nodeContent(it) } } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LinearProgressBar.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LinearProgressBar.kt index c48f160e7..c50fe00c6 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LinearProgressBar.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/LinearProgressBar.kt @@ -39,21 +39,20 @@ public fun HorizontalProgressBar( val shape = RoundedCornerShape(style.metrics.cornerSize) Box( - modifier.defaultMinSize(minHeight = style.metrics.minHeight).clip(shape) - .drawWithContent { - drawRect(color = colors.track) // Draw the background - val progressWidth = size.width * progress - val progressX = if (layoutDirection == LayoutDirection.Ltr) 0f else size.width - progressWidth + modifier.defaultMinSize(minHeight = style.metrics.minHeight).clip(shape).drawWithContent { + drawRect(color = colors.track) // Draw the background + val progressWidth = size.width * progress + val progressX = if (layoutDirection == LayoutDirection.Ltr) 0f else size.width - progressWidth - val cornerSizePx = style.metrics.cornerSize.toPx(size, Density(density, fontScale)) - val cornerRadius = CornerRadius(cornerSizePx, cornerSizePx) - drawRoundRect( - color = colors.progress, - topLeft = Offset(progressX, 0f), - size = size.copy(width = progressWidth), - cornerRadius = cornerRadius, - ) - }, + val cornerSizePx = style.metrics.cornerSize.toPx(size, Density(density, fontScale)) + val cornerRadius = CornerRadius(cornerSizePx, cornerSizePx) + drawRoundRect( + color = colors.progress, + topLeft = Offset(progressX, 0f), + size = size.copy(width = progressWidth), + cornerRadius = cornerRadius, + ) + } ) } @@ -64,24 +63,21 @@ public fun IndeterminateHorizontalProgressBar( ) { val infiniteTransition = rememberInfiniteTransition() - val cycleDurationMillis by remember { - mutableStateOf(style.indeterminateCycleDuration.inWholeMilliseconds.toInt()) - } - val animatedProgress by infiniteTransition.animateFloat( - initialValue = 0f, - targetValue = 2f, - animationSpec = - infiniteRepeatable( - tween(durationMillis = cycleDurationMillis, easing = LinearEasing), - repeatMode = RepeatMode.Restart, - ), - ) + val cycleDurationMillis by remember { mutableStateOf(style.indeterminateCycleDuration.inWholeMilliseconds.toInt()) } + val animatedProgress by + infiniteTransition.animateFloat( + initialValue = 0f, + targetValue = 2f, + animationSpec = + infiniteRepeatable( + tween(durationMillis = cycleDurationMillis, easing = LinearEasing), + repeatMode = RepeatMode.Restart, + ), + ) val highlightWidth = style.metrics.indeterminateHighlightWidth val colors = style.colors - val colorsList by remember { - mutableStateOf(listOf(colors.indeterminateBase, colors.indeterminateHighlight)) - } + val colorsList by remember { mutableStateOf(listOf(colors.indeterminateBase, colors.indeterminateHighlight)) } val shape = RoundedCornerShape(style.metrics.cornerSize) Box( @@ -96,8 +92,8 @@ public fun IndeterminateHorizontalProgressBar( start = Offset(x, 0f), end = Offset(x + highlightWidth.value, 0f), TileMode.Mirror, - ), + ) ) - }, + } ) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Link.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Link.kt index e9b5ac213..f5f979c30 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Link.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Link.kt @@ -29,6 +29,7 @@ import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow +import java.awt.Cursor import org.jetbrains.jewel.foundation.modifier.onHover import org.jetbrains.jewel.foundation.state.CommonStateBitMask import org.jetbrains.jewel.foundation.state.CommonStateBitMask.Active @@ -50,7 +51,6 @@ import org.jetbrains.jewel.ui.focusOutline import org.jetbrains.jewel.ui.icon.IconKey import org.jetbrains.jewel.ui.painter.hints.Stateful import org.jetbrains.jewel.ui.util.thenIf -import java.awt.Cursor @Composable public fun Link( @@ -174,8 +174,7 @@ private fun LinkImpl( when (interaction) { is PressInteraction.Press -> linkState = linkState.copy(pressed = true) is PressInteraction.Cancel, - is PressInteraction.Release, - -> linkState = linkState.copy(pressed = false) + is PressInteraction.Release -> linkState = linkState.copy(pressed = false) is HoverInteraction.Enter -> linkState = linkState.copy(hovered = true) is HoverInteraction.Exit -> linkState = linkState.copy(hovered = false) @@ -191,44 +190,39 @@ private fun LinkImpl( } val textColor by style.colors.contentFor(linkState) - val mergedTextStyle = remember(style.underlineBehavior, textStyle, linkState, textColor) { - val decoration = - when { - style.underlineBehavior == ShowAlways -> TextDecoration.Underline - style.underlineBehavior == ShowOnHover && linkState.isHovered -> TextDecoration.Underline - else -> TextDecoration.None - } + val mergedTextStyle = + remember(style.underlineBehavior, textStyle, linkState, textColor) { + val decoration = + when { + style.underlineBehavior == ShowAlways -> TextDecoration.Underline + style.underlineBehavior == ShowOnHover && linkState.isHovered -> TextDecoration.Underline + else -> TextDecoration.None + } - textStyle.merge(textDecoration = decoration, color = textColor) - } + textStyle.merge(textDecoration = decoration, color = textColor) + } val pointerChangeModifier = Modifier.pointerHoverIcon(PointerIcon(Cursor(Cursor.HAND_CURSOR))) Row( modifier = - modifier - .thenIf(linkState.isEnabled) { pointerChangeModifier } - .clickable( - onClick = { - linkState = linkState.copy(visited = true) - onClick() - }, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ) - .focusOutline(linkState, RoundedCornerShape(style.metrics.focusHaloCornerSize)), + modifier + .thenIf(linkState.isEnabled) { pointerChangeModifier } + .clickable( + onClick = { + linkState = linkState.copy(visited = true) + onClick() + }, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ) + .focusOutline(linkState, RoundedCornerShape(style.metrics.focusHaloCornerSize)), horizontalArrangement = Arrangement.spacedBy(style.metrics.textIconGap), verticalAlignment = Alignment.CenterVertically, ) { - BasicText( - text = text, - style = mergedTextStyle, - overflow = overflow, - softWrap = true, - maxLines = 1, - ) + BasicText(text = text, style = mergedTextStyle, overflow = overflow, softWrap = true, maxLines = 1) if (icon != null) { Icon( @@ -244,9 +238,7 @@ private fun LinkImpl( @Immutable @JvmInline -public value class LinkState( - public val state: ULong, -) : FocusableComponentState { +public value class LinkState(public val state: ULong) : FocusableComponentState { override val isActive: Boolean get() = state and Active != 0UL @@ -325,7 +317,7 @@ public value class LinkState( (if (focused) Focused else 0UL) or (if (pressed) Pressed else 0UL) or (if (hovered) Hovered else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Menu.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Menu.kt index 17ebace00..4317e9040 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Menu.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Menu.kt @@ -124,14 +124,8 @@ public fun PopupMenu( inputModeManager = LocalInputModeManager.current OverrideDarkMode(style.isDark) { - CompositionLocalProvider( - LocalMenuManager provides menuManager, - LocalMenuStyle provides style, - ) { - MenuContent( - modifier = modifier, - content = content, - ) + CompositionLocalProvider(LocalMenuManager provides menuManager, LocalMenuStyle provides style) { + MenuContent(modifier = modifier, content = content) } } } @@ -157,22 +151,20 @@ internal fun MenuContent( Box( modifier = - modifier - .shadow( - elevation = style.metrics.shadowSize, - shape = menuShape, - ambientColor = colors.shadow, - spotColor = colors.shadow, - ) - .border(Stroke.Alignment.Inside, style.metrics.borderWidth, colors.border, menuShape) - .background(colors.background, menuShape) - .width(IntrinsicSize.Max) - .onHover { localMenuManager.onHoveredChange(it) }, + modifier + .shadow( + elevation = style.metrics.shadowSize, + shape = menuShape, + ambientColor = colors.shadow, + spotColor = colors.shadow, + ) + .border(Stroke.Alignment.Inside, style.metrics.borderWidth, colors.border, menuShape) + .background(colors.background, menuShape) + .width(IntrinsicSize.Max) + .onHover { localMenuManager.onHoveredChange(it) } ) { Column(Modifier.verticalScroll(scrollState).padding(style.metrics.contentPadding)) { - items.forEach { - ShowMenuItem(it, anyItemHasIcon, anyItemHasKeybinding) - } + items.forEach { ShowMenuItem(it, anyItemHasIcon, anyItemHasKeybinding) } } Box(modifier = Modifier.matchParentSize()) { @@ -185,11 +177,7 @@ internal fun MenuContent( } @Composable -private fun ShowMenuItem( - item: MenuItem, - canShowIcon: Boolean = false, - canShowKeybinding: Boolean = false, -) { +private fun ShowMenuItem(item: MenuItem, canShowIcon: Boolean = false, canShowKeybinding: Boolean = false) { when (item) { is MenuSelectableItem -> MenuItem( @@ -250,9 +238,7 @@ public fun MenuScope.items( onItemClick: (Int) -> Unit, content: @Composable (Int) -> Unit, ) { - repeat(count) { - selectableItem(isSelected(it), onClick = { onItemClick(it) }) { content(it) } - } + repeat(count) { selectableItem(isSelected(it), onClick = { onItemClick(it) }) { content(it) } } } public fun MenuScope.items( @@ -262,54 +248,51 @@ public fun MenuScope.items( content: @Composable (T) -> Unit, ) { repeat(items.count()) { - selectableItem(isSelected(items[it]), onClick = { onItemClick(items[it]) }) { - content(items[it]) - } + selectableItem(isSelected(items[it]), onClick = { onItemClick(items[it]) }) { content(items[it]) } } } -private fun (MenuScope.() -> Unit).asList() = - buildList { - this@asList( - object : MenuScope { - override fun selectableItem( - selected: Boolean, - iconKey: IconKey?, - iconClass: Class<*>?, - keybinding: Set?, - onClick: () -> Unit, - enabled: Boolean, - content: @Composable () -> Unit, - ) { - add( - MenuSelectableItem( - isSelected = selected, - isEnabled = enabled, - iconKey = iconKey, - iconClass = iconClass, - keybinding = keybinding, - onClick = onClick, - content = content, - ), +private fun (MenuScope.() -> Unit).asList() = buildList { + this@asList( + object : MenuScope { + override fun selectableItem( + selected: Boolean, + iconKey: IconKey?, + iconClass: Class<*>?, + keybinding: Set?, + onClick: () -> Unit, + enabled: Boolean, + content: @Composable () -> Unit, + ) { + add( + MenuSelectableItem( + isSelected = selected, + isEnabled = enabled, + iconKey = iconKey, + iconClass = iconClass, + keybinding = keybinding, + onClick = onClick, + content = content, ) - } + ) + } - override fun passiveItem(content: @Composable () -> Unit) { - add(MenuPassiveItem(content)) - } + override fun passiveItem(content: @Composable () -> Unit) { + add(MenuPassiveItem(content)) + } - override fun submenu( - enabled: Boolean, - iconResource: String?, - iconClass: Class<*>, - submenu: MenuScope.() -> Unit, - content: @Composable () -> Unit, - ) { - add(SubmenuItem(enabled, iconResource, iconClass, submenu, content)) - } - }, - ) - } + override fun submenu( + enabled: Boolean, + iconResource: String?, + iconClass: Class<*>, + submenu: MenuScope.() -> Unit, + content: @Composable () -> Unit, + ) { + add(SubmenuItem(enabled, iconResource, iconClass, submenu, content)) + } + } + ) +} private interface MenuItem { val content: @Composable () -> Unit @@ -325,9 +308,7 @@ private data class MenuSelectableItem( override val content: @Composable () -> Unit, ) : MenuItem -private data class MenuPassiveItem( - override val content: @Composable () -> Unit, -) : MenuItem +private data class MenuPassiveItem(override val content: @Composable () -> Unit) : MenuItem private data class SubmenuItem( val isEnabled: Boolean = true, @@ -368,9 +349,8 @@ internal fun MenuItem( style: MenuStyle = JewelTheme.menuStyle, content: @Composable () -> Unit, ) { - var itemState by remember(interactionSource) { - mutableStateOf(MenuItemState.of(selected = selected, enabled = enabled)) - } + var itemState by + remember(interactionSource) { mutableStateOf(MenuItemState.of(selected = selected, enabled = enabled)) } remember(enabled, selected) { itemState = itemState.copy(selected = selected, enabled = enabled) } @@ -380,7 +360,8 @@ internal fun MenuItem( interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> itemState = itemState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> itemState = itemState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> itemState = itemState.copy(pressed = false) is HoverInteraction.Enter -> { itemState = itemState.copy(hovered = true) @@ -399,20 +380,20 @@ internal fun MenuItem( Box( modifier = - modifier - .focusRequester(focusRequester) - .selectable( - selected = selected, - onClick = { - onClick() - menuManager.closeAll(localInputModeManager.inputMode, true) - }, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ) - .fillMaxWidth(), + modifier + .focusRequester(focusRequester) + .selectable( + selected = selected, + onClick = { + onClick() + menuManager.closeAll(localInputModeManager.inputMode, true) + }, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ) + .fillMaxWidth() ) { DisposableEffect(Unit) { if (selected) { @@ -425,17 +406,15 @@ internal fun MenuItem( val itemColors = style.colors.itemColors val itemMetrics = style.metrics.itemMetrics - CompositionLocalProvider( - LocalContentColor provides itemColors.contentFor(itemState).value, - ) { + CompositionLocalProvider(LocalContentColor provides itemColors.contentFor(itemState).value) { val backgroundColor by itemColors.backgroundFor(itemState) Row( modifier = - Modifier.fillMaxWidth() - .defaultMinSize(minHeight = itemMetrics.minHeight) - .drawItemBackground(itemMetrics, backgroundColor) - .padding(itemMetrics.contentPadding), + Modifier.fillMaxWidth() + .defaultMinSize(minHeight = itemMetrics.minHeight) + .drawItemBackground(itemMetrics, backgroundColor) + .padding(itemMetrics.contentPadding), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically, ) { @@ -453,14 +432,12 @@ internal fun MenuItem( } } - Box(modifier = Modifier.weight(1f, true)) { - content() - } + Box(modifier = Modifier.weight(1f, true)) { content() } if (canShowKeybinding) { val keybindingText = remember(keybinding) { - if(hostOs.isMacOS) { + if (hostOs.isMacOS) { keybinding?.joinToString(" ") { it }.orEmpty() } else { keybinding?.joinToString(" + ") { it }.orEmpty() @@ -489,9 +466,8 @@ public fun MenuSubmenuItem( submenu: MenuScope.() -> Unit, content: @Composable () -> Unit, ) { - var itemState by remember(interactionSource) { - mutableStateOf(MenuItemState.of(selected = false, enabled = enabled)) - } + var itemState by + remember(interactionSource) { mutableStateOf(MenuItemState.of(selected = false, enabled = enabled)) } remember(enabled) { itemState = itemState.copy(selected = false, enabled = enabled) } @@ -501,7 +477,8 @@ public fun MenuSubmenuItem( interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> itemState = itemState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> itemState = itemState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> itemState = itemState.copy(pressed = false) is HoverInteraction.Enter -> { itemState = itemState.copy(hovered = true, selected = true) @@ -521,32 +498,29 @@ public fun MenuSubmenuItem( val backgroundColor by itemColors.backgroundFor(itemState) Box( modifier = - modifier - .fillMaxWidth() - .drawItemBackground(menuMetrics.itemMetrics, backgroundColor) - .focusRequester(focusRequester) - .clickable( - onClick = { itemState = itemState.copy(selected = !itemState.isSelected) }, - enabled = enabled, - role = Role.Button, - interactionSource = interactionSource, - indication = null, - ) - .onKeyEvent { - if (it.type == KeyEventType.KeyDown && it.key == Key.DirectionRight) { - itemState = itemState.copy(selected = true) - true - } else { - false + modifier + .fillMaxWidth() + .drawItemBackground(menuMetrics.itemMetrics, backgroundColor) + .focusRequester(focusRequester) + .clickable( + onClick = { itemState = itemState.copy(selected = !itemState.isSelected) }, + enabled = enabled, + role = Role.Button, + interactionSource = interactionSource, + indication = null, + ) + .onKeyEvent { + if (it.type == KeyEventType.KeyDown && it.key == Key.DirectionRight) { + itemState = itemState.copy(selected = true) + true + } else { + false + } } - }, ) { - CompositionLocalProvider( - LocalContentColor provides itemColors.contentFor(itemState).value, - ) { + CompositionLocalProvider(LocalContentColor provides itemColors.contentFor(itemState).value) { Row( - Modifier.fillMaxWidth() - .padding(menuMetrics.itemMetrics.contentPadding), + Modifier.fillMaxWidth().padding(menuMetrics.itemMetrics.contentPadding), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp), ) { @@ -565,7 +539,7 @@ public fun MenuSubmenuItem( tint = itemColors.iconTintFor(itemState).value, contentDescription = null, modifier = Modifier.size(style.metrics.itemMetrics.iconSize), - hint = Stateful(itemState) + hint = Stateful(itemState), ) } } @@ -587,10 +561,7 @@ public fun MenuSubmenuItem( } } -private fun Modifier.drawItemBackground( - itemMetrics: MenuItemMetrics, - backgroundColor: Color, -) = drawBehind { +private fun Modifier.drawItemBackground(itemMetrics: MenuItemMetrics, backgroundColor: Color) = drawBehind { val cornerSizePx = itemMetrics.selectionCornerSize.toPx(size, density = this) val cornerRadius = CornerRadius(cornerSizePx, cornerSizePx) @@ -608,19 +579,13 @@ private fun Modifier.drawItemBackground( ) } -private fun Size.subtract( - paddingValues: PaddingValues, - density: Density, - layoutDirection: LayoutDirection, -): Size = +private fun Size.subtract(paddingValues: PaddingValues, density: Density, layoutDirection: LayoutDirection): Size = with(density) { Size( width - paddingValues.calculateLeftPadding(layoutDirection).toPx() - paddingValues.calculateRightPadding(layoutDirection).toPx(), - height - - paddingValues.calculateTopPadding().toPx() - - paddingValues.calculateBottomPadding().toPx(), + height - paddingValues.calculateTopPadding().toPx() - paddingValues.calculateBottomPadding().toPx(), ) } @@ -645,9 +610,7 @@ internal fun Submenu( var inputModeManager: InputModeManager? by remember { mutableStateOf(null) } val parentMenuManager = LocalMenuManager.current val menuManager = - remember(parentMenuManager, onDismissRequest) { - parentMenuManager.submenuManager(onDismissRequest) - } + remember(parentMenuManager, onDismissRequest) { parentMenuManager.submenuManager(onDismissRequest) } Popup( popupPositionProvider = popupPositionProvider, @@ -656,8 +619,7 @@ internal fun Submenu( onPreviewKeyEvent = { false }, onKeyEvent = { val currentFocusManager = checkNotNull(focusManager) { "FocusManager must not be null" } - val currentInputModeManager = - checkNotNull(inputModeManager) { "InputModeManager must not be null" } + val currentInputModeManager = checkNotNull(inputModeManager) { "InputModeManager must not be null" } handlePopupMenuOnKeyEvent(it, currentFocusManager, currentInputModeManager, menuManager) }, ) { @@ -665,10 +627,7 @@ internal fun Submenu( inputModeManager = LocalInputModeManager.current CompositionLocalProvider(LocalMenuManager provides menuManager) { - MenuContent( - modifier = modifier, - content = content, - ) + MenuContent(modifier = modifier, content = content) } } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/MenuManager.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/MenuManager.kt index 7900ca818..a86e46337 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/MenuManager.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/MenuManager.kt @@ -11,9 +11,8 @@ public class MenuManager( private var isHovered: Boolean = false /** - * Called when the hovered state of the menu changes. This is used to abort - * parent menu closing in unforced mode when submenu closed by click parent - * menu's item. + * Called when the hovered state of the menu changes. This is used to abort parent menu closing in unforced mode + * when submenu closed by click parent menu's item. * * @param hovered true if the menu is hovered, false otherwise. */ @@ -25,13 +24,9 @@ public class MenuManager( * Close all menus in the hierarchy. * * @param mode the input mode, menus close by pointer or keyboard event. - * @param force true to force close all menus ignore parent hover state, - * false otherwise. + * @param force true to force close all menus ignore parent hover state, false otherwise. */ - public fun closeAll( - mode: InputMode, - force: Boolean, - ) { + public fun closeAll(mode: InputMode, force: Boolean) { // We ignore the pointer event if the menu is hovered in unforced mode. if (!force && mode == InputMode.Touch && isHovered) return @@ -50,7 +45,6 @@ public class MenuManager( MenuManager(onDismissRequest = onDismissRequest, parentMenuManager = this) } -public val LocalMenuManager: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No MenuManager provided. Have you forgotten the theme?") - } +public val LocalMenuManager: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No MenuManager provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Popup.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Popup.kt index ed181fe00..dfc259dab 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Popup.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Popup.kt @@ -89,9 +89,7 @@ internal data class AnchorVerticalMenuPositionProvider( // The content offset specified using the dropdown offset parameter. val contentOffsetX = - with(density) { - contentOffset.x.roundToPx() * if (layoutDirection == LayoutDirection.Ltr) 1 else -1 - } + with(density) { contentOffset.x.roundToPx() * if (layoutDirection == LayoutDirection.Ltr) 1 else -1 } val contentOffsetY = with(density) { contentOffset.y.roundToPx() } // Compute horizontal position. @@ -115,8 +113,7 @@ internal data class AnchorVerticalMenuPositionProvider( } val popupBounds = - IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height) - .constrainedIn(windowSpaceBounds) + IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height).constrainedIn(windowSpaceBounds) return IntOffset(popupBounds.left, popupBounds.top) } @@ -150,16 +147,11 @@ internal data class AnchorHorizontalMenuPositionProvider( // The content offset specified using the dropdown offset parameter. val contentOffsetX = - with(density) { - contentOffset.x.roundToPx() * if (layoutDirection == LayoutDirection.Ltr) 1 else -1 - } + with(density) { contentOffset.x.roundToPx() * if (layoutDirection == LayoutDirection.Ltr) 1 else -1 } val contentOffsetY = with(density) { contentOffset.y.roundToPx() } // Compute horizontal position. - val y = - anchorBounds.top + - alignment.align(popupContentSize.height, anchorBounds.height) + - contentOffsetY + val y = anchorBounds.top + alignment.align(popupContentSize.height, anchorBounds.height) + contentOffsetY // Compute vertical position. val leftSpacing = anchorBounds.left - contentOffsetX - windowSpaceBounds.left @@ -173,8 +165,7 @@ internal data class AnchorHorizontalMenuPositionProvider( } val popupBounds = - IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height) - .constrainedIn(windowSpaceBounds) + IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height).constrainedIn(windowSpaceBounds) return IntOffset(popupBounds.left, popupBounds.top) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/RadioButton.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/RadioButton.kt index 58d307a0a..807d3b9d4 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/RadioButton.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/RadioButton.kt @@ -140,28 +140,20 @@ private fun RadioButtonImpl( verticalAlignment: Alignment.Vertical, content: (@Composable RowScope.() -> Unit)?, ) { - var radioButtonState by remember { - mutableStateOf(RadioButtonState.of(selected = selected, enabled = enabled)) - } + var radioButtonState by remember { mutableStateOf(RadioButtonState.of(selected = selected, enabled = enabled)) } - remember(selected, enabled) { - radioButtonState = radioButtonState.copy(selected = selected, enabled = enabled) - } + remember(selected, enabled) { radioButtonState = radioButtonState.copy(selected = selected, enabled = enabled) } val swingCompatMode = JewelTheme.isSwingCompatMode LaunchedEffect(interactionSource, swingCompatMode) { interactionSource.interactions.collect { interaction -> when (interaction) { - is PressInteraction.Press -> - radioButtonState = - radioButtonState.copy(pressed = !swingCompatMode) + is PressInteraction.Press -> radioButtonState = radioButtonState.copy(pressed = !swingCompatMode) - is PressInteraction.Cancel, is PressInteraction.Release -> - radioButtonState = radioButtonState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> radioButtonState = radioButtonState.copy(pressed = false) - is HoverInteraction.Enter -> - radioButtonState = - radioButtonState.copy(hovered = !swingCompatMode) + is HoverInteraction.Enter -> radioButtonState = radioButtonState.copy(hovered = !swingCompatMode) is HoverInteraction.Exit -> radioButtonState = radioButtonState.copy(hovered = false) is FocusInteraction.Focus -> radioButtonState = radioButtonState.copy(focused = true) @@ -182,18 +174,12 @@ private fun RadioButtonImpl( val colors = style.colors val metrics = style.metrics - val radioButtonModifier = Modifier.size(metrics.radioButtonSize) - .outline( - radioButtonState, - outline, - outlineShape = CircleShape, - alignment = Stroke.Alignment.Inside, - ) + val radioButtonModifier = + Modifier.size(metrics.radioButtonSize) + .outline(radioButtonState, outline, outlineShape = CircleShape, alignment = Stroke.Alignment.Inside) val radioButtonPainterProvider = rememberResourcePainterProvider(style.icons.radioButton) - val radioButtonPainter by radioButtonPainterProvider.getPainter( - Selected(radioButtonState), - Stateful(radioButtonState), - ) + val radioButtonPainter by + radioButtonPainterProvider.getPainter(Selected(radioButtonState), Stateful(radioButtonState)) if (content == null) { RadioButtonImage(wrapperModifier, radioButtonPainter, radioButtonModifier) @@ -206,8 +192,8 @@ private fun RadioButtonImpl( RadioButtonImage(Modifier, radioButtonPainter, radioButtonModifier) val contentColor by colors.contentFor(radioButtonState) - val resolvedContentColor = contentColor.takeOrElse { textStyle.color } - .takeOrElse { LocalContentColor.current } + val resolvedContentColor = + contentColor.takeOrElse { textStyle.color }.takeOrElse { LocalContentColor.current } CompositionLocalProvider( LocalTextStyle provides textStyle.copy(color = contentColor.takeOrElse { textStyle.color }), @@ -220,14 +206,8 @@ private fun RadioButtonImpl( } @Composable -private fun RadioButtonImage( - outerModifier: Modifier, - radioButtonPainter: Painter, - radioButtonModifier: Modifier, -) { - Box(outerModifier) { - Image(radioButtonPainter, contentDescription = null, modifier = radioButtonModifier) - } +private fun RadioButtonImage(outerModifier: Modifier, radioButtonPainter: Painter, radioButtonModifier: Modifier) { + Box(outerModifier) { Image(radioButtonPainter, contentDescription = null, modifier = radioButtonModifier) } } @Immutable @@ -287,7 +267,7 @@ public value class RadioButtonState(public val state: ULong) : SelectableCompone (if (focused) Focused else 0UL) or (if (pressed) Pressed else 0UL) or (if (hovered) Hovered else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ScrollableContainer.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ScrollableContainer.kt index 33565b0d3..15fcb2a50 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ScrollableContainer.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/ScrollableContainer.kt @@ -28,6 +28,7 @@ import androidx.compose.ui.layout.layoutId import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp +import kotlin.time.Duration import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -40,7 +41,6 @@ import org.jetbrains.jewel.ui.component.styling.ScrollbarVisibility.WhenScrollin import org.jetbrains.jewel.ui.theme.scrollbarStyle import org.jetbrains.skiko.OS import org.jetbrains.skiko.hostOs -import kotlin.time.Duration private const val ID_CONTENT = "VerticallyScrollableContainer_content" private const val ID_VERTICAL_SCROLLBAR = "VerticallyScrollableContainer_verticalScrollbar" diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Scrollbar.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Scrollbar.kt index ab763b0d2..55c30fdf1 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Scrollbar.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Scrollbar.kt @@ -61,6 +61,7 @@ import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.constrainHeight import androidx.compose.ui.unit.constrainWidth import androidx.compose.ui.unit.dp +import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job @@ -77,7 +78,6 @@ import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior.JumpToSpot import org.jetbrains.jewel.ui.component.styling.TrackClickBehavior.NextPage import org.jetbrains.jewel.ui.theme.scrollbarStyle import org.jetbrains.jewel.ui.util.thenIf -import kotlin.math.roundToInt @Composable public fun VerticalScrollbar( diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControl.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControl.kt index f97177954..30e9d66ff 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControl.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControl.kt @@ -55,9 +55,7 @@ public fun SegmentedControl( val borderColor by style.colors.borderFor(segmentedControlState) val borderWidth = style.metrics.borderWidth - val selectedButtonIndex = remember(buttons) { - buttons.withIndex().singleOrNull { it.value.selected }?.index ?: -1 - } + val selectedButtonIndex = remember(buttons) { buttons.withIndex().singleOrNull { it.value.selected }?.index ?: -1 } Box(modifier) { val shape = RoundedCornerShape((style.metrics.cornerSize)) @@ -68,32 +66,32 @@ public fun SegmentedControl( ) Row( - modifier = Modifier - .onFocusEvent { segmentedControlState = segmentedControlState.copy(focused = it.isFocused) } - .onKeyEvent { - when { - KeyEventType.KeyUp == it.type && Key.DirectionRight == it.key -> { - if (selectedButtonIndex < buttons.size - 1) { - buttons[selectedButtonIndex + 1].onSelect() + modifier = + Modifier.onFocusEvent { segmentedControlState = segmentedControlState.copy(focused = it.isFocused) } + .onKeyEvent { + when { + KeyEventType.KeyUp == it.type && Key.DirectionRight == it.key -> { + if (selectedButtonIndex < buttons.size - 1) { + buttons[selectedButtonIndex + 1].onSelect() + } + true } - true - } - KeyEventType.KeyUp == it.type && Key.DirectionLeft == it.key -> { - if (selectedButtonIndex > 0) { - buttons[selectedButtonIndex - 1].onSelect() + KeyEventType.KeyUp == it.type && Key.DirectionLeft == it.key -> { + if (selectedButtonIndex > 0) { + buttons[selectedButtonIndex - 1].onSelect() + } + true } - true - } - else -> false + else -> false + } } - } - .focusable(enabled, interactionSource) - .selectableGroup() - .padding(style.metrics.borderWidth), + .focusable(enabled, interactionSource) + .selectableGroup() + .padding(style.metrics.borderWidth), horizontalArrangement = Arrangement.aligned(Alignment.CenterHorizontally), - verticalAlignment = Alignment.CenterVertically + verticalAlignment = Alignment.CenterVertically, ) { buttons.forEach { data -> SegmentedControlButton( @@ -114,7 +112,9 @@ public fun SegmentedControl( @GenerateDataFunctions public class SegmentedControlButtonData( public val selected: Boolean, - public val content: @Composable SegmentedControlButtonScope.(segmentedControlButtonState: SegmentedControlButtonState) -> Unit, + public val content: + @Composable + SegmentedControlButtonScope.(segmentedControlButtonState: SegmentedControlButtonState) -> Unit, public val onSelect: () -> Unit, ) @@ -143,13 +143,8 @@ public value class SegmentedControlState(public val state: ULong) : FocusableCom pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): SegmentedControlState = of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): SegmentedControlState = + of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, isHovered=$isHovered, " + @@ -169,7 +164,7 @@ public value class SegmentedControlState(public val state: ULong) : FocusableCom (if (focused) CommonStateBitMask.Focused else 0UL) or (if (hovered) CommonStateBitMask.Hovered else 0UL) or (if (pressed) CommonStateBitMask.Pressed else 0UL) or - (if (active) CommonStateBitMask.Active else 0UL), + (if (active) CommonStateBitMask.Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControlButton.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControlButton.kt index 22c26f609..440409597 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControlButton.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SegmentedControlButton.kt @@ -57,7 +57,7 @@ internal fun SegmentedControlButton( SegmentedControlButtonState.of( selected = segmentedControlButtonData.selected, active = isActive, - enabled = enabled + enabled = enabled, ) ) } @@ -70,8 +70,8 @@ internal fun SegmentedControlButton( interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> buttonState = buttonState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> - buttonState = buttonState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> buttonState = buttonState.copy(pressed = false) is HoverInteraction.Enter -> buttonState = buttonState.copy(hovered = true) is HoverInteraction.Exit -> buttonState = buttonState.copy(hovered = false) @@ -85,18 +85,19 @@ internal fun SegmentedControlButton( val borderColor by colors.borderFor(buttonState, isFocused) Box( - modifier = modifier - .focusProperties { canFocus = false } - .selectable( - selected = buttonState.isSelected, - interactionSource = interactionSource, - enabled = enabled, - indication = null, - role = Role.Button, - onClick = segmentedControlButtonData.onSelect, - ) - .background(backgroundColor, shape) - .border(alignment = Stroke.Alignment.Center, width = style.metrics.borderWidth, borderColor, shape), + modifier = + modifier + .focusProperties { canFocus = false } + .selectable( + selected = buttonState.isSelected, + interactionSource = interactionSource, + enabled = enabled, + indication = null, + role = Role.Button, + onClick = segmentedControlButtonData.onSelect, + ) + .background(backgroundColor, shape) + .border(alignment = Stroke.Alignment.Center, width = style.metrics.borderWidth, borderColor, shape), propagateMinConstraints = true, ) { val contentColor by colors.contentFor(buttonState) @@ -143,13 +144,7 @@ public value class SegmentedControlButtonState(public val state: ULong) : Select hovered: Boolean = isHovered, active: Boolean = isActive, ): SegmentedControlButtonState = - of( - selected = selected, - enabled = enabled, - pressed = pressed, - hovered = hovered, - active = active, - ) + of(selected = selected, enabled = enabled, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isSelected=$isSelected, isEnabled=$isEnabled, " + @@ -169,7 +164,7 @@ public value class SegmentedControlButtonState(public val state: ULong) : Select (if (enabled) Enabled else 0UL) or (if (pressed) Pressed else 0UL) or (if (hovered) Hovered else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Slider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Slider.kt index 8958bc1f4..324f3a4aa 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Slider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Slider.kt @@ -68,6 +68,9 @@ import androidx.compose.ui.semantics.setProgress import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import org.jetbrains.jewel.foundation.Stroke @@ -82,9 +85,6 @@ import org.jetbrains.jewel.foundation.theme.JewelTheme import org.jetbrains.jewel.ui.component.styling.SliderStyle import org.jetbrains.jewel.ui.focusOutline import org.jetbrains.jewel.ui.theme.sliderStyle -import kotlin.math.abs -import kotlin.math.max -import kotlin.math.min // Note: a lot of code in this file is from the Material 2 implementation @@ -104,10 +104,7 @@ public fun Slider( val onValueChangeState = rememberUpdatedState(onValueChange) val onValueChangeFinishedState = rememberUpdatedState(onValueChangeFinished) - val tickFractions = - remember(steps) { - stepsToTickFractions(steps) - } + val tickFractions = remember(steps) { stepsToTickFractions(steps) } val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl val focusRequester = remember { FocusRequester() } @@ -127,7 +124,7 @@ public fun Slider( .sliderSemantics(value, enabled, onValueChange, onValueChangeFinished, valueRange, steps) .focusRequester(focusRequester) .focusable(enabled, interactionSource) - .slideOnKeyEvents(enabled, steps, valueRange, value, isRtl, onValueChangeState, onValueChangeFinishedState), + .slideOnKeyEvents(enabled, steps, valueRange, value, isRtl, onValueChangeState, onValueChangeFinishedState) ) { val widthPx = constraints.maxWidth.toFloat() val maxPx: Float @@ -169,9 +166,7 @@ public fun Slider( if (canAnimate) { animateToTarget(draggableState, current, target, velocity) } else { - draggableState.drag { - dragBy(target - current) - } + draggableState.drag { dragBy(target - current) } } onValueChangeFinished?.invoke() } @@ -231,17 +226,9 @@ private fun SliderImpl( interactionSource: MutableInteractionSource, modifier: Modifier, ) { - Box( - modifier.then( - Modifier - .widthIn(min = SliderMinWidth) - .heightIn(min = minHeight), - ), - ) { + Box(modifier.then(Modifier.widthIn(min = SliderMinWidth).heightIn(min = minHeight))) { val widthDp: Dp - with(LocalDensity.current) { - widthDp = width.toDp() - } + with(LocalDensity.current) { widthDp = width.toDp() } Track( modifier = Modifier.fillMaxWidth(), @@ -333,24 +320,20 @@ private fun BoxScope.SliderThumb( enabled: Boolean, modifier: Modifier = Modifier, ) { - Box( - Modifier - .padding(start = offset, top = style.metrics.thumbBorderWidth) - .align(Alignment.TopStart), - ) { + Box(Modifier.padding(start = offset, top = style.metrics.thumbBorderWidth).align(Alignment.TopStart)) { var state by remember { mutableStateOf(SliderState.of(enabled)) } remember(enabled) { state = state.copy(enabled = enabled) } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { - is PressInteraction.Press, is DragInteraction.Start -> - state = state.copy(pressed = true) + is PressInteraction.Press, + is DragInteraction.Start -> state = state.copy(pressed = true) - is PressInteraction.Release, is PressInteraction.Cancel, - is DragInteraction.Stop, is DragInteraction.Cancel, - -> - state = state.copy(pressed = false) + is PressInteraction.Release, + is PressInteraction.Cancel, + is DragInteraction.Stop, + is DragInteraction.Cancel -> state = state.copy(pressed = false) is HoverInteraction.Enter -> state = state.copy(hovered = true) is HoverInteraction.Exit -> state = state.copy(hovered = false) @@ -372,40 +355,24 @@ private fun BoxScope.SliderThumb( color = style.colors.thumbBorderFor(state).value, shape = style.thumbShape, ) - .focusOutline(state, style.thumbShape), + .focusOutline(state, style.thumbShape) ) } } -private fun snapValueToTick( - current: Float, - tickFractions: List, - minPx: Float, - maxPx: Float, -): Float = +private fun snapValueToTick(current: Float, tickFractions: List, minPx: Float, maxPx: Float): Float = // target is a closest anchor to the `current`, if exists - tickFractions - .minByOrNull { abs(lerp(minPx, maxPx, it) - current) } - ?.run { lerp(minPx, maxPx, this) } - ?: current + tickFractions.minByOrNull { abs(lerp(minPx, maxPx, it) - current) }?.run { lerp(minPx, maxPx, this) } ?: current -private fun stepsToTickFractions(steps: Int): List = if (steps == 0) emptyList() else List(steps + 2) { it.toFloat() / (steps + 1) } +private fun stepsToTickFractions(steps: Int): List = + if (steps == 0) emptyList() else List(steps + 2) { it.toFloat() / (steps + 1) } // Scale x1 from a1..b1 range to a2..b2 range -private fun scale( - a1: Float, - b1: Float, - x1: Float, - a2: Float, - b2: Float, -) = lerp(a2, b2, calcFraction(a1, b1, x1)) +private fun scale(a1: Float, b1: Float, x1: Float, a2: Float, b2: Float) = lerp(a2, b2, calcFraction(a1, b1, x1)) // Calculate the 0..1 fraction that `pos` value represents between `a` and `b` -private fun calcFraction( - a: Float, - b: Float, - pos: Float, -) = (if (b - a == 0f) 0f else (pos - a) / (b - a)).coerceIn(0f, 1f) +private fun calcFraction(a: Float, b: Float, pos: Float) = + (if (b - a == 0f) 0f else (pos - a) / (b - a)).coerceIn(0f, 1f) @Composable private fun CorrectValueSideEffect( @@ -435,43 +402,40 @@ private fun Modifier.sliderSemantics( val coerced = value.coerceIn(valueRange.start, valueRange.endInclusive) return semantics { - if (!enabled) disabled() - - setProgress( - action = { targetValue -> - var newValue = targetValue.coerceIn(valueRange.start, valueRange.endInclusive) - val originalVal = newValue - val resolvedValue = - if (steps > 0) { - var distance: Float = newValue - for (i in 0..steps + 1) { - val stepValue = - lerp( - valueRange.start, - valueRange.endInclusive, - i.toFloat() / (steps + 1), - ) - if (abs(stepValue - originalVal) <= distance) { - distance = abs(stepValue - originalVal) - newValue = stepValue + if (!enabled) disabled() + + setProgress( + action = { targetValue -> + var newValue = targetValue.coerceIn(valueRange.start, valueRange.endInclusive) + val originalVal = newValue + val resolvedValue = + if (steps > 0) { + var distance: Float = newValue + for (i in 0..steps + 1) { + val stepValue = + lerp(valueRange.start, valueRange.endInclusive, i.toFloat() / (steps + 1)) + if (abs(stepValue - originalVal) <= distance) { + distance = abs(stepValue - originalVal) + newValue = stepValue + } } + newValue + } else { + newValue } - newValue + // This is to keep it consistent with AbsSeekbar.java: return false if no + // change from current. + if (resolvedValue == coerced) { + false } else { - newValue + onValueChange(resolvedValue) + onValueChangeFinished?.invoke() + true } - // This is to keep it consistent with AbsSeekbar.java: return false if no - // change from current. - if (resolvedValue == coerced) { - false - } else { - onValueChange(resolvedValue) - onValueChangeFinished?.invoke() - true } - }, - ) - }.progressSemantics(value, valueRange, steps) + ) + } + .progressSemantics(value, valueRange, steps) } private fun Modifier.sliderTapModifier( @@ -483,58 +447,54 @@ private fun Modifier.sliderTapModifier( gestureEndAction: State<(Float) -> Unit>, pressOffset: MutableState, enabled: Boolean, -) = composed( - factory = { - if (enabled) { - val scope = rememberCoroutineScope() - pointerInput(draggableState, interactionSource, maxPx, isRtl) { - detectTapGestures( - onPress = { pos -> - val to = if (isRtl) maxPx - pos.x else pos.x - pressOffset.value = to - rawOffset.value - try { - awaitRelease() - } catch (_: GestureCancellationException) { - pressOffset.value = 0f - } - }, - onTap = { - scope.launch { - draggableState.drag(MutatePriority.UserInput) { - // just trigger animation, press offset will be applied - dragBy(0f) +) = + composed( + factory = { + if (enabled) { + val scope = rememberCoroutineScope() + pointerInput(draggableState, interactionSource, maxPx, isRtl) { + detectTapGestures( + onPress = { pos -> + val to = if (isRtl) maxPx - pos.x else pos.x + pressOffset.value = to - rawOffset.value + try { + awaitRelease() + } catch (_: GestureCancellationException) { + pressOffset.value = 0f } - gestureEndAction.value.invoke(0f) - } - }, - ) + }, + onTap = { + scope.launch { + draggableState.drag(MutatePriority.UserInput) { + // just trigger animation, press offset will be applied + dragBy(0f) + } + gestureEndAction.value.invoke(0f) + } + }, + ) + } + } else { + this } - } else { - this - } - }, - inspectorInfo = - debugInspectorInfo { - name = "sliderTapModifier" - properties["draggableState"] = draggableState - properties["interactionSource"] = interactionSource - properties["maxPx"] = maxPx - properties["isRtl"] = isRtl - properties["rawOffset"] = rawOffset - properties["gestureEndAction"] = gestureEndAction - properties["pressOffset"] = pressOffset - properties["enabled"] = enabled - }, -) + }, + inspectorInfo = + debugInspectorInfo { + name = "sliderTapModifier" + properties["draggableState"] = draggableState + properties["interactionSource"] = interactionSource + properties["maxPx"] = maxPx + properties["isRtl"] = isRtl + properties["rawOffset"] = rawOffset + properties["gestureEndAction"] = gestureEndAction + properties["pressOffset"] = pressOffset + properties["enabled"] = enabled + }, + ) private val SliderToTickAnimation = TweenSpec(durationMillis = 100) -private suspend fun animateToTarget( - draggableState: DraggableState, - current: Float, - target: Float, - velocity: Float, -) { +private suspend fun animateToTarget(draggableState: DraggableState, current: Float, target: Float, velocity: Float) { draggableState.drag { var latestValue = current Animatable(initialValue = current).animateTo(target, SliderToTickAnimation, velocity) { @@ -544,7 +504,8 @@ private suspend fun animateToTarget( } } -// TODO: Edge case - losing focus on slider while key is pressed will end up with onValueChangeFinished not being invoked +// TODO: Edge case - losing focus on slider while key is pressed will end up with +// onValueChangeFinished not being invoked @OptIn(ExperimentalComposeUiApi::class) private fun Modifier.slideOnKeyEvents( enabled: Boolean, @@ -563,9 +524,12 @@ private fun Modifier.slideOnKeyEvents( when (it.type) { KeyEventType.KeyDown -> { val rangeLength = abs(valueRange.endInclusive - valueRange.start) - // When steps == 0, it means that a user is not limited by a step length (delta) when using touch or mouse. - // But it is not possible to adjust the value continuously when using keyboard buttons - - // the delta has to be discrete. In this case, 1% of the valueRange seems to make sense. + // When steps == 0, it means that a user is not limited by a step length (delta) + // when using touch or mouse. + // But it is not possible to adjust the value continuously when using keyboard + // buttons - + // the delta has to be discrete. In this case, 1% of the valueRange seems to make + // sense. val actualSteps = if (steps > 0) steps + 1 else 100 val delta = rangeLength / actualSteps when { @@ -619,8 +583,15 @@ private fun Modifier.slideOnKeyEvents( KeyEventType.KeyUp -> { @Suppress("ComplexCondition") // In original m2 code - if (it.isDirectionDown || it.isDirectionUp || it.isDirectionRight || - it.isDirectionLeft || it.isHome || it.isMoveEnd || it.isPgUp || it.isPgDn + if ( + it.isDirectionDown || + it.isDirectionUp || + it.isDirectionRight || + it.isDirectionLeft || + it.isHome || + it.isMoveEnd || + it.isPgUp || + it.isPgDn ) { onValueChangeFinishedState.value?.invoke() true @@ -658,11 +629,7 @@ internal val KeyEvent.isPgUp: Boolean internal val KeyEvent.isPgDn: Boolean get() = key.nativeKeyCode == java.awt.event.KeyEvent.VK_PAGE_DOWN -internal fun lerp( - start: Float, - stop: Float, - fraction: Float, -): Float = (1 - fraction) * start + fraction * stop +internal fun lerp(start: Float, stop: Float, fraction: Float): Float = (1 - fraction) * start + fraction * stop @Immutable @JvmInline @@ -688,14 +655,7 @@ public value class SliderState(public val state: ULong) : FocusableComponentStat pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): SliderState = - of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): SliderState = of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, isHovered=$isHovered, " + @@ -714,14 +674,12 @@ public value class SliderState(public val state: ULong) : FocusableComponentStat (if (focused) Focused else 0UL) or (if (hovered) Hovered else 0UL) or (if (pressed) Pressed else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } -private class SliderDraggableState( - val onDelta: (Float) -> Unit, -) : DraggableState { +private class SliderDraggableState(val onDelta: (Float) -> Unit) : DraggableState { var isDragging by mutableStateOf(false) private set @@ -734,10 +692,7 @@ private class SliderDraggableState( private val scrollMutex = MutatorMutex() - override suspend fun drag( - dragPriority: MutatePriority, - block: suspend DragScope.() -> Unit, - ) { + override suspend fun drag(dragPriority: MutatePriority, block: suspend DragScope.() -> Unit) { coroutineScope { isDragging = true scrollMutex.mutateWith(dragScope, dragPriority, block) diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SplitLayout.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SplitLayout.kt index 0e5df98ac..6d3d43416 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SplitLayout.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/SplitLayout.kt @@ -1,5 +1,6 @@ package org.jetbrains.jewel.ui.component +import androidx.compose.foundation.gestures.Orientation as ComposeOrientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.interaction.MutableInteractionSource @@ -23,11 +24,10 @@ import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp -import org.jetbrains.jewel.foundation.theme.JewelTheme -import org.jetbrains.jewel.ui.Orientation import java.awt.Cursor import kotlin.math.roundToInt -import androidx.compose.foundation.gestures.Orientation as ComposeOrientation +import org.jetbrains.jewel.foundation.theme.JewelTheme +import org.jetbrains.jewel.ui.Orientation @Composable public fun HorizontalSplitLayout( @@ -70,29 +70,24 @@ public fun HorizontalSplitLayout( state = rememberDraggableState { delta -> dividerX += delta.toInt() }, ) .pointerHoverIcon(PointerIcon(Cursor(Cursor.E_RESIZE_CURSOR))) - .layoutId("divider-handle"), + .layoutId("divider-handle") ) }, ) { measurables, incomingConstraints -> val availableWidth = incomingConstraints.maxWidth val actualDividerX = - dividerX.coerceIn(0, availableWidth) - .coerceIn( - (availableWidth * minRatio).roundToInt(), - (availableWidth * maxRatio).roundToInt(), - ) + dividerX + .coerceIn(0, availableWidth) + .coerceIn((availableWidth * minRatio).roundToInt(), (availableWidth * maxRatio).roundToInt()) val dividerMeasurable = measurables.single { it.layoutId == "divider" } val dividerPlaceable = - dividerMeasurable.measure( - Constraints.fixed(dividerThickness.roundToPx(), incomingConstraints.maxHeight), - ) + dividerMeasurable.measure(Constraints.fixed(dividerThickness.roundToPx(), incomingConstraints.maxHeight)) val firstComponentConstraints = Constraints.fixed((actualDividerX).coerceAtLeast(0), incomingConstraints.maxHeight) val firstPlaceable = - measurables.find { it.layoutId == "first" } - ?.measure(firstComponentConstraints) + measurables.find { it.layoutId == "first" }?.measure(firstComponentConstraints) ?: error("No first component found. Have you applied the provided Modifier to it?") val secondComponentConstraints = @@ -101,12 +96,12 @@ public fun HorizontalSplitLayout( height = incomingConstraints.maxHeight, ) val secondPlaceable = - measurables.find { it.layoutId == "second" } - ?.measure(secondComponentConstraints) + measurables.find { it.layoutId == "second" }?.measure(secondComponentConstraints) ?: error("No second component found. Have you applied the provided Modifier to it?") val dividerHandlePlaceable = - measurables.single { it.layoutId == "divider-handle" } + measurables + .single { it.layoutId == "divider-handle" } .measure(Constraints.fixedHeight(incomingConstraints.maxHeight)) layout(availableWidth, incomingConstraints.maxHeight) { @@ -159,29 +154,24 @@ public fun VerticalSplitLayout( state = rememberDraggableState { delta -> dividerY += delta.toInt() }, ) .pointerHoverIcon(PointerIcon(Cursor(Cursor.N_RESIZE_CURSOR))) - .layoutId("divider-handle"), + .layoutId("divider-handle") ) }, ) { measurables, incomingConstraints -> val availableHeight = incomingConstraints.maxHeight val actualDividerY = - dividerY.coerceIn(0, availableHeight) - .coerceIn( - (availableHeight * minRatio).roundToInt(), - (availableHeight * maxRatio).roundToInt(), - ) + dividerY + .coerceIn(0, availableHeight) + .coerceIn((availableHeight * minRatio).roundToInt(), (availableHeight * maxRatio).roundToInt()) val dividerMeasurable = measurables.single { it.layoutId == "divider" } val dividerPlaceable = - dividerMeasurable.measure( - Constraints.fixed(incomingConstraints.maxWidth, dividerThickness.roundToPx()), - ) + dividerMeasurable.measure(Constraints.fixed(incomingConstraints.maxWidth, dividerThickness.roundToPx())) val firstComponentConstraints = Constraints.fixed(incomingConstraints.maxWidth, (actualDividerY - 1).coerceAtLeast(0)) val firstPlaceable = - measurables.find { it.layoutId == "first" } - ?.measure(firstComponentConstraints) + measurables.find { it.layoutId == "first" }?.measure(firstComponentConstraints) ?: error("No first component found. Have you applied the provided Modifier to it?") val secondComponentConstraints = @@ -190,12 +180,12 @@ public fun VerticalSplitLayout( height = availableHeight - actualDividerY + dividerPlaceable.height, ) val secondPlaceable = - measurables.find { it.layoutId == "second" } - ?.measure(secondComponentConstraints) + measurables.find { it.layoutId == "second" }?.measure(secondComponentConstraints) ?: error("No second component found. Have you applied the provided Modifier to it?") val dividerHandlePlaceable = - measurables.single { it.layoutId == "divider-handle" } + measurables + .single { it.layoutId == "divider-handle" } .measure(Constraints.fixedWidth(incomingConstraints.maxWidth)) layout(incomingConstraints.maxWidth, availableHeight) { diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TabStrip.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TabStrip.kt index cd83d43a2..752dd181e 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TabStrip.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TabStrip.kt @@ -31,26 +31,20 @@ import org.jetbrains.jewel.foundation.state.FocusableComponentState import org.jetbrains.jewel.ui.component.styling.TabStyle @Composable -public fun TabStrip( - tabs: List, - style: TabStyle, - modifier: Modifier = Modifier, - enabled: Boolean = true, -) { +public fun TabStrip(tabs: List, style: TabStyle, modifier: Modifier = Modifier, enabled: Boolean = true) { var tabStripState: TabStripState by remember { mutableStateOf(TabStripState.of(enabled = true)) } remember(enabled) { tabStripState = tabStripState.copy(enabled) } val scrollState = rememberScrollState() Box( - modifier - .focusable(true, remember { MutableInteractionSource() }) - .onHover { tabStripState = tabStripState.copy(hovered = it) }, + modifier.focusable(true, remember { MutableInteractionSource() }).onHover { + tabStripState = tabStripState.copy(hovered = it) + } ) { Row( modifier = - Modifier - .horizontalScroll(scrollState) + Modifier.horizontalScroll(scrollState) .scrollable( orientation = Orientation.Vertical, reverseDirection = @@ -61,7 +55,8 @@ public fun TabStrip( ), state = scrollState, interactionSource = remember { MutableInteractionSource() }, - ).selectableGroup(), + ) + .selectableGroup() ) { tabs.forEach { TabImpl(isActive = tabStripState.isActive, tabData = it) } } @@ -71,11 +66,7 @@ public fun TabStrip( enter = fadeIn(tween(durationMillis = 125, delayMillis = 0, easing = LinearEasing)), exit = fadeOut(tween(durationMillis = 125, delayMillis = 700, easing = LinearEasing)), ) { - HorizontalScrollbar( - scrollState, - style = style.scrollbarStyle, - modifier = Modifier.fillMaxWidth(), - ) + HorizontalScrollbar(scrollState, style = style.scrollbarStyle, modifier = Modifier.fillMaxWidth()) } } } @@ -133,14 +124,7 @@ public value class TabStripState(public val state: ULong) : FocusableComponentSt pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): TabStripState = - of( - enabled = enabled, - focused = focused, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): TabStripState = of(enabled = enabled, focused = focused, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isEnabled=$isEnabled, isFocused=$isFocused, isHovered=$isHovered, " + @@ -159,7 +143,7 @@ public value class TabStripState(public val state: ULong) : FocusableComponentSt (if (focused) CommonStateBitMask.Focused else 0UL) or (if (hovered) CommonStateBitMask.Hovered else 0UL) or (if (pressed) CommonStateBitMask.Pressed else 0UL) or - (if (active) CommonStateBitMask.Active else 0UL), + (if (active) CommonStateBitMask.Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tabs.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tabs.kt index 6f110d7a9..b12ade433 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tabs.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tabs.kt @@ -120,18 +120,15 @@ internal fun TabImpl( is TabData.Editor -> JewelTheme.editorTabStyle } - var tabState by remember { - mutableStateOf(TabState.of(selected = tabData.selected, active = isActive)) - } - remember(tabData.selected, isActive) { - tabState = tabState.copy(selected = tabData.selected, active = isActive) - } + var tabState by remember { mutableStateOf(TabState.of(selected = tabData.selected, active = isActive)) } + remember(tabData.selected, isActive) { tabState = tabState.copy(selected = tabData.selected, active = isActive) } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> tabState = tabState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> tabState = tabState.copy(pressed = false) + is PressInteraction.Cancel, + is PressInteraction.Release -> tabState = tabState.copy(pressed = false) is HoverInteraction.Enter -> tabState = tabState.copy(hovered = true) is HoverInteraction.Exit -> tabState = tabState.copy(hovered = false) } @@ -142,13 +139,12 @@ internal fun TabImpl( val lineThickness = tabStyle.metrics.underlineThickness val backgroundColor by tabStyle.colors.backgroundFor(state = tabState) - val resolvedContentColor = - tabStyle.colors.contentFor(tabState).value - .takeOrElse { LocalContentColor.current } + val resolvedContentColor = tabStyle.colors.contentFor(tabState).value.takeOrElse { LocalContentColor.current } CompositionLocalProvider(LocalContentColor provides resolvedContentColor) { Row( - modifier.height(tabStyle.metrics.tabHeight) + modifier + .height(tabStyle.metrics.tabHeight) .background(backgroundColor) .focusProperties { canFocus = false } .selectable( @@ -191,7 +187,8 @@ internal fun TabImpl( closeActionInteractionSource.interactions.collect { interaction -> when (interaction) { is PressInteraction.Press -> closeButtonState = closeButtonState.copy(pressed = true) - is PressInteraction.Cancel, is PressInteraction.Release -> { + is PressInteraction.Cancel, + is PressInteraction.Release -> { closeButtonState = closeButtonState.copy(pressed = false) } @@ -205,14 +202,13 @@ internal fun TabImpl( Icon( key = tabStyle.icons.close, modifier = - Modifier - .clickable( - interactionSource = closeActionInteractionSource, - indication = null, - onClick = tabData.onClose, - role = Role.Button, - ) - .size(16.dp), + Modifier.clickable( + interactionSource = closeActionInteractionSource, + indication = null, + onClick = tabData.onClose, + role = Role.Button, + ) + .size(16.dp), contentDescription = "Close tab", hint = Stateful(closeButtonState), ) @@ -247,14 +243,7 @@ public value class TabState(public val state: ULong) : SelectableComponentState pressed: Boolean = isPressed, hovered: Boolean = isHovered, active: Boolean = isActive, - ): TabState = - of( - selected = selected, - enabled = enabled, - pressed = pressed, - hovered = hovered, - active = active, - ) + ): TabState = of(selected = selected, enabled = enabled, pressed = pressed, hovered = hovered, active = active) override fun toString(): String = "${javaClass.simpleName}(isSelected=$isSelected, isEnabled=$isEnabled, " + @@ -273,7 +262,7 @@ public value class TabState(public val state: ULong) : SelectableComponentState (if (enabled) Enabled else 0UL) or (if (pressed) Pressed else 0UL) or (if (hovered) Hovered else 0UL) or - (if (active) Active else 0UL), + (if (active) Active else 0UL) ) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Text.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Text.kt index 9f007876a..54a5802c7 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Text.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Text.kt @@ -93,18 +93,8 @@ public fun Text( textDecoration = textDecoration, fontStyle = fontStyle, letterSpacing = letterSpacing, - ), + ) ) - BasicText( - text, - modifier, - mergedStyle, - onTextLayout, - overflow, - softWrap, - maxLines, - minLines = 1, - inlineContent, - ) + BasicText(text, modifier, mergedStyle, onTextLayout, overflow, softWrap, maxLines, minLines = 1, inlineContent) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TextField.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TextField.kt index fd6f16134..dbd649343 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TextField.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/TextField.kt @@ -202,8 +202,8 @@ public fun TextField( TextFieldDecorationBox( modifier = - Modifier.defaultMinSize(minWidth = minSize.width, minHeight = minSize.height) - .padding(style.metrics.contentPadding), + Modifier.defaultMinSize(minWidth = minSize.width, minHeight = minSize.height) + .padding(style.metrics.contentPadding), innerTextField = innerTextField, textStyle = textStyle, placeholderTextColor = style.colors.placeholder, diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tooltip.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tooltip.kt index 2329b7fb9..718b77ec2 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tooltip.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Tooltip.kt @@ -39,32 +39,27 @@ public fun Tooltip( ) { TooltipArea( tooltip = { - CompositionLocalProvider( - LocalContentColor provides style.colors.content, - ) { + CompositionLocalProvider(LocalContentColor provides style.colors.content) { Box( modifier = - Modifier - .shadow( - elevation = style.metrics.shadowSize, - shape = RoundedCornerShape(style.metrics.cornerSize), - ambientColor = style.colors.shadow, - spotColor = Color.Transparent, - ) - .background( - color = style.colors.background, - shape = RoundedCornerShape(style.metrics.cornerSize), - ) - .border( - width = style.metrics.borderWidth, - color = style.colors.border, - shape = RoundedCornerShape(style.metrics.cornerSize), - ) - .padding(style.metrics.contentPadding), + Modifier.shadow( + elevation = style.metrics.shadowSize, + shape = RoundedCornerShape(style.metrics.cornerSize), + ambientColor = style.colors.shadow, + spotColor = Color.Transparent, + ) + .background( + color = style.colors.background, + shape = RoundedCornerShape(style.metrics.cornerSize), + ) + .border( + width = style.metrics.borderWidth, + color = style.colors.border, + shape = RoundedCornerShape(style.metrics.cornerSize), + ) + .padding(style.metrics.contentPadding) ) { - OverrideDarkMode(style.colors.background.isDark()) { - tooltip() - } + OverrideDarkMode(style.colors.background.isDark()) { tooltip() } } } }, @@ -76,9 +71,8 @@ public fun Tooltip( } /** - * [TooltipPlacement] implementation for providing a [PopupPositionProvider] that calculates - * the position of the popup relative to the current mouse cursor position, but never changes - * it after showing the popup. + * [TooltipPlacement] implementation for providing a [PopupPositionProvider] that calculates the position of the popup + * relative to the current mouse cursor position, but never changes it after showing the popup. * * @param offset [DpOffset] to be added to the position of the popup. * @param alignment The alignment of the popup relative to the current cursor position. @@ -101,8 +95,8 @@ public class FixedCursorPoint( } /** - * A [PopupPositionProvider] that positions the popup at the given position relative to the anchor, - * but never updates it after showing the popup. + * A [PopupPositionProvider] that positions the popup at the given position relative to the anchor, but never updates it + * after showing the popup. * * @param positionPx the offset, in pixels, relative to the anchor, to position the popup at. * @param offset [DpOffset] to be added to the position of the popup. diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Typography.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Typography.kt index ed0881fec..ef420d4ee 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Typography.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/Typography.kt @@ -10,73 +10,44 @@ import androidx.compose.ui.unit.sp import org.jetbrains.jewel.foundation.theme.JewelTheme /** - * A quick way to obtain text styles derived from - * [the default `TextStyle`][JewelTheme.defaultTextStyle]. These match + * A quick way to obtain text styles derived from [the default `TextStyle`][JewelTheme.defaultTextStyle]. These match * the functionality provided by `JBFont` in the IntelliJ Platform. */ public object Typography { - /** - * The text style to use for labels. Identical to - * [JewelTheme.defaultTextStyle]. - */ - @Composable - public fun labelTextStyle(): TextStyle = JewelTheme.defaultTextStyle + /** The text style to use for labels. Identical to [JewelTheme.defaultTextStyle]. */ + @Composable public fun labelTextStyle(): TextStyle = JewelTheme.defaultTextStyle - /** - * The text size to use for labels. Identical to the size set in - * [JewelTheme.defaultTextStyle]. - */ - @Composable - public fun labelTextSize(): TextUnit = JewelTheme.defaultTextStyle.fontSize + /** The text size to use for labels. Identical to the size set in [JewelTheme.defaultTextStyle]. */ + @Composable public fun labelTextSize(): TextUnit = JewelTheme.defaultTextStyle.fontSize - /** - * The text style to use for h0 titles. Derived from - * [JewelTheme.defaultTextStyle]. - */ + /** The text style to use for h0 titles. Derived from [JewelTheme.defaultTextStyle]. */ @Composable public fun h0TextStyle(): TextStyle = JewelTheme.defaultTextStyle.copy(fontSize = labelTextSize() + 12.sp, fontWeight = FontWeight.Bold) - /** - * The text style to use for h1 titles. Derived from - * [JewelTheme.defaultTextStyle]. - */ + /** The text style to use for h1 titles. Derived from [JewelTheme.defaultTextStyle]. */ @Composable public fun h1TextStyle(): TextStyle = JewelTheme.defaultTextStyle.copy(fontSize = labelTextSize() + 9.sp, fontWeight = FontWeight.Bold) - /** - * The text style to use for h2 titles. Derived from - * [JewelTheme.defaultTextStyle]. - */ + /** The text style to use for h2 titles. Derived from [JewelTheme.defaultTextStyle]. */ @Composable public fun h2TextStyle(): TextStyle = JewelTheme.defaultTextStyle.copy(fontSize = labelTextSize() + 5.sp) - /** - * The text style to use for h3 titles. Derived from - * [JewelTheme.defaultTextStyle]. - */ + /** The text style to use for h3 titles. Derived from [JewelTheme.defaultTextStyle]. */ @Composable public fun h3TextStyle(): TextStyle = JewelTheme.defaultTextStyle.copy(fontSize = labelTextSize() + 3.sp) - /** - * The text style to use for h4 titles. Derived from - * [JewelTheme.defaultTextStyle]. - */ + /** The text style to use for h4 titles. Derived from [JewelTheme.defaultTextStyle]. */ @Composable public fun h4TextStyle(): TextStyle = JewelTheme.defaultTextStyle.copy(fontSize = labelTextSize() + 1.sp, fontWeight = FontWeight.Bold) /** The text style used for code editors. Usually is a monospaced font. */ - @Composable - public fun editorTextStyle(): TextStyle = JewelTheme.editorTextStyle + @Composable public fun editorTextStyle(): TextStyle = JewelTheme.editorTextStyle - /** - * The text style used for code consoles. Usually is a monospaced font. Can - * be the same as [editorTextStyle]. - */ - @Composable - public fun consoleTextStyle(): TextStyle = JewelTheme.consoleTextStyle + /** The text style used for code consoles. Usually is a monospaced font. Can be the same as [editorTextStyle]. */ + @Composable public fun consoleTextStyle(): TextStyle = JewelTheme.consoleTextStyle } public operator fun TextUnit.plus(other: TextUnit): TextUnit = diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ButtonStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ButtonStyling.kt index b4f562e12..65901c04b 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ButtonStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ButtonStyling.kt @@ -57,7 +57,7 @@ public class ButtonColors( pressed = backgroundPressed, hovered = backgroundHovered, active = background, - ), + ) ) @Composable @@ -70,7 +70,7 @@ public class ButtonColors( pressed = contentPressed, hovered = contentHovered, active = content, - ), + ) ) @Composable @@ -93,7 +93,7 @@ public class ButtonColors( state.isHovered -> borderHovered else -> border } - }, + } ) public companion object @@ -111,12 +111,10 @@ public class ButtonMetrics( public companion object } -public val LocalDefaultButtonStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No default ButtonStyle provided. Have you forgotten the theme?") - } +public val LocalDefaultButtonStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No default ButtonStyle provided. Have you forgotten the theme?") +} -public val LocalOutlinedButtonStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No outlined ButtonStyle provided. Have you forgotten the theme?") - } +public val LocalOutlinedButtonStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No outlined ButtonStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CheckboxStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CheckboxStyling.kt index 3b09a416e..10ef2053f 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CheckboxStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CheckboxStyling.kt @@ -40,7 +40,7 @@ public class CheckboxColors( !state.isEnabled -> contentDisabled state.toggleableState == ToggleableState.On -> contentSelected else -> content - }, + } ) public companion object @@ -65,7 +65,6 @@ public class CheckboxIcons(public val checkbox: IconKey) { public companion object } -public val LocalCheckboxStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No CheckboxStyle provided. Have you forgotten the theme?") - } +public val LocalCheckboxStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No CheckboxStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ChipStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ChipStyling.kt index 3b98d13cc..bf65e2d0e 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ChipStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ChipStyling.kt @@ -18,10 +18,7 @@ import org.jetbrains.jewel.ui.component.ChipState @Stable @GenerateDataFunctions -public class ChipStyle( - public val colors: ChipColors, - public val metrics: ChipMetrics, -) { +public class ChipStyle(public val colors: ChipColors, public val metrics: ChipMetrics) { public companion object } @@ -78,7 +75,7 @@ public class ChipColors( state.isHovered -> backgroundHovered else -> background } - }, + } ) @Composable @@ -100,7 +97,7 @@ public class ChipColors( state.isHovered -> contentHovered else -> content } - }, + } ) @Composable @@ -122,7 +119,7 @@ public class ChipColors( state.isHovered && !JewelTheme.isSwingCompatMode -> borderHovered else -> border } - }, + } ) public companion object @@ -139,7 +136,6 @@ public class ChipMetrics( public companion object } -public val LocalChipStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No ChipStyle provided. Have you forgotten the theme?") - } +public val LocalChipStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No ChipStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CircularProgressStyle.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CircularProgressStyle.kt index 984348756..6f6d9caa1 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CircularProgressStyle.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/CircularProgressStyle.kt @@ -7,14 +7,10 @@ import androidx.compose.ui.graphics.Color import kotlin.time.Duration @Immutable -public class CircularProgressStyle( - public val frameTime: Duration, - public val color: Color, -) { +public class CircularProgressStyle(public val frameTime: Duration, public val color: Color) { public companion object } -public val LocalCircularProgressStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No CircularProgressStyle provided. Have you forgotten the theme?") - } +public val LocalCircularProgressStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No CircularProgressStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DividerStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DividerStyling.kt index d99dba268..19cd8b728 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DividerStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DividerStyling.kt @@ -10,28 +10,19 @@ import org.jetbrains.jewel.foundation.GenerateDataFunctions @Immutable @GenerateDataFunctions -public class DividerStyle( - public val color: Color, - public val metrics: DividerMetrics, -) { +public class DividerStyle(public val color: Color, public val metrics: DividerMetrics) { public companion object } @Immutable @GenerateDataFunctions -public class DividerMetrics( - public val thickness: Dp, - public val startIndent: Dp, -) { +public class DividerMetrics(public val thickness: Dp, public val startIndent: Dp) { public companion object { - public fun defaults( - thickness: Dp = 1.dp, - startIndent: Dp = 0.dp, - ): DividerMetrics = DividerMetrics(thickness, startIndent) + public fun defaults(thickness: Dp = 1.dp, startIndent: Dp = 0.dp): DividerMetrics = + DividerMetrics(thickness, startIndent) } } -public val LocalDividerStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No DividerStyle provided. Have you forgotten the theme?") - } +public val LocalDividerStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No DividerStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DropdownStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DropdownStyling.kt index 8b09d5252..639b5c996 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DropdownStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/DropdownStyling.kt @@ -61,7 +61,7 @@ public class DropdownColors( state.isFocused -> backgroundFocused state.isActive -> background else -> background - }, + } ) @Composable @@ -74,7 +74,7 @@ public class DropdownColors( pressed = contentPressed, hovered = contentHovered, active = content, - ), + ) ) @Composable @@ -87,7 +87,7 @@ public class DropdownColors( pressed = borderPressed, hovered = borderHovered, active = border, - ), + ) ) @Composable @@ -100,7 +100,7 @@ public class DropdownColors( pressed = iconTintPressed, hovered = iconTintHovered, active = iconTint, - ), + ) ) public companion object @@ -124,12 +124,10 @@ public class DropdownIcons(public val chevronDown: IconKey) { public companion object } -public val LocalDefaultDropdownStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No DefaultDropdownStyle provided. Have you forgotten the theme?") - } +public val LocalDefaultDropdownStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No DefaultDropdownStyle provided. Have you forgotten the theme?") +} -public val LocalUndecoratedDropdownStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No UndecoratedDropdownStyle provided. Have you forgotten the theme?") - } +public val LocalUndecoratedDropdownStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No UndecoratedDropdownStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/GroupHeaderStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/GroupHeaderStyling.kt index 671f77706..82d79d74b 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/GroupHeaderStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/GroupHeaderStyling.kt @@ -9,10 +9,7 @@ import org.jetbrains.jewel.foundation.GenerateDataFunctions @Immutable @GenerateDataFunctions -public class GroupHeaderStyle( - public val colors: GroupHeaderColors, - public val metrics: GroupHeaderMetrics, -) { +public class GroupHeaderStyle(public val colors: GroupHeaderColors, public val metrics: GroupHeaderMetrics) { public companion object } @@ -24,14 +21,10 @@ public class GroupHeaderColors(public val divider: Color) { @Immutable @GenerateDataFunctions -public class GroupHeaderMetrics( - public val dividerThickness: Dp, - public val indent: Dp, -) { +public class GroupHeaderMetrics(public val dividerThickness: Dp, public val indent: Dp) { public companion object } -public val LocalGroupHeaderStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No GroupHeaderStyle provided. Have you forgotten the theme?") - } +public val LocalGroupHeaderStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No GroupHeaderStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/HorizontalProgressBarStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/HorizontalProgressBarStyling.kt index 4e5e8d467..598a467ed 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/HorizontalProgressBarStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/HorizontalProgressBarStyling.kt @@ -6,8 +6,8 @@ import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp -import org.jetbrains.jewel.foundation.GenerateDataFunctions import kotlin.time.Duration +import org.jetbrains.jewel.foundation.GenerateDataFunctions @Immutable @GenerateDataFunctions diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/IconButtonStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/IconButtonStyling.kt index 8197e5810..d26bb0f52 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/IconButtonStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/IconButtonStyling.kt @@ -20,10 +20,7 @@ import org.jetbrains.jewel.ui.component.ToggleableIconButtonState @Stable @GenerateDataFunctions -public class IconButtonStyle( - public val colors: IconButtonColors, - public val metrics: IconButtonMetrics, -) { +public class IconButtonStyle(public val colors: IconButtonColors, public val metrics: IconButtonMetrics) { public companion object } @@ -55,7 +52,7 @@ public class IconButtonColors( state.isHovered -> backgroundHovered state.isFocused -> backgroundFocused else -> background - }, + } ) @Composable @@ -69,7 +66,7 @@ public class IconButtonColors( state.isHovered -> backgroundHovered state.isFocused -> backgroundFocused else -> background - }, + } ) @Composable @@ -83,7 +80,7 @@ public class IconButtonColors( state.isHovered -> backgroundHovered state.isFocused -> backgroundFocused else -> background - }, + } ) @Composable @@ -92,7 +89,7 @@ public class IconButtonColors( when { state.isActive && state.isSelected -> foregroundSelectedActivated else -> Color.Unspecified - }, + } ) @Composable @@ -101,7 +98,7 @@ public class IconButtonColors( when { state.isActive && state.toggleableState == ToggleableState.On -> foregroundSelectedActivated else -> Color.Unspecified - }, + } ) @Composable @@ -113,7 +110,7 @@ public class IconButtonColors( state.isPressed -> borderPressed state.isHovered -> borderHovered else -> border - }, + } ) @Composable @@ -127,7 +124,7 @@ public class IconButtonColors( state.isPressed -> borderPressed state.isHovered -> borderHovered else -> border - }, + } ) @Composable @@ -141,7 +138,7 @@ public class IconButtonColors( state.isPressed -> borderPressed state.isHovered -> borderHovered else -> border - }, + } ) public companion object @@ -158,7 +155,6 @@ public class IconButtonMetrics( public companion object } -public val LocalIconButtonStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No IconButtonStyle provided. Have you forgotten the theme?") - } +public val LocalIconButtonStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No IconButtonStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/InputFieldStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/InputFieldStyling.kt index 2f3593e5d..5287eb03f 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/InputFieldStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/InputFieldStyling.kt @@ -36,7 +36,7 @@ public interface InputFieldColors { pressed = backgroundPressed, hovered = backgroundHovered, active = background, - ), + ) ) public val content: Color @@ -55,7 +55,7 @@ public interface InputFieldColors { pressed = contentPressed, hovered = contentHovered, active = content, - ), + ) ) public val border: Color @@ -74,7 +74,7 @@ public interface InputFieldColors { pressed = borderPressed, hovered = borderHovered, active = border, - ), + ) ) public val caret: Color @@ -93,7 +93,7 @@ public interface InputFieldColors { pressed = caretPressed, hovered = caretHovered, active = caret, - ), + ) ) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LazyTreeStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LazyTreeStyling.kt index 3990ff0c9..c76574674 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LazyTreeStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LazyTreeStyling.kt @@ -44,7 +44,7 @@ public class LazyTreeColors( state.isFocused -> contentFocused state.isSelected -> contentSelected else -> content - }, + } ) public companion object @@ -72,10 +72,7 @@ public class LazyTreeIcons( public val chevronSelectedExpanded: IconKey, ) { @Composable - public fun chevron( - isExpanded: Boolean, - isSelected: Boolean, - ): IconKey = + public fun chevron(isExpanded: Boolean, isSelected: Boolean): IconKey = when { isSelected && isExpanded -> chevronSelectedExpanded isSelected && !isExpanded -> chevronSelectedCollapsed @@ -86,7 +83,6 @@ public class LazyTreeIcons( public companion object } -public val LocalLazyTreeStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No LazyTreeStyle provided. Have you forgotten the theme?") - } +public val LocalLazyTreeStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No LazyTreeStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LinkStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LinkStyling.kt index 893883f41..3e1c1251c 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LinkStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/LinkStyling.kt @@ -46,7 +46,7 @@ public class LinkColors( hovered = contentHovered, visited = contentVisited, active = content, - ), + ) ) public companion object @@ -64,18 +64,15 @@ public class LinkMetrics( @Immutable @GenerateDataFunctions -public class LinkIcons( - public val dropdownChevron: IconKey, - public val externalLink: IconKey, -) { +public class LinkIcons(public val dropdownChevron: IconKey, public val externalLink: IconKey) { public companion object } -public val LocalLinkStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No LinkStyle provided. Have you forgotten the theme?") - } +public val LocalLinkStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No LinkStyle provided. Have you forgotten the theme?") +} public enum class LinkUnderlineBehavior { - ShowAlways, ShowOnHover + ShowAlways, + ShowOnHover, } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/MenuStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/MenuStyling.kt index 98566b4ed..1ff2a8e18 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/MenuStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/MenuStyling.kt @@ -73,7 +73,7 @@ public class MenuItemColors( focused = backgroundFocused, pressed = backgroundPressed, hovered = backgroundHovered, - ), + ) ) @Composable @@ -86,7 +86,7 @@ public class MenuItemColors( pressed = contentPressed, hovered = contentHovered, active = content, - ), + ) ) @Composable @@ -99,7 +99,7 @@ public class MenuItemColors( pressed = iconTintPressed, hovered = iconTintHovered, active = iconTint, - ), + ) ) @Composable @@ -112,7 +112,7 @@ public class MenuItemColors( pressed = keybindingTintPressed, hovered = keybindingTintHovered, active = keybindingTint, - ), + ) ) public companion object @@ -161,7 +161,6 @@ public class MenuIcons(public val submenuChevron: IconKey) { public companion object } -public val LocalMenuStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No MenuStyle provided. Have you forgotten the theme?") - } +public val LocalMenuStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No MenuStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/RadioButtonStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/RadioButtonStyling.kt index b6eac76a0..291078f88 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/RadioButtonStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/RadioButtonStyling.kt @@ -43,7 +43,7 @@ public class RadioButtonColors( state.isSelected -> contentSelected state.isHovered -> contentHovered else -> content - }, + } ) public companion object @@ -51,10 +51,7 @@ public class RadioButtonColors( @Immutable @GenerateDataFunctions -public class RadioButtonMetrics( - public val radioButtonSize: DpSize, - public val iconContentGap: Dp, -) { +public class RadioButtonMetrics(public val radioButtonSize: DpSize, public val iconContentGap: Dp) { public companion object } @@ -65,7 +62,6 @@ public class RadioButtonIcons(public val radioButton: IconKey) { public companion object } -public val LocalRadioButtonStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No RadioButtonStyle provided. Have you forgotten the theme?") - } +public val LocalRadioButtonStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No RadioButtonStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ScrollbarStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ScrollbarStyling.kt index 75f66b643..561b4d6ed 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ScrollbarStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/ScrollbarStyling.kt @@ -8,9 +8,9 @@ import androidx.compose.runtime.Stable import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp -import org.jetbrains.jewel.foundation.GenerateDataFunctions import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds +import org.jetbrains.jewel.foundation.GenerateDataFunctions @Stable @GenerateDataFunctions @@ -44,10 +44,7 @@ public class ScrollbarColors( @Stable @GenerateDataFunctions -public class ScrollbarMetrics( - public val thumbCornerSize: CornerSize, - public val minThumbLength: Dp, -) { +public class ScrollbarMetrics(public val thumbCornerSize: CornerSize, public val minThumbLength: Dp) { public companion object } @@ -99,7 +96,6 @@ public enum class TrackClickBehavior { JumpToSpot, } -public val LocalScrollbarStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No ScrollbarStyle provided. Have you forgotten the theme?") - } +public val LocalScrollbarStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No ScrollbarStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SegmentedControlStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SegmentedControlStyling.kt index 046937422..20b5d7cdd 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SegmentedControlStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SegmentedControlStyling.kt @@ -52,10 +52,7 @@ public class SegmentedControlColors( @Stable @GenerateDataFunctions -public class SegmentedControlMetrics( - public val cornerSize: CornerSize, - public val borderWidth: Dp, -) { +public class SegmentedControlMetrics(public val cornerSize: CornerSize, public val borderWidth: Dp) { public companion object } @@ -76,7 +73,6 @@ private fun SegmentedControlState.chooseValueIgnoreCompat( else -> normal } -public val LocalSegmentedControlStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No LocalSegmentedControlStyle provided. Have you forgotten the theme?") - } +public val LocalSegmentedControlStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No LocalSegmentedControlStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SliderStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SliderStyling.kt index 2e8860365..6c3c598db 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SliderStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/SliderStyling.kt @@ -53,7 +53,7 @@ public class SliderColors( focused = thumbFillFocused, pressed = thumbFillPressed, hovered = thumbFillHovered, - ), + ) ) @Composable @@ -65,7 +65,7 @@ public class SliderColors( focused = thumbBorderFocused, pressed = thumbBorderPressed, hovered = thumbBorderHovered, - ), + ) ) @Composable @@ -75,13 +75,14 @@ public class SliderColors( pressed: Color, hovered: Color, focused: Color, - ) = when { - !isEnabled -> disabled - isFocused -> focused - isPressed && !JewelTheme.isSwingCompatMode -> pressed - isHovered && !JewelTheme.isSwingCompatMode -> hovered - else -> normal - } + ) = + when { + !isEnabled -> disabled + isFocused -> focused + isPressed && !JewelTheme.isSwingCompatMode -> pressed + isHovered && !JewelTheme.isSwingCompatMode -> hovered + else -> normal + } public companion object } @@ -99,7 +100,6 @@ public class SliderMetrics( public companion object } -public val LocalSliderStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No default SliderStyle provided. Have you forgotten the theme?") - } +public val LocalSliderStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No default SliderStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TabStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TabStyling.kt index b63e45354..e8ad1f9dc 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TabStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TabStyling.kt @@ -76,7 +76,7 @@ public class TabColors( hovered = contentHovered, active = content, ) - }, + } ) @Composable @@ -89,7 +89,7 @@ public class TabColors( state.isActive -> background state.isSelected -> backgroundSelected else -> background - }, + } ) @Composable @@ -105,7 +105,7 @@ public class TabColors( hovered = underlineHovered, active = underline, ) - }, + } ) public companion object @@ -138,7 +138,7 @@ public class TabContentAlpha( hovered = iconHovered, active = iconNormal, ) - }, + } ) @Composable @@ -154,7 +154,7 @@ public class TabContentAlpha( hovered = contentHovered, active = contentNormal, ) - }, + } ) public companion object @@ -162,13 +162,7 @@ public class TabContentAlpha( // Tabs are the only components that handle hover states @Composable -private fun TabState.chooseValueIgnoreCompat( - normal: T, - disabled: T, - pressed: T, - hovered: T, - active: T, -): T = +private fun TabState.chooseValueIgnoreCompat(normal: T, disabled: T, pressed: T, hovered: T, active: T): T = when { !isEnabled -> disabled isPressed -> pressed @@ -177,12 +171,10 @@ private fun TabState.chooseValueIgnoreCompat( else -> normal } -public val LocalDefaultTabStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No LocalDefaultTabStyle provided. Have you forgotten the theme?") - } +public val LocalDefaultTabStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No LocalDefaultTabStyle provided. Have you forgotten the theme?") +} -public val LocalEditorTabStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No LocalEditorTabStyle provided. Have you forgotten the theme?") - } +public val LocalEditorTabStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No LocalEditorTabStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextAreaStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextAreaStyling.kt index eb89bda16..d196e7222 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextAreaStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextAreaStyling.kt @@ -13,10 +13,8 @@ import org.jetbrains.jewel.foundation.GenerateDataFunctions @Stable @GenerateDataFunctions -public class TextAreaStyle( - override val colors: TextAreaColors, - override val metrics: TextAreaMetrics, -) : InputFieldStyle { +public class TextAreaStyle(override val colors: TextAreaColors, override val metrics: TextAreaMetrics) : + InputFieldStyle { public companion object } @@ -59,7 +57,6 @@ public class TextAreaMetrics( public companion object } -public val LocalTextAreaStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No TextAreaStyle provided. Have you forgotten the theme?") - } +public val LocalTextAreaStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No TextAreaStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextFieldStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextFieldStyling.kt index 1aaa804e7..1f2e6c8db 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextFieldStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TextFieldStyling.kt @@ -13,10 +13,8 @@ import org.jetbrains.jewel.foundation.GenerateDataFunctions @Stable @GenerateDataFunctions -public class TextFieldStyle( - override val colors: TextFieldColors, - override val metrics: TextFieldMetrics, -) : InputFieldStyle { +public class TextFieldStyle(override val colors: TextFieldColors, override val metrics: TextFieldMetrics) : + InputFieldStyle { public companion object } @@ -59,7 +57,6 @@ public class TextFieldMetrics( public companion object } -public val LocalTextFieldStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No TextFieldStyle provided. Have you forgotten the theme?") - } +public val LocalTextFieldStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No TextFieldStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TooltipStyling.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TooltipStyling.kt index 56a461256..a34619199 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TooltipStyling.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/component/styling/TooltipStyling.kt @@ -10,17 +10,14 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp -import org.jetbrains.jewel.foundation.GenerateDataFunctions -import org.jetbrains.jewel.ui.component.FixedCursorPoint import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds +import org.jetbrains.jewel.foundation.GenerateDataFunctions +import org.jetbrains.jewel.ui.component.FixedCursorPoint @Stable @GenerateDataFunctions -public class TooltipStyle( - public val colors: TooltipColors, - public val metrics: TooltipMetrics, -) { +public class TooltipStyle(public val colors: TooltipColors, public val metrics: TooltipMetrics) { public companion object } @@ -53,19 +50,10 @@ public class TooltipMetrics( borderWidth: Dp = 1.dp, shadowSize: Dp = 12.dp, placement: TooltipPlacement = FixedCursorPoint(DpOffset(4.dp, 24.dp)), - ): TooltipMetrics = - TooltipMetrics( - contentPadding, - showDelay, - cornerSize, - borderWidth, - shadowSize, - placement, - ) + ): TooltipMetrics = TooltipMetrics(contentPadding, showDelay, cornerSize, borderWidth, shadowSize, placement) } } -public val LocalTooltipStyle: ProvidableCompositionLocal = - staticCompositionLocalOf { - error("No TooltipStyle provided. Have you forgotten the theme?") - } +public val LocalTooltipStyle: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No TooltipStyle provided. Have you forgotten the theme?") +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/IconKey.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/IconKey.kt index 9e036b7ad..98167b5f6 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/IconKey.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/IconKey.kt @@ -9,10 +9,7 @@ public interface IconKey { } @GenerateDataFunctions -public class PathIconKey( - private val path: String, - override val iconClass: Class<*>, -) : IconKey { +public class PathIconKey(private val path: String, override val iconClass: Class<*>) : IconKey { override fun path(isNewUi: Boolean): String = path } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/NewUiChecker.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/NewUiChecker.kt index 7c08af81a..c260d05b3 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/NewUiChecker.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/icon/NewUiChecker.kt @@ -9,8 +9,9 @@ public fun interface NewUiChecker { public fun isNewUi(): Boolean } -public val LocalNewUiChecker: ProvidableCompositionLocal = - staticCompositionLocalOf { error("No NewUiChecker provided") } +public val LocalNewUiChecker: ProvidableCompositionLocal = staticCompositionLocalOf { + error("No NewUiChecker provided") +} public val JewelTheme.Companion.newUiChecker: NewUiChecker @Composable get() = LocalNewUiChecker.current diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/BadgePainter.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/BadgePainter.kt index e4cfb025d..29227e307 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/BadgePainter.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/BadgePainter.kt @@ -18,27 +18,19 @@ import org.jetbrains.jewel.ui.painter.badge.BadgeShape /** * Paints a badge over the [source]. * - * An area corresponding to the result of [BadgeShape.createHoleOutline] - * is cleared out first, to allow for visual separation with the badge,and - * then the [BadgeShape.createOutline] is filled with the [color]. + * An area corresponding to the result of [BadgeShape.createHoleOutline] is cleared out first, to allow for visual + * separation with the badge,and then the [BadgeShape.createOutline] is filled with the [color]. */ -public class BadgePainter( - private val source: Painter, - private val color: Color, - private val shape: BadgeShape, -) : DelegatePainter(source) { +public class BadgePainter(private val source: Painter, private val color: Color, private val shape: BadgeShape) : + DelegatePainter(source) { /** - * Optional [Paint] used to draw contents into an offscreen layer to - * apply alpha or [ColorFilter] parameters accordingly. If no alpha or - * [ColorFilter] is provided or the [Painter] implementation implements - * [applyAlpha] and [applyColorFilter] then this paint is not used. + * Optional [Paint] used to draw contents into an offscreen layer to apply alpha or [ColorFilter] parameters + * accordingly. If no alpha or [ColorFilter] is provided or the [Painter] implementation implements [applyAlpha] and + * [applyColorFilter] then this paint is not used. */ private var layerPaint: Paint? = null - /** - * Lazily create a [Paint] object or return the existing instance if it is - * already allocated. - */ + /** Lazily create a [Paint] object or return the existing instance if it is already allocated. */ private fun obtainPaint(): Paint { var target = layerPaint if (target == null) { diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/DelegatePainter.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/DelegatePainter.kt index 66dbff961..5b7f8d4d3 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/DelegatePainter.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/DelegatePainter.kt @@ -7,8 +7,8 @@ import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.unit.LayoutDirection /** - * A painter that delegates drawing to another [Painter], but can apply - * custom alphas, filters and layoutDirection to it. + * A painter that delegates drawing to another [Painter], but can apply custom alphas, filters and layoutDirection to + * it. */ public open class DelegatePainter(private val delegate: Painter) : Painter() { override val intrinsicSize: Size diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHint.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHint.kt index e69d250e7..12541b0c7 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHint.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHint.kt @@ -6,10 +6,9 @@ import org.w3c.dom.Element /** * A [PainterHint] is a hint for [PainterProvider] on how to load a - * [Painter][androidx.compose.ui.graphics.painter.Painter]. It can used to - * patch the path of the resource being loaded (e.g., for New UI icon path - * mapping, and handling the dark theme variants), replace colors in an SVG - * based on the theme palette, etc. + * [Painter][androidx.compose.ui.graphics.painter.Painter]. It can used to patch the path of the resource being loaded + * (e.g., for New UI icon path mapping, and handling the dark theme variants), replace colors in an SVG based on the + * theme palette, etc. * * Custom implementations are not allowed. There are two types of hints: * * [PainterPathHint] modifies the path of the resource to load @@ -22,9 +21,7 @@ import org.w3c.dom.Element public sealed interface PainterHint { public fun PainterProviderScope.canApply(): Boolean = true - /** - * An empty [PainterHint], it will be ignored. - */ + /** An empty [PainterHint], it will be ignored. */ public companion object None : PainterHint { override fun PainterProviderScope.canApply(): Boolean = false @@ -32,38 +29,32 @@ public sealed interface PainterHint { } } -/** - * Mark this [PainterHint] just available with SVG images. - */ +/** Mark this [PainterHint] just available with SVG images. */ @Immutable public interface SvgPainterHint : PainterHint { override fun PainterProviderScope.canApply(): Boolean = path.substringAfterLast('.').lowercase() == "svg" } -/** - * Mark this [PainterHint] just available with Bitmap images. - */ +/** Mark this [PainterHint] just available with Bitmap images. */ @Immutable public interface BitmapPainterHint : PainterHint { override fun PainterProviderScope.canApply(): Boolean = when (path.substringAfterLast('.').lowercase()) { - "svg", "xml" -> false + "svg", + "xml" -> false else -> true } } -/** - * Mark this [PainterHint] just available with XML images. - */ +/** Mark this [PainterHint] just available with XML images. */ @Immutable public interface XmlPainterHint : PainterHint { override fun PainterProviderScope.canApply(): Boolean = path.substringAfterLast('.').lowercase() == "xml" } /** - * A [PainterHint] that modifies the path of the resource being loaded. - * Usage examples are applying the New UI icon mappings, or picking up dark - * theme variants of icons. + * A [PainterHint] that modifies the path of the resource being loaded. Usage examples are applying the New UI icon + * mappings, or picking up dark theme variants of icons. */ @Immutable public interface PainterPathHint : PainterHint { @@ -72,14 +63,12 @@ public interface PainterPathHint : PainterHint { } /** - * A [PainterHint] that patches the content of SVG resources. It is only - * applied to SVG resources; it doesn't affect other types of resources. + * A [PainterHint] that patches the content of SVG resources. It is only applied to SVG resources; it doesn't affect + * other types of resources. */ @Immutable public interface PainterSvgPatchHint : SvgPainterHint { - /** - * Patch the SVG content. - */ + /** Patch the SVG content. */ public fun PainterProviderScope.patch(element: Element) } @@ -89,45 +78,40 @@ public interface PainterWrapperHint : PainterHint { } /** - * A [PainterHint] that adds a prefix to a resource file name, without - * changing the rest of the path. For example, if the original path is - * `icons/MyIcon.svg`, and the prefix is `Dark`, the patched path will be - * `icons/DarkMyIcon.svg`. + * A [PainterHint] that adds a prefix to a resource file name, without changing the rest of the path. For example, if + * the original path is `icons/MyIcon.svg`, and the prefix is `Dark`, the patched path will be `icons/DarkMyIcon.svg`. */ @Immutable public abstract class PainterPrefixHint : PainterPathHint { - override fun PainterProviderScope.patch(): String = - buildString { - append(path.substringBeforeLast('/', "")) - append('/') - append(prefix()) - append(path.substringBeforeLast('.').substringAfterLast('/')) - - append('.') - append(path.substringAfterLast('.')) - } + override fun PainterProviderScope.patch(): String = buildString { + append(path.substringBeforeLast('/', "")) + append('/') + append(prefix()) + append(path.substringBeforeLast('.').substringAfterLast('/')) + + append('.') + append(path.substringAfterLast('.')) + } public abstract fun PainterProviderScope.prefix(): String } /** - * A [PainterHint] that adds a suffix to a resource file name, without - * changing the rest of the path nor the extension. For example, if the - * original path is `icons/MyIcon.svg`, and the suffix is `_dark`, the - * patched path will be `icons/MyIcon_dark.svg`. + * A [PainterHint] that adds a suffix to a resource file name, without changing the rest of the path nor the extension. + * For example, if the original path is `icons/MyIcon.svg`, and the suffix is `_dark`, the patched path will be + * `icons/MyIcon_dark.svg`. */ @Immutable public abstract class PainterSuffixHint : PainterPathHint { - override fun PainterProviderScope.patch(): String = - buildString { - append(path.substringBeforeLast('/', "")) - append('/') - append(path.substringBeforeLast('.').substringAfterLast('/')) - append(suffix()) - - append('.') - append(path.substringAfterLast('.')) - } + override fun PainterProviderScope.patch(): String = buildString { + append(path.substringBeforeLast('/', "")) + append('/') + append(path.substringBeforeLast('.').substringAfterLast('/')) + append(suffix()) + + append('.') + append(path.substringAfterLast('.')) + } public abstract fun PainterProviderScope.suffix(): String } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHintsProvider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHintsProvider.kt index ed79713a1..067aacba9 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHintsProvider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterHintsProvider.kt @@ -18,29 +18,24 @@ import org.jetbrains.jewel.ui.painter.hints.HiDpi @Immutable public interface PainterHintsProvider { /** - * These hints will be consumed before the hints which are passed as a - * parameter to [PainterProvider.getPainter]. + * These hints will be consumed before the hints which are passed as a parameter to [PainterProvider.getPainter]. */ @Composable public fun priorityHints(path: String): List = emptyList() - /** - * These hints will be consumed after the hints which are passed as a - * parameter to [PainterProvider.getPainter]. - */ + /** These hints will be consumed after the hints which are passed as a parameter to [PainterProvider.getPainter]. */ @Composable public fun hints(path: String): List } /** * The default [PainterHintsProvider] to load dark theme icon variants. * - * It will provide the [Dark] hint when - * [LocalIsDarkTheme][org.jetbrains.jewel.foundation.theme.LocalIsDarkTheme] - * is true. + * It will provide the [Dark] hint when [LocalIsDarkTheme][org.jetbrains.jewel.foundation.theme.LocalIsDarkTheme] is + * true. */ public object CommonPainterHintsProvider : PainterHintsProvider { - @Composable - override fun hints(path: String): List = listOf(HiDpi(), Dark(JewelTheme.isDark)) + @Composable override fun hints(path: String): List = listOf(HiDpi(), Dark(JewelTheme.isDark)) } -public val LocalPainterHintsProvider: ProvidableCompositionLocal = - staticCompositionLocalOf { CommonPainterHintsProvider } +public val LocalPainterHintsProvider: ProvidableCompositionLocal = staticCompositionLocalOf { + CommonPainterHintsProvider +} diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterProvider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterProvider.kt index 83acf7cc6..cfec80a37 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterProvider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PainterProvider.kt @@ -5,23 +5,18 @@ import androidx.compose.runtime.State import androidx.compose.ui.graphics.painter.Painter /** - * Provides a [Painter] for an image, which may be transformed by the - * provided hints. + * Provides a [Painter] for an image, which may be transformed by the provided hints. * - * Note: implementations of this interface should handle the - * passed [PainterHint]s correctly. For now, this means calling - * [PainterPathHint.patch] and [PainterSvgPatchHint.patch]. Most likely, a - * [PainterProvider] should also hold the resource path and [ClassLoader] - * references. + * Note: implementations of this interface should handle the passed [PainterHint]s correctly. For now, this means + * calling [PainterPathHint.patch] and [PainterSvgPatchHint.patch]. Most likely, a [PainterProvider] should also hold + * the resource path and [ClassLoader] references. */ public interface PainterProvider { /** - * Provides a [Painter] using the specified [PainterHint]s. The painters - * are [remember][androidx.compose.runtime.remember]ed and this function - * can be called multiple times for the same data. + * Provides a [Painter] using the specified [PainterHint]s. The painters are + * [remember][androidx.compose.runtime.remember]ed and this function can be called multiple times for the same data. * - * Depending on the implementation, errors may be suppressed and a - * replacement painter provided. + * Depending on the implementation, errors may be suppressed and a replacement painter provided. */ @Composable public fun getPainter(vararg hints: PainterHint): State } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PalettePainterHintsProvider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PalettePainterHintsProvider.kt index fc8c1b0b1..4ccd3e6d8 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PalettePainterHintsProvider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/PalettePainterHintsProvider.kt @@ -21,11 +21,7 @@ public abstract class PalettePainterHintsProvider( } // See com.intellij.ide.ui.UITheme.toColorString - protected fun resolveKeyColor( - key: String, - keyPalette: Map, - isDark: Boolean, - ): Color? { + protected fun resolveKeyColor(key: String, keyPalette: Map, isDark: Boolean): Color? { val darkKey = "$key.Dark" val resolvedKey = if (isDark && keyPalette.containsKey(darkKey)) darkKey else key return Color.fromRGBAHexStringOrNull(keyPalette[resolvedKey] ?: return null) @@ -45,15 +41,14 @@ public abstract class PalettePainterHintsProvider( } /** - * Returns a [PainterHint] that can be used to patch colors for a resource - * with a given [path]. + * Returns a [PainterHint] that can be used to patch colors for a resource with a given [path]. * - * The implementations vary depending on the path, and when running on the - * IntelliJ Platform, also on the IDE version and the current theme (New UI - * vs Classic UI). + * The implementations vary depending on the path, and when running on the IntelliJ Platform, also on the IDE + * version and the current theme (New UI vs Classic UI). */ protected fun getPaletteHint(path: String): PainterHint { - if (!path.contains("com/intellij/ide/ui/laf/icons/") && !path.contains("themes/expUI/icons/dark/")) return uiPaletteHint + if (!path.contains("com/intellij/ide/ui/laf/icons/") && !path.contains("themes/expUI/icons/dark/")) + return uiPaletteHint val file = path.substringAfterLast('/') // ⚠️ This next line is not a copy-paste error — the code in diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/ResourcePainterProvider.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/ResourcePainterProvider.kt index de9ee7cc6..e72acaba0 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/ResourcePainterProvider.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/ResourcePainterProvider.kt @@ -14,11 +14,6 @@ import androidx.compose.ui.res.loadImageBitmap import androidx.compose.ui.res.loadSvgPainter import androidx.compose.ui.res.loadXmlImageVector import androidx.compose.ui.unit.Density -import org.jetbrains.jewel.foundation.util.myLogger -import org.jetbrains.jewel.ui.icon.IconKey -import org.jetbrains.jewel.ui.icon.LocalNewUiChecker -import org.w3c.dom.Document -import org.xml.sax.InputSource import java.io.IOException import java.io.InputStream import java.io.StringWriter @@ -32,23 +27,23 @@ import javax.xml.transform.TransformerException import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult +import org.jetbrains.jewel.foundation.util.myLogger +import org.jetbrains.jewel.ui.icon.IconKey +import org.jetbrains.jewel.ui.icon.LocalNewUiChecker +import org.w3c.dom.Document +import org.xml.sax.InputSource private val errorPainter = ColorPainter(Color.Magenta) /** - * Provide [Painter] by resources in the module and jars, it use the - * ResourceResolver to load resources. + * Provide [Painter] by resources in the module and jars, it use the ResourceResolver to load resources. * - * It will cache the painter by [PainterHint]s, so it is safe to call - * [getPainter] multiple times. + * It will cache the painter by [PainterHint]s, so it is safe to call [getPainter] multiple times. * - * If a resource fails to load, it will be silently replaced by a - * magenta color painter, and the exception logged as error. + * If a resource fails to load, it will be silently replaced by a magenta color painter, and the exception logged as + * error. */ -public class ResourcePainterProvider( - private val basePath: String, - vararg classLoaders: ClassLoader, -) : PainterProvider { +public class ResourcePainterProvider(private val basePath: String, vararg classLoaders: ClassLoader) : PainterProvider { private val logger = myLogger() private val classLoaders = classLoaders.toSet() @@ -58,9 +53,7 @@ public class ResourcePainterProvider( private val contextClassLoaders = classLoaders.toList() private val documentBuilderFactory = - DocumentBuilderFactory.newDefaultInstance().apply { - setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) - } + DocumentBuilderFactory.newDefaultInstance().apply { setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) } private fun Scope.resolveHint(hint: PainterHint) { with(hint) { @@ -76,15 +69,11 @@ public class ResourcePainterProvider( val scope = Scope(density, basePath, classLoaders) val currentHintsProvider = LocalPainterHintsProvider.current - currentHintsProvider - .priorityHints(basePath) - .forEach { scope.resolveHint(it) } + currentHintsProvider.priorityHints(basePath).forEach { scope.resolveHint(it) } hints.forEach { scope.resolveHint(it) } - currentHintsProvider - .hints(basePath) - .forEach { scope.resolveHint(it) } + currentHintsProvider.hints(basePath).forEach { scope.resolveHint(it) } val cacheKey = scope.acceptedHints.hashCode() * 31 + LocalDensity.current.hashCode() @@ -149,10 +138,7 @@ public class ResourcePainterProvider( } @Composable - private fun createSvgPainter( - scope: Scope, - url: URL, - ): Painter = + private fun createSvgPainter(scope: Scope, url: URL): Painter = tryLoadingResource( url = url, loadingAction = { resourceUrl -> @@ -164,11 +150,7 @@ public class ResourcePainterProvider( paintAction = { it }, ) - private fun patchSvg( - scope: Scope, - inputStream: InputStream, - hints: List, - ): InputStream { + private fun patchSvg(scope: Scope, inputStream: InputStream, hints: List): InputStream { if (hints.all { it !is PainterSvgPatchHint }) { return inputStream } @@ -190,10 +172,7 @@ public class ResourcePainterProvider( } @Composable - private fun createVectorDrawablePainter( - scope: Scope, - url: URL, - ): Painter = + private fun createVectorDrawablePainter(scope: Scope, url: URL): Painter = tryLoadingResource( url = url, loadingAction = { resourceUrl -> @@ -238,8 +217,7 @@ public class ResourcePainterProvider( override val classLoaders: Set, override val path: String = rawPath, override val acceptedHints: MutableList = mutableListOf(), - ) : ResourcePainterProviderScope, - Density by localDensity { + ) : ResourcePainterProviderScope, Density by localDensity { fun apply(pathHint: PainterPathHint): Scope? { with(pathHint) { val patched = patch() @@ -283,15 +261,10 @@ public fun rememberResourcePainterProvider( ): PainterProvider { val isNewUi = LocalNewUiChecker.current.isNewUi() return remember(iconKey, iconClass.classLoader, isNewUi) { - ResourcePainterProvider( - iconKey.path(isNewUi), - iconClass.classLoader, - ) + ResourcePainterProvider(iconKey.path(isNewUi), iconClass.classLoader) } } @Composable -public fun rememberResourcePainterProvider( - path: String, - iconClass: Class<*>, -): PainterProvider = remember(path, iconClass.classLoader) { ResourcePainterProvider(path, iconClass.classLoader) } +public fun rememberResourcePainterProvider(path: String, iconClass: Class<*>): PainterProvider = + remember(path, iconClass.classLoader) { ResourcePainterProvider(path, iconClass.classLoader) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/BadgeShape.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/BadgeShape.kt index 49dba8e13..6e6906aad 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/BadgeShape.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/BadgeShape.kt @@ -9,23 +9,16 @@ import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection /** - * A shape used to draw badges. Badge shapes have a clear area surrounding - * them, whose outline is determined by [createHoleOutline]. + * A shape used to draw badges. Badge shapes have a clear area surrounding them, whose outline is determined by + * [createHoleOutline]. * * @see org.jetbrains.jewel.ui.painter.hints.Badge * @see org.jetbrains.jewel.ui.painter.BadgePainter */ @Immutable public interface BadgeShape : Shape { - /** - * Create the outline of the clear area (or "hole") surrounding this badge - * shape. - */ - public fun createHoleOutline( - size: Size, - layoutDirection: LayoutDirection, - density: Density, - ): Outline + /** Create the outline of the clear area (or "hole") surrounding this badge shape. */ + public fun createHoleOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline } internal val emptyOutline = Outline.Rectangle(Rect.Zero) diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/DotBadgeShape.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/DotBadgeShape.kt index 7f8ecb85b..8995a46a4 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/DotBadgeShape.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/badge/DotBadgeShape.kt @@ -9,9 +9,7 @@ import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import org.jetbrains.jewel.foundation.GenerateDataFunctions -/** - * @see com.intellij.ui.BadgeDotProvider - */ +/** @see com.intellij.ui.BadgeDotProvider */ @Immutable @GenerateDataFunctions public class DotBadgeShape( @@ -20,22 +18,13 @@ public class DotBadgeShape( public val radius: Float = 3.5f / 20, public val border: Float = 1.5f / 20, ) : BadgeShape { - override fun createHoleOutline( - size: Size, - layoutDirection: LayoutDirection, - density: Density, - ): Outline = createOutline(size, hole = true) + override fun createHoleOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline = + createOutline(size, hole = true) - override fun createOutline( - size: Size, - layoutDirection: LayoutDirection, - density: Density, - ): Outline = createOutline(size, hole = false) + override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline = + createOutline(size, hole = false) - private fun createOutline( - size: Size, - hole: Boolean, - ): Outline { + private fun createOutline(size: Size, hole: Boolean): Outline { val dotSize = size.width.coerceAtMost(size.height) if (dotSize <= 0) return emptyOutline @@ -58,13 +47,7 @@ public class DotBadgeShape( val r = radius + border.coerceAtLeast(0.0f) return Outline.Rounded( - RoundRect( - left = x - r, - top = y - r, - right = x + r, - bottom = y + r, - cornerRadius = CornerRadius(r), - ), + RoundRect(left = x - r, top = y - r, right = x + r, bottom = y + r, cornerRadius = CornerRadius(r)) ) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Badge.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Badge.kt index b28c428ec..6afc4e060 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Badge.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Badge.kt @@ -12,16 +12,11 @@ import org.jetbrains.jewel.ui.painter.badge.BadgeShape import org.jetbrains.jewel.ui.painter.badge.DotBadgeShape @GenerateDataFunctions -private class BadgeImpl( - private val color: Color, - private val shape: BadgeShape, -) : PainterWrapperHint { +private class BadgeImpl(private val color: Color, private val shape: BadgeShape) : PainterWrapperHint { override fun PainterProviderScope.wrap(painter: Painter): Painter = BadgePainter(painter, color, shape) } /** Adds a colored badge to the image being loaded. */ @Suppress("FunctionName") -public fun Badge( - color: Color, - shape: BadgeShape = DotBadgeShape.Default, -): PainterHint = if (color.isSpecified) BadgeImpl(color, shape) else PainterHint.None +public fun Badge(color: Color, shape: BadgeShape = DotBadgeShape.Default): PainterHint = + if (color.isSpecified) BadgeImpl(color, shape) else PainterHint.None diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/ColorBasedPaletteReplacement.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/ColorBasedPaletteReplacement.kt index 7559bac4e..6656968ba 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/ColorBasedPaletteReplacement.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/ColorBasedPaletteReplacement.kt @@ -2,13 +2,13 @@ package org.jetbrains.jewel.ui.painter.hints import androidx.compose.runtime.Immutable import androidx.compose.ui.graphics.Color +import kotlin.math.roundToInt import org.jetbrains.jewel.foundation.GenerateDataFunctions import org.jetbrains.jewel.ui.painter.PainterHint import org.jetbrains.jewel.ui.painter.PainterProviderScope import org.jetbrains.jewel.ui.painter.PainterSvgPatchHint import org.jetbrains.jewel.ui.util.toRgbaHexString import org.w3c.dom.Element -import kotlin.math.roundToInt @Immutable @GenerateDataFunctions @@ -18,10 +18,7 @@ private class ColorBasedReplacementPainterSvgPatchHint(val map: Map, - stroke: Map = fill, -) { +internal fun Element.patchPalette(fill: Map, stroke: Map = fill) { patchColorAttribute("fill", fill) patchColorAttribute("stroke", stroke) @@ -35,10 +32,7 @@ internal fun Element.patchPalette( } } -private fun Element.patchColorAttribute( - attrName: String, - pattern: Map, -) { +private fun Element.patchColorAttribute(attrName: String, pattern: Map) { val color = getAttribute(attrName) val opacity = getAttribute("$attrName-opacity") @@ -53,10 +47,7 @@ private fun Element.patchColorAttribute( } } -private fun tryParseColor( - color: String, - alpha: Float, -): Color? { +private fun tryParseColor(color: String, alpha: Float): Color? { val rawColor = color.lowercase() if (rawColor.startsWith("#") && rawColor.length - 1 <= 8) { return fromHexOrNull(rawColor, alpha) @@ -64,10 +55,7 @@ private fun tryParseColor( return null } -private fun fromHexOrNull( - rawColor: String, - alpha: Float, -): Color? { +private fun fromHexOrNull(rawColor: String, alpha: Float): Color? { val startPos = if (rawColor.startsWith("#")) { 1 @@ -117,9 +105,8 @@ private fun fromHexOrNull( } /** - * Creates a PainterHint that replaces all colors in the [paletteMap] with - * their corresponding new value. It is used in IJ up to 23.3 to support - * patching the SVG colors for checkboxes and radio buttons. + * Creates a PainterHint that replaces all colors in the [paletteMap] with their corresponding new value. It is used in + * IJ up to 23.3 to support patching the SVG colors for checkboxes and radio buttons. */ @Suppress("FunctionName") public fun ColorBasedPaletteReplacement(paletteMap: Map): PainterHint = diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/DarkAndStroke.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/DarkAndStroke.kt index 54ef5703f..9699d196b 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/DarkAndStroke.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/DarkAndStroke.kt @@ -75,23 +75,19 @@ private class StrokeImpl(private val color: Color) : PainterSuffixHint(), Painte override fun hashCode(): Int = color.hashCode() } -/** - * Transforms an SVG image to only draw its borders in the provided - * [color]. All fills are removed. - */ +/** Transforms an SVG image to only draw its borders in the provided [color]. All fills are removed. */ @Suppress("FunctionName") public fun Stroke(color: Color): PainterHint = if (color.isSpecified) StrokeImpl(color) else PainterHint.None /** - * Switches between the light and dark variants of an image based on - * [isDark]. If no dark image exists, the light image will be used. + * Switches between the light and dark variants of an image based on [isDark]. If no dark image exists, the light image + * will be used. * * All images that aren't dark images are base, or light, images. * - * Dark images must be named in exactly the same way as the corresponding - * light image, but add a `_dark` suffix right before the extension. Dark - * images must be placed in the same directory and have the same extension - * as their light counterparts. + * Dark images must be named in exactly the same way as the corresponding light image, but add a `_dark` suffix right + * before the extension. Dark images must be placed in the same directory and have the same extension as their light + * counterparts. * * Examples: * diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/HiDpi.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/HiDpi.kt index 4dc676620..ac08f9c7d 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/HiDpi.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/HiDpi.kt @@ -15,15 +15,13 @@ private object HiDpiImpl : PainterSuffixHint() { } /** - * Selects the `@2x` HiDPI variant for bitmap images when running on a - * HiDPI screen. + * Selects the `@2x` HiDPI variant for bitmap images when running on a HiDPI screen. * * If an image does not have a HiDPI variant, the base image will be used. * - * Note that combining a [Size] with [HiDpi] could lead to unexpected - * results and is not supported as of now. Generally speaking, however, the - * IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] - * for PNGs, even though both are in theory supported for all formats. + * Note that combining a [Size] with [HiDpi] could lead to unexpected results and is not supported as of now. Generally + * speaking, however, the IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] for PNGs, even though + * both are in theory supported for all formats. * * | Base image name | HiDPI image name | * |-----------------|------------------| @@ -32,5 +30,4 @@ private object HiDpiImpl : PainterSuffixHint() { * * @see Size */ -@Suppress("FunctionName") -public fun HiDpi(): PainterHint = HiDpiImpl +@Suppress("FunctionName") public fun HiDpi(): PainterHint = HiDpiImpl diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/PathOverride.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/PathOverride.kt index dc1863326..9d0f7b6f1 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/PathOverride.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/PathOverride.kt @@ -15,13 +15,12 @@ private class PathOverrideImpl(private val overrides: Map) : Pai } /** - * A [PainterPathHint] that will override the paths passed as keys in the - * [overrides] map with the corresponding map values. + * A [PainterPathHint] that will override the paths passed as keys in the [overrides] map with the corresponding map + * values. * * This is used, for example, to implement the - * [New UI Icon Mapping](https://plugins.jetbrains.com/docs/intellij/icons.html#mapping-entries) - * when running in standalone mode. In the IntelliJ Platform, this logic is - * delegated to the platform by + * [New UI Icon Mapping](https://plugins.jetbrains.com/docs/intellij/icons.html#mapping-entries) when running in + * standalone mode. In the IntelliJ Platform, this logic is delegated to the platform by * [org.jetbrains.jewel.bridge.BridgeOverride]. */ @Suppress("FunctionName") diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Selected.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Selected.kt index 6e7f75cd1..c6e529717 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Selected.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Selected.kt @@ -14,9 +14,8 @@ private object SelectedImpl : PainterSuffixHint() { } /** - * Selects the "selected" variant of an image when [selected] is true. If - * an image does not have a selected variant, the base version will be - * used. + * Selects the "selected" variant of an image when [selected] is true. If an image does not have a selected variant, the + * base version will be used. * * | Base image name | Selected image name | * |-----------------------|-------------------------------| @@ -27,5 +26,4 @@ private object SelectedImpl : PainterSuffixHint() { @Suppress("FunctionName") public fun Selected(selected: Boolean = true): PainterHint = if (selected) SelectedImpl else PainterHint.None -@Suppress("FunctionName") -public fun Selected(state: SelectableComponentState): PainterHint = Selected(state.isSelected) +@Suppress("FunctionName") public fun Selected(state: SelectableComponentState): PainterHint = Selected(state.isSelected) diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Size.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Size.kt index 9a76ab906..72eb320e6 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Size.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Size.kt @@ -13,36 +13,29 @@ import org.jetbrains.jewel.ui.painter.SvgPainterHint @Immutable @GenerateDataFunctions -private class SizeImpl( - private val width: Int, - private val height: Int, -) : PainterSuffixHint(), PainterWrapperHint, SvgPainterHint { - override fun PainterProviderScope.suffix(): String = - buildString { - append("@") - append(width) - append("x") - append(height) - } +private class SizeImpl(private val width: Int, private val height: Int) : + PainterSuffixHint(), PainterWrapperHint, SvgPainterHint { + override fun PainterProviderScope.suffix(): String = buildString { + append("@") + append(width) + append("x") + append(height) + } override fun PainterProviderScope.wrap(painter: Painter): Painter { if (path.contains(suffix())) return painter - return ResizedPainter( - painter, - androidx.compose.ui.geometry.Size(width.dp.toPx(), height.dp.toPx()), - ) + return ResizedPainter(painter, androidx.compose.ui.geometry.Size(width.dp.toPx(), height.dp.toPx())) } } /** - * Selects a size variant for the image. If the specific size that was - * requested is not available, the base image will be used. + * Selects a size variant for the image. If the specific size that was requested is not available, the base image will + * be used. * - * Note that combining a [Size] with [HiDpi] could lead to unexpected - * results and is not supported as of now. Generally speaking, however, the - * IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] - * for PNGs, even though both are in theory supported for all formats. + * Note that combining a [Size] with [HiDpi] could lead to unexpected results and is not supported as of now. Generally + * speaking, however, the IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] for PNGs, even though + * both are in theory supported for all formats. * * | Base image name | Sized image name | * |--------------------|--------------------------| @@ -58,13 +51,12 @@ public fun Size(size: Int): PainterHint { } /** - * Selects a size variant for the image. If the specific size that was - * requested is not available, the base image will be used. + * Selects a size variant for the image. If the specific size that was requested is not available, the base image will + * be used. * - * Note that combining a [Size] with [HiDpi] could lead to unexpected - * results and is not supported as of now. Generally speaking, however, the - * IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] - * for PNGs, even though both are in theory supported for all formats. + * Note that combining a [Size] with [HiDpi] could lead to unexpected results and is not supported as of now. Generally + * speaking, however, the IntelliJ Platform tends to use only [Size] for SVGs and only [HiDpi] for PNGs, even though + * both are in theory supported for all formats. * * | Base image name | Sized image name | * |--------------------|--------------------------| @@ -74,10 +66,7 @@ public fun Size(size: Int): PainterHint { * @see HiDpi */ @Suppress("FunctionName") -public fun Size( - width: Int, - height: Int, -): PainterHint { +public fun Size(width: Int, height: Int): PainterHint { require(width > 0 && height > 0) { "Width and height must be positive" } return SizeImpl(width, height) } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Stateful.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Stateful.kt index f62d65098..c3fff73a3 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Stateful.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/painter/hints/Stateful.kt @@ -11,29 +11,25 @@ import org.jetbrains.jewel.ui.painter.PainterSuffixHint @Immutable @GenerateDataFunctions private class StatefulImpl(private val state: InteractiveComponentState) : PainterSuffixHint() { - override fun PainterProviderScope.suffix(): String = - buildString { - if (state.isEnabled) { - when { - state is FocusableComponentState && state.isFocused -> append("Focused") - state.isPressed -> append("Pressed") - state.isHovered -> append("Hovered") - } - } else { - append("Disabled") + override fun PainterProviderScope.suffix(): String = buildString { + if (state.isEnabled) { + when { + state is FocusableComponentState && state.isFocused -> append("Focused") + state.isPressed -> append("Pressed") + state.isHovered -> append("Hovered") } + } else { + append("Disabled") } + } } /** - * Selects a stateful variant of an image, based on the current [state]. - * Stateful variants are `Focused`, `Pressed`, `Hovered`, and `Disabled`. - * If an image does not have the required stateful variant, the base one - * will be used. + * Selects a stateful variant of an image, based on the current [state]. Stateful variants are `Focused`, `Pressed`, + * `Hovered`, and `Disabled`. If an image does not have the required stateful variant, the base one will be used. * - * If the [state] is a [FocusableComponentState] and its - * [`isFocused`][FocusableComponentState.isFocused] property - * is true, then the `Focused` variant will be used. + * If the [state] is a [FocusableComponentState] and its [`isFocused`][FocusableComponentState.isFocused] property is + * true, then the `Focused` variant will be used. * * For the base image name `myIcon.svg`, for example: * @@ -45,10 +41,7 @@ private class StatefulImpl(private val state: InteractiveComponentState) : Paint * | Enabled, hovered | `myIconHovered.svg` | * | Enabled, at rest | `myIcon.svg` | * - * Note that the - * [Swing Compat mode][org.jetbrains.jewel.foundation.theme.JewelTheme.isSwingCompatMode] - * value might prevent the selection of the pressed and hovered states, - * when true. + * Note that the [Swing Compat mode][org.jetbrains.jewel.foundation.theme.JewelTheme.isSwingCompatMode] value might + * prevent the selection of the pressed and hovered states, when true. */ -@Suppress("FunctionName") -public fun Stateful(state: InteractiveComponentState): PainterHint = StatefulImpl(state) +@Suppress("FunctionName") public fun Stateful(state: InteractiveComponentState): PainterHint = StatefulImpl(state) diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/theme/JewelTheme.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/theme/JewelTheme.kt index 348211866..f89873ec2 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/theme/JewelTheme.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/theme/JewelTheme.kt @@ -56,140 +56,86 @@ import org.jetbrains.jewel.ui.component.styling.TextFieldStyle import org.jetbrains.jewel.ui.component.styling.TooltipStyle public val JewelTheme.Companion.colorPalette: ThemeColorPalette - @Composable - @ReadOnlyComposable - get() = LocalColorPalette.current + @Composable @ReadOnlyComposable get() = LocalColorPalette.current public val JewelTheme.Companion.iconData: ThemeIconData - @Composable - @ReadOnlyComposable - get() = LocalIconData.current + @Composable @ReadOnlyComposable get() = LocalIconData.current // ----------------- // Component styling // ----------------- public val JewelTheme.Companion.defaultButtonStyle: ButtonStyle - @Composable - @ReadOnlyComposable - get() = LocalDefaultButtonStyle.current + @Composable @ReadOnlyComposable get() = LocalDefaultButtonStyle.current public val JewelTheme.Companion.outlinedButtonStyle: ButtonStyle - @Composable - @ReadOnlyComposable - get() = LocalOutlinedButtonStyle.current + @Composable @ReadOnlyComposable get() = LocalOutlinedButtonStyle.current public val JewelTheme.Companion.checkboxStyle: CheckboxStyle - @Composable - @ReadOnlyComposable - get() = LocalCheckboxStyle.current + @Composable @ReadOnlyComposable get() = LocalCheckboxStyle.current public val JewelTheme.Companion.chipStyle: ChipStyle - @Composable - @ReadOnlyComposable - get() = LocalChipStyle.current + @Composable @ReadOnlyComposable get() = LocalChipStyle.current public val JewelTheme.Companion.dividerStyle: DividerStyle - @Composable - @ReadOnlyComposable - get() = LocalDividerStyle.current + @Composable @ReadOnlyComposable get() = LocalDividerStyle.current public val JewelTheme.Companion.dropdownStyle: DropdownStyle - @Composable - @ReadOnlyComposable - get() = LocalDefaultDropdownStyle.current + @Composable @ReadOnlyComposable get() = LocalDefaultDropdownStyle.current public val JewelTheme.Companion.groupHeaderStyle: GroupHeaderStyle - @Composable - @ReadOnlyComposable - get() = LocalGroupHeaderStyle.current + @Composable @ReadOnlyComposable get() = LocalGroupHeaderStyle.current public val JewelTheme.Companion.linkStyle: LinkStyle - @Composable - @ReadOnlyComposable - get() = LocalLinkStyle.current + @Composable @ReadOnlyComposable get() = LocalLinkStyle.current public val JewelTheme.Companion.menuStyle: MenuStyle - @Composable - @ReadOnlyComposable - get() = LocalMenuStyle.current + @Composable @ReadOnlyComposable get() = LocalMenuStyle.current public val JewelTheme.Companion.horizontalProgressBarStyle: HorizontalProgressBarStyle - @Composable - @ReadOnlyComposable - get() = LocalHorizontalProgressBarStyle.current + @Composable @ReadOnlyComposable get() = LocalHorizontalProgressBarStyle.current public val JewelTheme.Companion.radioButtonStyle: RadioButtonStyle - @Composable - @ReadOnlyComposable - get() = LocalRadioButtonStyle.current + @Composable @ReadOnlyComposable get() = LocalRadioButtonStyle.current public val JewelTheme.Companion.scrollbarStyle: ScrollbarStyle - @Composable - @ReadOnlyComposable - get() = LocalScrollbarStyle.current + @Composable @ReadOnlyComposable get() = LocalScrollbarStyle.current public val JewelTheme.Companion.segmentedControlButtonStyle: SegmentedControlButtonStyle - @Composable - @ReadOnlyComposable - get() = LocalSegmentedControlButtonStyle.current + @Composable @ReadOnlyComposable get() = LocalSegmentedControlButtonStyle.current public val JewelTheme.Companion.segmentedControlStyle: SegmentedControlStyle - @Composable - @ReadOnlyComposable - get() = LocalSegmentedControlStyle.current + @Composable @ReadOnlyComposable get() = LocalSegmentedControlStyle.current public val JewelTheme.Companion.textAreaStyle: TextAreaStyle - @Composable - @ReadOnlyComposable - get() = LocalTextAreaStyle.current + @Composable @ReadOnlyComposable get() = LocalTextAreaStyle.current public val JewelTheme.Companion.textFieldStyle: TextFieldStyle - @Composable - @ReadOnlyComposable - get() = LocalTextFieldStyle.current + @Composable @ReadOnlyComposable get() = LocalTextFieldStyle.current public val JewelTheme.Companion.treeStyle: LazyTreeStyle - @Composable - @ReadOnlyComposable - get() = LocalLazyTreeStyle.current + @Composable @ReadOnlyComposable get() = LocalLazyTreeStyle.current public val JewelTheme.Companion.defaultTabStyle: TabStyle - @Composable - @ReadOnlyComposable - get() = LocalDefaultTabStyle.current + @Composable @ReadOnlyComposable get() = LocalDefaultTabStyle.current public val JewelTheme.Companion.editorTabStyle: TabStyle - @Composable - @ReadOnlyComposable - get() = LocalEditorTabStyle.current + @Composable @ReadOnlyComposable get() = LocalEditorTabStyle.current public val JewelTheme.Companion.circularProgressStyle: CircularProgressStyle - @Composable - @ReadOnlyComposable - get() = LocalCircularProgressStyle.current + @Composable @ReadOnlyComposable get() = LocalCircularProgressStyle.current public val JewelTheme.Companion.tooltipStyle: TooltipStyle - @Composable - @ReadOnlyComposable - get() = LocalTooltipStyle.current + @Composable @ReadOnlyComposable get() = LocalTooltipStyle.current public val JewelTheme.Companion.iconButtonStyle: IconButtonStyle - @Composable - @ReadOnlyComposable - get() = LocalIconButtonStyle.current + @Composable @ReadOnlyComposable get() = LocalIconButtonStyle.current public val JewelTheme.Companion.sliderStyle: SliderStyle - @Composable - @ReadOnlyComposable - get() = LocalSliderStyle.current + @Composable @ReadOnlyComposable get() = LocalSliderStyle.current @Composable -public fun BaseJewelTheme( - theme: ThemeDefinition, - styling: ComponentStyling, - content: @Composable () -> Unit, -) { +public fun BaseJewelTheme(theme: ThemeDefinition, styling: ComponentStyling, content: @Composable () -> Unit) { BaseJewelTheme(theme, styling, swingCompatMode = false, content) } @@ -201,10 +147,7 @@ public fun BaseJewelTheme( content: @Composable () -> Unit, ) { JewelTheme(theme, swingCompatMode) { - CompositionLocalProvider( - LocalColorPalette provides theme.colorPalette, - LocalIconData provides theme.iconData, - ) { + CompositionLocalProvider(LocalColorPalette provides theme.colorPalette, LocalIconData provides theme.iconData) { CompositionLocalProvider(values = styling.styles(), content = content) } } diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ColorExtensions.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ColorExtensions.kt index fd4daa520..220239eed 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ColorExtensions.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ColorExtensions.kt @@ -5,8 +5,8 @@ import androidx.compose.ui.graphics.luminance import kotlin.math.roundToInt /** - * Converts a [java.awt.Color] to a RGBA formatted color `#RRGGBBAA` hex - * string; e.g., `#FFFFFF1A` (a translucent white). + * Converts a [java.awt.Color] to a RGBA formatted color `#RRGGBBAA` hex string; e.g., `#FFFFFF1A` (a translucent + * white). */ public fun java.awt.Color.toRgbaHexString(): String { val r = Integer.toHexString(red) @@ -26,10 +26,7 @@ public fun java.awt.Color.toRgbaHexString(): String { } } -/** - * Converts a [Color] to a RGBA formatted color `#RRGGBBAA` hex string; - * e.g., `#FFFFFF1A` (a translucent white). - */ +/** Converts a [Color] to a RGBA formatted color `#RRGGBBAA` hex string; e.g., `#FFFFFF1A` (a translucent white). */ public fun Color.toRgbaHexString(): String { val r = Integer.toHexString((red * 255).roundToInt()) val g = Integer.toHexString((green * 255).roundToInt()) @@ -48,10 +45,7 @@ public fun Color.toRgbaHexString(): String { } } -/** - * Converts a RGBA formatted color `#RRGGBBAA` hex string to a [Color]; - * e.g., `#FFFFFF1A` (a translucent white). - */ +/** Converts a RGBA formatted color `#RRGGBBAA` hex string to a [Color]; e.g., `#FFFFFF1A` (a translucent white). */ public fun Color.Companion.fromRGBAHexStringOrNull(rgba: String): Color? = rgba .lowercase() diff --git a/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ModifierExtensions.kt b/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ModifierExtensions.kt index 61208e6f0..78ef44221 100644 --- a/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ModifierExtensions.kt +++ b/ui/src/main/kotlin/org/jetbrains/jewel/ui/util/ModifierExtensions.kt @@ -3,10 +3,8 @@ package org.jetbrains.jewel.ui.util import androidx.compose.ui.Modifier /** - * Conditionally applies the [action] to the receiver [Modifier], if - * [precondition] is true. Returns the receiver as-is otherwise. + * Conditionally applies the [action] to the receiver [Modifier], if [precondition] is true. Returns the receiver as-is + * otherwise. */ -public inline fun Modifier.thenIf( - precondition: Boolean, - action: Modifier.() -> Modifier, -): Modifier = if (precondition) action() else this +public inline fun Modifier.thenIf(precondition: Boolean, action: Modifier.() -> Modifier): Modifier = + if (precondition) action() else this diff --git a/ui/src/test/kotlin/org/jetbrains/jewel/BasicJewelUiTest.kt b/ui/src/test/kotlin/org/jetbrains/jewel/BasicJewelUiTest.kt index 19a666ca1..359a224b9 100644 --- a/ui/src/test/kotlin/org/jetbrains/jewel/BasicJewelUiTest.kt +++ b/ui/src/test/kotlin/org/jetbrains/jewel/BasicJewelUiTest.kt @@ -7,15 +7,12 @@ import kotlinx.coroutines.runBlocking import org.junit.Rule open class BasicJewelUiTest { - @get:Rule - val composeRule = createComposeRule() + @get:Rule val composeRule = createComposeRule() @Suppress("ImplicitUnitReturnType") - protected fun runComposeTest( - composable: @Composable () -> Unit, - block: suspend ComposeContentTestRule.() -> Unit, - ) = runBlocking { - composeRule.setContent(composable) - composeRule.block() - } + protected fun runComposeTest(composable: @Composable () -> Unit, block: suspend ComposeContentTestRule.() -> Unit) = + runBlocking { + composeRule.setContent(composable) + composeRule.block() + } } diff --git a/ui/src/test/kotlin/org/jetbrains/jewel/PainterHintTest.kt b/ui/src/test/kotlin/org/jetbrains/jewel/PainterHintTest.kt index 5705aab3b..255f1b55f 100644 --- a/ui/src/test/kotlin/org/jetbrains/jewel/PainterHintTest.kt +++ b/ui/src/test/kotlin/org/jetbrains/jewel/PainterHintTest.kt @@ -4,6 +4,8 @@ import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.unit.Density +import javax.xml.XMLConstants +import javax.xml.parsers.DocumentBuilderFactory import org.jetbrains.jewel.foundation.theme.OverrideDarkMode import org.jetbrains.jewel.ui.component.CheckboxState import org.jetbrains.jewel.ui.painter.PainterHint @@ -23,8 +25,6 @@ import org.jetbrains.jewel.ui.painter.writeToString import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Test -import javax.xml.XMLConstants -import javax.xml.parsers.DocumentBuilderFactory @Suppress("ImplicitUnitReturnType") class PainterHintTest : BasicJewelUiTest() { @@ -32,8 +32,7 @@ class PainterHintTest : BasicJewelUiTest() { fun `empty hint should be ignored`() = runComposeTest({ OverrideDarkMode(isDark = false) { - val provider = - rememberResourcePainterProvider("icons/github.svg", PainterHintTest::class.java) + val provider = rememberResourcePainterProvider("icons/github.svg", PainterHintTest::class.java) val painter1 by provider.getPainter() // must be ignored the None and hit cache @@ -55,8 +54,9 @@ class PainterHintTest : BasicJewelUiTest() { override val acceptedHints: List = listOf(), ) : PainterProviderScope, Density by density { private val documentBuilderFactory = - DocumentBuilderFactory.newDefaultInstance() - .apply { setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) } + DocumentBuilderFactory.newDefaultInstance().apply { + setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) + } fun applyPathHints(vararg hints: PainterHint): String { var result = rawPath @@ -70,10 +70,7 @@ class PainterHintTest : BasicJewelUiTest() { return result } - fun applyPaletteHints( - svg: String, - vararg hints: PainterHint, - ): String { + fun applyPaletteHints(svg: String, vararg hints: PainterHint): String { val doc = documentBuilderFactory.newDocumentBuilder().parse(svg.toByteArray().inputStream()) hints.filterIsInstance().onEach { @@ -87,10 +84,8 @@ class PainterHintTest : BasicJewelUiTest() { } } - private fun testScope( - path: String, - density: Float = 1f, - ): TestPainterProviderScope = TestPainterProviderScope(Density(density), path) + private fun testScope(path: String, density: Float = 1f): TestPainterProviderScope = + TestPainterProviderScope(Density(density), path) @Test fun `dark painter hint should append suffix when isDark is true`() { @@ -110,8 +105,7 @@ class PainterHintTest : BasicJewelUiTest() { fun `override painter hint should replace path entirely`() { val basePath = "icons/github.svg" val patchedPath = - testScope(basePath) - .applyPathHints(PathOverride(mapOf("icons/github.svg" to "icons/search.svg"))) + testScope(basePath).applyPathHints(PathOverride(mapOf("icons/github.svg" to "icons/search.svg"))) assertEquals("icons/search.svg", patchedPath) } @@ -119,8 +113,7 @@ class PainterHintTest : BasicJewelUiTest() { fun `override painter hint should not replace path when not matched`() { val basePath = "icons/github.svg" val patchedPath = - testScope(basePath) - .applyPathHints(PathOverride(mapOf("icons/settings.svg" to "icons/search.svg"))) + testScope(basePath).applyPathHints(PathOverride(mapOf("icons/settings.svg" to "icons/search.svg"))) assertEquals(basePath, patchedPath) } @@ -170,13 +163,9 @@ class PainterHintTest : BasicJewelUiTest() { fun `size painter hint should throw with wrong width or height`() { val basePath = "icons/github.svg" - Assert.assertThrows(IllegalArgumentException::class.java) { - testScope(basePath).applyPathHints(Size(-1, 20)) - } + Assert.assertThrows(IllegalArgumentException::class.java) { testScope(basePath).applyPathHints(Size(-1, 20)) } - Assert.assertThrows(IllegalArgumentException::class.java) { - testScope(basePath).applyPathHints(Size(20, 0)) - } + Assert.assertThrows(IllegalArgumentException::class.java) { testScope(basePath).applyPathHints(Size(20, 0)) } } @Test @@ -214,8 +203,7 @@ class PainterHintTest : BasicJewelUiTest() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) val patchedPath = - testScope(basePath) - .applyPathHints(Stateful(state.copy(pressed = true, hovered = true, focused = true))) + testScope(basePath).applyPathHints(Stateful(state.copy(pressed = true, hovered = true, focused = true))) assertEquals("icons/checkboxFocused.svg", patchedPath) } @@ -231,9 +219,7 @@ class PainterHintTest : BasicJewelUiTest() { fun `stateful painter hint pressed state takes higher priority over hovered state`() { val basePath = "icons/checkbox.svg" val state = CheckboxState.of(toggleableState = ToggleableState.Off) - val patchedPath = - testScope(basePath) - .applyPathHints(Stateful(state.copy(pressed = true, hovered = true))) + val patchedPath = testScope(basePath).applyPathHints(Stateful(state.copy(pressed = true, hovered = true))) assertEquals("icons/checkboxPressed.svg", patchedPath) } @@ -268,7 +254,8 @@ class PainterHintTest : BasicJewelUiTest() { | | | - """.trimMargin() + """ + .trimMargin() val patchedSvg = testScope("fake_icon.svg") @@ -279,7 +266,7 @@ class PainterHintTest : BasicJewelUiTest() { Color(0x80000000) to Color(0xFF123456), Color.Black to Color.White, Color.Green to Color.Red, - ), + ) ), ) .replace("\r\n", "\n") @@ -291,7 +278,8 @@ class PainterHintTest : BasicJewelUiTest() { | | | - """.trimMargin(), + """ + .trimMargin(), patchedSvg, ) }