Skip to content

Commit

Permalink
chore(intellij): address ktlint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
fwouts committed Jan 4, 2024
1 parent 0845ae4 commit 09293de
Show file tree
Hide file tree
Showing 7 changed files with 216 additions and 150 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class OpenPreviewAction : AnAction() {
if (selectedTextEditor == null || selectedFiles.isEmpty()) {
notificationGroup.createNotification(
"No file is currently selected",
NotificationType.ERROR
NotificationType.ERROR,
).notify(project)
return
}
Expand All @@ -29,7 +29,7 @@ class OpenPreviewAction : AnAction() {
if (previewables.isEmpty()) {
notificationGroup.createNotification(
"No components or stories detected in ${selectedFile.path}",
NotificationType.ERROR
NotificationType.ERROR,
).notify(project)
return@crawlFile
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,80 +10,93 @@ import retrofit2.http.POST
import java.util.concurrent.TimeUnit

fun api(baseUrl: String): PreviewJsApi {
val moshi = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
val okHttpClient: OkHttpClient = OkHttpClient().newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
val moshi =
Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
val okHttpClient: OkHttpClient =
OkHttpClient().newBuilder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build()
val retrofit =
Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()

return retrofit.create(PreviewJsApi::class.java)
}

interface PreviewJsApi {
@POST("/crawl-file")
suspend fun crawlFile(@Body req: CrawlFileRequest): CrawlFileResponse
suspend fun crawlFile(
@Body req: CrawlFileRequest,
): CrawlFileResponse

@POST("/previews/start")
suspend fun startPreview(@Body req: StartPreviewRequest): StartPreviewResponse
suspend fun startPreview(
@Body req: StartPreviewRequest,
): StartPreviewResponse

@POST("/previews/status")
suspend fun checkPreviewStatus(@Body req: CheckPreviewStatusRequest): CheckPreviewStatusResponse
suspend fun checkPreviewStatus(
@Body req: CheckPreviewStatusRequest,
): CheckPreviewStatusResponse

@POST("/previews/stop")
suspend fun stopPreview(@Body req: StopPreviewRequest): StopPreviewResponse
suspend fun stopPreview(
@Body req: StopPreviewRequest,
): StopPreviewResponse

@POST("/pending-files/update")
suspend fun updatePendingFile(@Body req: UpdatePendingFileRequest): UpdatePendingFileResponse
suspend fun updatePendingFile(
@Body req: UpdatePendingFileRequest,
): UpdatePendingFileResponse
}

data class CrawlFileRequest(
val absoluteFilePath: String
val absoluteFilePath: String,
)

data class CrawlFileResponse(
val rootDir: String?,
val previewables: List<Previewable>
val previewables: List<Previewable>,
)

data class Previewable(
val start: Int,
val end: Int,
val id: String
val id: String,
)

data class StartPreviewRequest(
val rootDir: String
val rootDir: String,
)

data class StartPreviewResponse(
val url: String
val url: String,
)

data class CheckPreviewStatusRequest(
val rootDir: String
val rootDir: String,
)

data class CheckPreviewStatusResponse(
val running: Boolean
val running: Boolean,
)

data class StopPreviewRequest(
val rootDir: String
val rootDir: String,
)

class StopPreviewResponse

data class UpdatePendingFileRequest(
val absoluteFilePath: String,
val utf8Content: String?
val utf8Content: String?,
)

class UpdatePendingFileResponse
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@ class InlayProviderFactory : InlayHintsProviderFactory {
companion object {
// Note #1: "textmate" is what's used in IntelliJ CE for JS/TS(X) files.
// Note #2: "TEXT" is what's used in IntelliJ CE for Vue files.
val LANGUAGE_IDS = setOf(
"TEXT",
"textmate",
"ECMAScript 6",
"JavaScript",
"TypeScript",
"TypeScript JSX",
"SvelteHTML",
"VueJS"
)
val LANGUAGE_IDS =
setOf(
"TEXT",
"textmate",
"ECMAScript 6",
"JavaScript",
"TypeScript",
"TypeScript JSX",
"SvelteHTML",
"VueJS",
)

// Full list from IntelliJ IDEA 2023.1:
// TOML, JSON, HgIgnore, InjectedFreeMarker, MySQL, AZURE, TypeScript, AIDL, AngularJS, PostCSS, Snowflake, Micronaut-MongoDB-JSON, Redis, XML, SQL92, TSQL, protobase, Angular2Svg, JSUnicodeRegexp, Nashorn JS, JVM, EL, Gherkin, AndroidDataBinding, SQLDateTime, SVG, , XHTML, RoomSql, DB2, Properties, XPath, DB2_ZOS, FTL>, JavaScript 1.8, ThymeleafSpringSecurityExtras, Renderscript, Angular2, prototext, ThymeleafTemplatesExpressions, H2, XsdRegExp, HTML, LESS, JQL, yaml, MongoJSExt, JSPX, Flow JS, PostgreSQL, JQuery-CSS, GitIgnore, Lombok.Config, Dockerfile, KND, CouchbaseQuery, Qute, JSRegexp, ThymeleafExpressions, VueExpr, SQLite, SparkSQL, GenericSQL, JSP, OracleSqlPlus, UastContextLanguage, Markdown, DTD, TEXT, DeviceSpec, UAST, ThymeleafUrlExpressions, EQL, Groovy, TypeScript JSX, SCSS, JSONPath, JSON5, Vue, Exasol, HSQLDB, protobuf, EditorConfig, ECMA Script Level 4, Greenplum, Cookie, kotlin, textmate, ClickHouse, HtmlCompatible, EJBQL, Derby, SPI, Cockroach, JavaScript, Angular2Html, MicronautDataQL, IntegrationPerformanceTest, VTL, GitExclude, MultiDexKeep, Shell Script, CassandraQL, RegExp, HiveQL, Smali, Manifest, SHRINKER_CONFIG, JAVA, LogcatFilter, VueJS, IgnoreLang, SQL, $XSLT, PointcutExpression, MariaDB, DB2_IS, AGSL, Oracle, SpEL, SpringDataQL, JSON Lines, FTL], BigQuery, MongoJS, YouTrack, CSS, MongoDB, Metadata JSON, Vertica, SASS, Sybase, ThymeleafIterateExpressions, ThymeleafTemplatesFragmentExpressions, ECMAScript 6, XPath2, HTTP Request, RELAX-NG, DockerIgnore, HttpClientHandlerJavaScriptDialect, FTL, JPAQL, HQL, JShellLanguage, VueTS, MySQL based, MongoDB-JSON, Spring-MongoDB-JSON, Redshift
Expand All @@ -59,6 +60,7 @@ class InlayProviderFactory : InlayHintsProviderFactory {
override val key = SettingsKey<NoSettings>(InlayProvider::class.qualifiedName!!)
override val name = "Preview.js hints"
override val previewText = null

override fun createSettings() = NoSettings()

override val isVisibleInSettings = false
Expand All @@ -71,9 +73,13 @@ class InlayProviderFactory : InlayHintsProviderFactory {
file: PsiFile,
editor: Editor,
settings: NoSettings,
sink: InlayHintsSink
sink: InlayHintsSink,
) = object : FactoryInlayHintsCollector(editor) {
override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean {
override fun collect(
element: PsiElement,
editor: Editor,
sink: InlayHintsSink,
): Boolean {
val projectService = file.project.service<ProjectService>()
val components = projectService.getPrecomputedComponents(file)
for (component in components) {
Expand All @@ -83,11 +89,12 @@ class InlayProviderFactory : InlayHintsProviderFactory {
relatesToPrecedingText = false,
showAbove = true,
priority = 0,
presentation = factory.referenceOnHover(
factory.roundWithBackground(factory.smallText("Open $previewableName in Preview.js"))
) { _, _ ->
projectService.openPreview(file.virtualFile.path, component.id)
}
presentation =
factory.referenceOnHover(
factory.roundWithBackground(factory.smallText("Open $previewableName in Preview.js")),
) { _, _ ->
projectService.openPreview(file.virtualFile.path, component.id)
},
)
}
return false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,36 +54,37 @@ class PreviewJsSharedService : Disposable {
data class Message(
val project: Project,
val fn: suspend CoroutineScope.(api: PreviewJsApi) -> Unit,
val getErrorMessage: (e: Throwable) -> String
val getErrorMessage: (e: Throwable) -> String,
)

@OptIn(ObsoleteCoroutinesApi::class)
private var actor = coroutineScope.actor<Message> {
var errorCount = 0
for (msg in channel) {
val api = initializeApi(msg.project)
try {
(msg.fn)(api)
} catch (e: Throwable) {
val errorMessage = (msg.getErrorMessage)(e)
msg.project.service<ProjectService>().printToConsole("$errorMessage\n\n${e.stackTraceToString()}\n")
errorCount += 1
if (errorCount > 10) {
// Something must be seriously wrong, abort.
notificationGroup.createNotification(
"Preview.js tasks are failing repeatedly",
"""Please report this issue at https://github.com/fwouts/previewjs/issues
private var actor =
coroutineScope.actor<Message> {
var errorCount = 0
for (msg in channel) {
val api = initializeApi(msg.project)
try {
(msg.fn)(api)
} catch (e: Throwable) {
val errorMessage = (msg.getErrorMessage)(e)
msg.project.service<ProjectService>().printToConsole("$errorMessage\n\n${e.stackTraceToString()}\n")
errorCount += 1
if (errorCount > 10) {
// Something must be seriously wrong, abort.
notificationGroup.createNotification(
"Preview.js tasks are failing repeatedly",
"""Please report this issue at https://github.com/fwouts/previewjs/issues
Include the content of the Preview.js logs panel for easier debugging.
""".trimMargin(),
NotificationType.ERROR
)
.notify(msg.project)
return@actor
""".trimMargin(),
NotificationType.ERROR,
)
.notify(msg.project)
return@actor
}
}
}
}
}

private suspend fun initializeApi(project: Project): PreviewJsApi {
api?.let {
Expand All @@ -97,7 +98,7 @@ Include the content of the Preview.js logs panel for easier debugging.
notificationGroup.createNotification(
"Incompatible Node.js version",
e.message,
NotificationType.ERROR
NotificationType.ERROR,
)
.notify(project)
throw e
Expand All @@ -107,7 +108,7 @@ Include the content of the Preview.js logs panel for easier debugging.
"""Please report this issue at https://github.com/fwouts/previewjs/issues
${e.stackTraceToString()}""",
NotificationType.ERROR
NotificationType.ERROR,
)
.notify(project)
throw e
Expand All @@ -117,7 +118,7 @@ ${e.stackTraceToString()}""",
fun enqueueAction(
project: Project,
fn: suspend CoroutineScope.(api: PreviewJsApi) -> Unit,
getErrorMessage: (e: Throwable) -> String
getErrorMessage: (e: Throwable) -> String,
): Job {
return coroutineScope.launch {
actor.send(Message(project, fn, getErrorMessage))
Expand Down Expand Up @@ -159,8 +160,9 @@ ${e.stackTraceToString()}""",
throw Error("Preview.js was unable to run node.\\n\\nIs it installed? You may need to restart your IDE.")
}
checkNodeVersion(nodeVersionProcess)
val builder = processBuilder("node --trace-warnings dist/main.js $port").redirectErrorStream(true)
.directory(nodeDirPath.toFile())
val builder =
processBuilder("node --trace-warnings dist/main.js $port").redirectErrorStream(true)
.directory(nodeDirPath.toFile())
builder.environment()["PREVIEWJS_PARENT_PROCESS_PID"] = ProcessHandle.current().pid().toString()
val process = builder.start()
daemonProcess = process
Expand All @@ -179,13 +181,13 @@ ${e.stackTraceToString()}""",
if (line.contains("[install:begin]")) {
notificationGroup.createNotification(
"⏳ Installing Preview.js dependencies...",
NotificationType.INFORMATION
NotificationType.INFORMATION,
).notify(project)
}
if (line.contains("[install:end]")) {
notificationGroup.createNotification(
"✅ Preview.js dependencies installed",
NotificationType.INFORMATION
NotificationType.INFORMATION,
).notify(project)
}
if (line.contains("[ready]")) {
Expand Down Expand Up @@ -221,13 +223,16 @@ ${e.stackTraceToString()}""",
}
},
0,
PING_INTERVAL_MILLIS
PING_INTERVAL_MILLIS,
)

return client
}

private fun everyProject(project: Project, f: ProjectService.() -> Unit) {
private fun everyProject(
project: Project,
f: ProjectService.() -> Unit,
) {
for (p in workspaceIds.keys + setOf(project)) {
if (p.isDisposed) {
continue
Expand All @@ -242,7 +247,9 @@ ${e.stackTraceToString()}""",
matchResult?.let {
val majorVersion = matchResult.groups[1]!!.value.toInt()
if (majorVersion < 18) {
throw NodeVersionError("Preview.js needs NodeJS 18+ to run, but current version is: ${nodeVersion}\n\nPlease upgrade then restart your IDE.")
throw NodeVersionError(
"Preview.js needs NodeJS 18+ to run, but current version is: ${nodeVersion}\n\nPlease upgrade then restart your IDE.",
)
}
}
}
Expand All @@ -252,7 +259,7 @@ ${e.stackTraceToString()}""",
ProcessBuilder(
"cmd.exe",
"/C",
command
command,
)
} else {
// Note: in production builds of IntelliJ / WebStorm, PATH is not initialised
Expand Down
Loading

0 comments on commit 09293de

Please sign in to comment.