diff --git a/.gitattributes b/.gitattributes index 00a51af..9a335a8 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,6 +1,8 @@ # # https://help.github.com/articles/dealing-with-line-endings/ # +* text=auto eol=lf + # These are explicitly windows files and should use crlf *.bat text eol=crlf diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..8e7429d --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,46 @@ +name: Build + +on: + push: + branches: [master] + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Fetch sources + uses: actions/checkout@v6 + + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Test and build + run: ./gradlew check buildPlugin + + - name: Verify plugin compatibility + run: ./gradlew verifyPlugin + + - name: Upload plugin distribution + uses: actions/upload-artifact@v7 + with: + name: angular-cli-quick-switch + path: build/distributions/*.zip + + - name: Upload verification reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: plugin-verifier-reports + path: build/reports/pluginVerifier + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2bc55ca --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +name: Publish + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish: + runs-on: ubuntu-latest + environment: marketplace + steps: + - name: Fetch sources + uses: actions/checkout@v6 + + - name: Set up Java + uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: 21 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@v6 + + - name: Test and verify + run: ./gradlew check verifyPlugin + + - name: Sign and publish + run: ./gradlew publishPlugin + env: + CERTIFICATE_CHAIN: ${{ secrets.CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.PRIVATE_KEY_PASSWORD }} + PUBLISH_TOKEN: ${{ secrets.PUBLISH_TOKEN }} diff --git a/.gitignore b/.gitignore index 4ddb3dd..2c7d09a 100755 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .idea/ .gradle/ +.intellijPlatform/ *.iws *.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 32e9a14..9d715c2 100755 --- a/README.md +++ b/README.md @@ -1,36 +1,96 @@ -# angular-cli-quick-switch-plugin +# Angular CLI QuickSwitch -IntelliJ Plugin for switching amongst Angular CLI component files efficiently (e.g. ts -> html -> css) by just using one shortcut (**Alt+S**). +Quickly switch between related component files in IntelliJ-based IDEs. Use one shortcut to cycle through a component, or jump directly to its controller, markup, style, or test files. -For example let's say we have a structure like this +Given these related files: - foo/ - bar.info - foo.component.css - foo.component.html - **foo.component.ts** - foo.md +```text +foo/ + foo.component.css + foo.component.html + foo.component.spec.ts + foo.component.ts +``` -By pressing the assigned shortcut repeatedly, the IDE will cycle amongst the files as follows: +Press **Alt+S** repeatedly to cycle through the enabled file types: - foo.component.ts -> foo.component.html -> foo.component.css -> foo.component.ts -> ... +```text +foo.component.ts -> foo.component.html -> foo.component.css -> foo.component.ts +``` +Test files are excluded from the main cycle by default. Press **Alt+T** to jump directly to `foo.component.spec.ts`, or enable test files in the plugin settings to include them in the main cycle. -Whilst cycling, unknown filenames (like bar.info) and extensions (like foo.md) will be skipped on purpose. +## Shortcuts -Explicitly whitelisted extensions are: -- js, ts -- html, php, haml, jade, pug, slim -- css, sass, scss, less, styl +| Action | Default | Behavior | +|---|---|---| +| QuickSwitch | **Alt+S** | Cycles through all enabled related file types. | +| QuickSwitch: Controllers | **Alt+X** | Jumps to and cycles between `.ts` and `.js`. | +| QuickSwitch: Markup | **Alt+C** | Jumps to and cycles between supported markup files. | +| QuickSwitch: Styles | **Alt+V** | Jumps to and cycles between supported style files. | +| QuickSwitch: Tests | **Alt+T** | Jumps to and cycles between `.spec.ts` and `.spec.js`. | -Note: -For switching between your code and test/spec files, you can simply use the built in default shortcut from IntelliJ (**Ctrl+Shift+T**) +All shortcuts can be changed under the IDE's **Settings | Keymap** page by searching for `QuickSwitch`. +## Settings +Open **Settings | Tools | Angular CLI QuickSwitch** to configure navigation behavior and the main cycle. -Further information: +### General -If the default shortcut **Alt + S** does not fit your needs, you can of course easily adjust it in the keymap settings by replacing it for **QuickSwitch**. +**Close the previous tab after switching** is disabled by default. -Due to the nature of this plugin, it will of course also **work with other projects**, that have not been generated by Angular CLI - or are -not even Angular projects at all - as long as your project structure follows similar patterns. \ No newline at end of file +When disabled, the previous file remains open. This provides the smoothest behavior and preserves tab order, pinned state, and editor splits. + +When enabled, QuickSwitch opens the target in the active editor group first and closes the source only after the target opens successfully. Opening first minimizes the tab collapse and flicker caused by the old close-first behavior. + +IntelliJ does not expose stable public APIs for transferring pinned state or closing only one occurrence of a file in a specific split. Consequently, close-on-switch mode can lose pinning and may close other occurrences of the source file in sibling editor groups. + +### Supported Extensions + +The settings page groups file types by purpose: + +| Group | File types | Main-cycle default | +|---|---|---| +| Controller | `.ts`, `.js` | Enabled | +| Template | `.html`, `.php`, `.haml`, `.jade`, `.pug`, `.slim` | Enabled | +| Style | `.css`, `.sass`, `.scss`, `.less`, `.styl` | Enabled | +| Tests | `.spec.ts`, `.spec.js` | Disabled | + +**Alt+S** checks the groups in the listed order: Controller, Template, Style, then Tests. Each checkbox controls whether that file type participates in the main cycle, making workflows such as cycling directly between TypeScript and HTML possible by disabling the style types. + +The dedicated category shortcuts intentionally ignore these checkboxes. For example, **Alt+T** can always find a related test file even when tests are excluded from the main cycle. + +### Custom Extensions + +Each group supports one optional custom suffix, such as `.tsx` or `.module.scss`; enable its checkbox and enter a unique suffix starting with a dot. Enabled custom suffixes are appended to their group and used as targets by both the main cycle and dedicated category shortcut. + +## Compatibility + +Version 2.0 targets IntelliJ Platform build `242` and newer, corresponding to IntelliJ IDEA 2024.2 and compatible releases of WebStorm, PhpStorm, PyCharm, GoLand, Rider, CLion, Android Studio, and other standalone IntelliJ-based IDEs. + +The plugin is compiled with Java 21. End users do not need to install a separate JDK because supported IDEs provide the required runtime. Java 21 is required when building the plugin from source. + +Compatibility is checked with JetBrains Plugin Verifier against platform versions from 2024.2 through 2026.2. + +## Build Variants + +The shared codebase produces two mutually exclusive plugin variants: + +| Variant | Plugin name | Plugin ID | +|---|---|---| +| `angular` (default) | Angular CLI QuickSwitch | `patrick.kelleter.angular-cli-quick-switch` | +| `file` | File QuickSwitch | `patrick.kelleter.file-quick-switch` | + +Build either variant with Java 21: + +```shell +./gradlew buildPlugin -PpluginVariant=angular +./gradlew buildPlugin -PpluginVariant=file +``` + +The ZIP files are written to `build/distributions` with variant-specific names. Both variants retain the same internal action and settings IDs so keymaps and preferences survive switching between them, but they cannot be installed simultaneously. + +## License + +Licensed under the [Apache License 2.0](LICENSE). diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 18de48f..0000000 --- a/build.gradle +++ /dev/null @@ -1,41 +0,0 @@ -/* - * This file was generated by the Gradle 'init' task. - * - * This is a general purpose Gradle build. - * Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds - */ - -plugins { - id 'java' - id 'idea' - id 'org.jetbrains.intellij' version '0.4.21' -} - -group 'patrick.kelleter' -version '1.3.1' - -apply plugin: 'java' - -java { - sourceCompatibility = JavaVersion.VERSION_11 -} - -repositories { - mavenCentral() -} - -dependencies { - testCompileOnly 'junit:junit:4.12' -} - -intellij { - updateSinceUntilBuild false -} -patchPluginXml { - changeNotes """ - - Added support for php, haml, jade, pug, slim, less, styl files.
- Updated docs
""" -} - -task wrapper(type: Wrapper) { - gradleVersion = '6.5' -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..d72456c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,177 @@ +import org.apache.tools.ant.filters.ReplaceTokens +import org.gradle.api.tasks.bundling.Zip +import org.jetbrains.intellij.platform.gradle.IntelliJPlatformType +import org.jetbrains.intellij.platform.gradle.TestFrameworkType +import org.jetbrains.intellij.platform.gradle.tasks.ComposedJarTask +import org.jetbrains.intellij.platform.gradle.tasks.PatchPluginXmlTask + +plugins { + java + id("org.jetbrains.intellij.platform") version "2.18.1" +} + +data class PluginBranding( + val id: String, + val name: String, + val description: String, + val actionPrefix: String, + val controllerCategoryName: String, + val controllerActionName: String, + val controllerActionDescription: String, + val templateCategoryName: String, + val cycleActionDescription: String, + val incompatiblePluginId: String, + val archiveBaseName: String +) + +val pluginVariantName = providers.gradleProperty("pluginVariant") + .orElse("angular") + .get() + .lowercase() +val pluginBranding = when (pluginVariantName) { + "angular" -> PluginBranding( + id = "patrick.kelleter.angular-cli-quick-switch", + name = "Angular CLI QuickSwitch", + description = "Switch between related Angular component files with configurable shortcuts. Cycle through controllers, templates, styles, and tests, jump directly to a category, and add custom suffixes.", + actionPrefix = "QuickSwitch", + controllerCategoryName = "Controller", + controllerActionName = "Controllers", + controllerActionDescription = "Switches directly to and between related controller files", + templateCategoryName = "Template", + cycleActionDescription = "Quickly switches between Angular CLI files for one component, e.g. ts, html, css", + incompatiblePluginId = "patrick.kelleter.file-quick-switch", + archiveBaseName = "angular-cli-quick-switch" + ) + "file" -> PluginBranding( + id = "patrick.kelleter.file-quick-switch", + name = "File QuickSwitch", + description = "Switch between related sibling files with configurable shortcuts. Cycle through scripts, markup, styles, and tests, jump directly to a category, and add custom suffixes.", + actionPrefix = "File QuickSwitch", + controllerCategoryName = "Scripts", + controllerActionName = "Scripts", + controllerActionDescription = "Switches directly to and between related script files", + templateCategoryName = "Markup", + cycleActionDescription = "Quickly switches between related files with the same base name, e.g. ts, html, css", + incompatiblePluginId = "patrick.kelleter.angular-cli-quick-switch", + archiveBaseName = "file-quick-switch" + ) + else -> throw GradleException( + "Unknown pluginVariant '$pluginVariantName'. Supported variants are 'angular' and 'file'." + ) +} + +val brandingTokens = mapOf( + "PLUGIN_ID" to pluginBranding.id, + "PLUGIN_NAME" to pluginBranding.name, + "PLUGIN_DESCRIPTION" to pluginBranding.description, + "ACTION_PREFIX" to pluginBranding.actionPrefix, + "CONTROLLER_CATEGORY_NAME" to pluginBranding.controllerCategoryName, + "CONTROLLER_ACTION_NAME" to pluginBranding.controllerActionName, + "CONTROLLER_ACTION_DESCRIPTION" to pluginBranding.controllerActionDescription, + "TEMPLATE_CATEGORY_NAME" to pluginBranding.templateCategoryName, + "CYCLE_ACTION_DESCRIPTION" to pluginBranding.cycleActionDescription, + "INCOMPATIBLE_PLUGIN_ID" to pluginBranding.incompatiblePluginId +) + +group = "patrick.kelleter" +version = "2.0.0" + +base { + archivesName = pluginBranding.archiveBaseName +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() + intellijPlatform { + defaultRepositories() + } +} + +dependencies { + testImplementation("junit:junit:4.13.2") + + intellijPlatform { + intellijIdeaCommunity("2024.2.6") + testFramework(TestFrameworkType.Platform) + } +} + +tasks.withType().configureEach { + options.release = 21 +} + +val generatedPluginXml = layout.buildDirectory.file("generated/pluginXml/plugin.xml") +val generatePluginXml = tasks.register("generatePluginXml") { + inputs.property("pluginVariant", pluginVariantName) + inputs.properties(brandingTokens) + from(layout.projectDirectory.file("src/main/plugin/plugin.xml")) + into(generatedPluginXml.map { it.asFile.parentFile }) + filteringCharset = "UTF-8" + filter("tokens" to brandingTokens) +} + +tasks.named("patchPluginXml") { + dependsOn(generatePluginXml) + inputFile = generatedPluginXml +} + +tasks.processResources { + inputs.property("pluginVariant", pluginVariantName) + inputs.properties(brandingTokens) + filteringCharset = "UTF-8" + filter("tokens" to brandingTokens) +} + +tasks.named("buildPlugin") { + archiveBaseName = pluginBranding.archiveBaseName +} + +tasks.named("composedJar") { + archiveBaseName = pluginBranding.archiveBaseName +} + +tasks.check { + dependsOn(tasks.named("verifyPluginProjectConfiguration")) +} + +intellijPlatform { + buildSearchableOptions = true + + pluginConfiguration { + id = pluginBranding.id + name = pluginBranding.name + description = pluginBranding.description + changeNotes = """ +
    +
  • Updated for IntelliJ Platform 2024.2 and newer.
  • +
  • Added a settings page with optional previous-tab closing.
  • +
  • Added grouped file-type controls and optional spec.ts/spec.js test cycling.
  • +
  • Added one validated custom file suffix per category.
  • +
  • Added dedicated shortcuts for tests, ${pluginBranding.controllerActionName.lowercase()}, styles, and markup.
  • +
  • Fixed switching in editor splits and removed tab-closing side effects by default.
  • +
  • Improved support for virtual files and modern IntelliJ action APIs.
  • +
+ """.trimIndent() + + ideaVersion { + sinceBuild = "242" + untilBuild = provider { null } + } + } + + pluginVerification { + ides { + current() + recommended() + create(IntelliJPlatformType.IntellijIdea, "2025.3.6.1") + create(IntelliJPlatformType.IntellijIdea, "2026.1.5") + create(IntelliJPlatformType.IntellijIdea, "2026.2.1") + } + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..bd042d8 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.caching=true +org.gradle.configuration-cache=true +org.jetbrains.intellij.platform.forceBuildSearchableOptions=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 62d4c05..eddabd2 100755 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ad635e5..760c459 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,10 @@ -#Wed Jun 03 13:15:19 CEST 2020 -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 32f5a93..249efbb 100755 --- a/gradlew +++ b/gradlew @@ -1,79 +1,128 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -82,88 +131,118 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 85baee8..a51ec4f 100755 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,15 +1,34 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -24,65 +43,40 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -goto fail +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +if exist "%JAVA_EXE%" goto execute -goto fail +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* +"%COMSPEC%" /c exit 1 :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 9ced24a..0000000 --- a/settings.gradle +++ /dev/null @@ -1,10 +0,0 @@ -/* - * This file was generated by the Gradle 'init' task. - * - * The settings file is used to specify which projects to include in your build. - * - * Detailed information about configuring a multi-project build in Gradle can be found - * in the user manual at https://docs.gradle.org/6.5/userguide/multi_project_builds.html - */ - -rootProject.name = 'angular-cli-quick-switch-plugin' diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..29d909a --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "angular-cli-quick-switch-plugin" diff --git a/src/main/java/QuickSwitchAction.java b/src/main/java/QuickSwitchAction.java deleted file mode 100755 index 9e0563b..0000000 --- a/src/main/java/QuickSwitchAction.java +++ /dev/null @@ -1,84 +0,0 @@ -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.fileEditor.FileEditorManager; -import com.intellij.openapi.fileEditor.OpenFileDescriptor; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.LocalFileSystem; -import com.intellij.openapi.vfs.VirtualFile; - -import java.util.Arrays; -import java.util.List; - -public class QuickSwitchAction extends AnAction { - - private AnActionEvent latestEvent; - - private List extensions = Arrays.asList( - "ts", "js", - "html", "php", "haml", "jade", "pug", "slim", - "css", "sass", "scss", "less", "styl" - ); - - public QuickSwitchAction() { - super("QuickSwitch"); - } - - @Override - public void actionPerformed(AnActionEvent event) { - this.latestEvent = event; - - VirtualFile currentFile = (VirtualFile) event.getDataContext().getData("virtualFile"); - if (currentFile == null) return; - - String currentFilePath = currentFile.getCanonicalPath(); - if (currentFilePath == null) return; - - String basePath = this.removeFilePathExtension(currentFilePath); - String extension = this.getFilePathExtension(currentFilePath); - if (basePath == null || extension == null) return; - - String newPath = this.cycleExtension(basePath, extension); - this.switchFile(currentFilePath, newPath); - } - - private String getFilePathExtension(String filePath) { - int extensionPosition = filePath.lastIndexOf("."); - if (extensionPosition == -1) return null; - return filePath.substring(extensionPosition + 1); - } - - private String removeFilePathExtension(String filePath) { - int extensionPosition = filePath.lastIndexOf("."); - if (extensionPosition == -1) return filePath; - return filePath.substring(0, extensionPosition); - } - - private String cycleExtension(String basePath, String currentExtension) { - String currentPath = basePath + "." + currentExtension; - int currentIndex = this.extensions.indexOf(currentExtension); - if (currentIndex == -1) return currentPath; - for (int i = 0; i < this.extensions.size(); i++) { - int newIndex = ((currentIndex + 1 + i) % this.extensions.size()); - String newExtension = this.extensions.get(newIndex); - String newPath = basePath + "." + newExtension; - VirtualFile newFile = this.getFileByPath(newPath); - if (newFile != null && newFile.exists()) return newPath; - } - return currentPath; - } - - private void switchFile(String currentFilePath, String newFilePath) { - Project project = this.latestEvent.getProject(); - if (project == null) return; - VirtualFile currentFile = this.getFileByPath(currentFilePath); - VirtualFile newFile = this.getFileByPath(newFilePath); - if (!currentFile.exists() || !newFile.exists()) return; - FileEditorManager.getInstance(project).closeFile(currentFile); - new OpenFileDescriptor(project, newFile).navigate(true); - } - - private VirtualFile getFileByPath(String path) { - return LocalFileSystem.getInstance().findFileByPath(path); - } - -} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchAction.java new file mode 100644 index 0000000..ee9cd38 --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchAction.java @@ -0,0 +1,288 @@ +package patrick.kelleter.angularcliquickswitch; + +import com.intellij.openapi.actionSystem.ActionUpdateThread; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.project.DumbAwareAction; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +public final class QuickSwitchAction extends DumbAwareAction { + private static final List BUILT_IN_TYPES = List.of(QuickSwitchFileType.values()); + private static final List BUILT_IN_DEFINITIONS = BUILT_IN_TYPES.stream() + .map(fileType -> new FileTypeDefinition(fileType.category(), fileType.suffix(), fileType)) + .toList(); + + @Override + public @NotNull ActionUpdateThread getActionUpdateThread() { + return ActionUpdateThread.BGT; + } + + @Override + public void update(@NotNull AnActionEvent event) { + Project project = event.getProject(); + VirtualFile file = event.getData(CommonDataKeys.VIRTUAL_FILE); + event.getPresentation().setEnabled( + project != null + && !project.isDisposed() + && isSwitchable(file, QuickSwitchSettings.getInstance()) + ); + } + + @Override + public void actionPerformed(@NotNull AnActionEvent event) { + Project project = event.getProject(); + VirtualFile currentFile = event.getData(CommonDataKeys.VIRTUAL_FILE); + if (project == null || project.isDisposed() || currentFile == null) { + return; + } + + QuickSwitchSettings settings = QuickSwitchSettings.getInstance(); + VirtualFile targetFile = findTargetFile(currentFile, settings); + if (targetFile == null) { + return; + } + + navigate(project, currentFile, targetFile, settings.isClosePreviousTab()); + } + + static void navigate( + @NotNull Project project, + @NotNull VirtualFile currentFile, + @NotNull VirtualFile targetFile, + boolean closePreviousTab + ) { + OpenFileDescriptor descriptor = new OpenFileDescriptor(project, targetFile) + .setUseCurrentWindow(true); + FileEditorManager fileEditorManager = FileEditorManager.getInstance(project); + boolean targetOpened = !fileEditorManager.openEditor(descriptor, true).isEmpty(); + + if (targetOpened && closePreviousTab && currentFile.isValid() && !currentFile.equals(targetFile)) { + fileEditorManager.closeFile(currentFile); + } + } + + static @Nullable VirtualFile findTargetFile(@NotNull VirtualFile currentFile) { + return findTargetFile(currentFile, QuickSwitchFileType::enabledByDefault); + } + + static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull Predicate isEnabled + ) { + return findTargetFile( + currentFile, + BUILT_IN_DEFINITIONS, + definition -> isEnabled.test(definition.builtInType()) + ); + } + + static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull QuickSwitchSettings settings + ) { + List definitions = createFileTypeDefinitions(settings); + return findTargetFile(currentFile, definitions, definition -> isEnabled(definition, settings)); + } + + static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull QuickSwitchFileType.Category category + ) { + return findTargetFile(currentFile, category, BUILT_IN_DEFINITIONS, definition -> true); + } + + static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull QuickSwitchFileType.Category category, + @NotNull QuickSwitchSettings settings + ) { + List definitions = createFileTypeDefinitions(settings); + return findTargetFile( + currentFile, + category, + definitions, + definition -> definition.builtInType() != null || isEnabled(definition, settings) + ); + } + + static boolean isSwitchable(@Nullable VirtualFile file, @NotNull QuickSwitchSettings settings) { + return isSwitchable(file, createFileTypeDefinitions(settings)); + } + + private static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull List definitions, + @NotNull Predicate isEnabled + ) { + FileContext context = getFileContext(currentFile, definitions); + if (context == null) { + return null; + } + + int currentIndex = definitions.indexOf(context.currentType()); + for (int offset = 1; offset < definitions.size(); offset++) { + FileTypeDefinition targetType = definitions.get((currentIndex + offset) % definitions.size()); + if (!isEnabled.test(targetType)) { + continue; + } + + VirtualFile target = findSibling(context.baseName(), targetType, context.siblings()); + if (target != null) { + return target; + } + } + return null; + } + + private static @Nullable VirtualFile findTargetFile( + @NotNull VirtualFile currentFile, + @NotNull QuickSwitchFileType.Category category, + @NotNull List definitions, + @NotNull Predicate isEnabled + ) { + FileContext context = getFileContext(currentFile, definitions); + if (context == null) { + return null; + } + + List categoryTypes = definitions.stream() + .filter(definition -> definition.category() == category) + .toList(); + int currentIndex = categoryTypes.indexOf(context.currentType()); + + if (currentIndex < 0) { + for (FileTypeDefinition targetType : categoryTypes) { + if (!isEnabled.test(targetType)) { + continue; + } + VirtualFile target = findSibling(context.baseName(), targetType, context.siblings()); + if (target != null) { + return target; + } + } + return null; + } + + for (int offset = 1; offset < categoryTypes.size(); offset++) { + FileTypeDefinition targetType = categoryTypes.get((currentIndex + offset) % categoryTypes.size()); + if (!isEnabled.test(targetType)) { + continue; + } + VirtualFile target = findSibling(context.baseName(), targetType, context.siblings()); + if (target != null) { + return target; + } + } + return null; + } + + private static boolean isSwitchable( + @Nullable VirtualFile file, + @NotNull List definitions + ) { + return file != null && getFileContext(file, definitions) != null; + } + + private static @Nullable FileContext getFileContext( + @NotNull VirtualFile file, + @NotNull List definitions + ) { + if (!file.isValid() || file.isDirectory()) { + return null; + } + + VirtualFile parent = file.getParent(); + FileMatch match = matchFile(file, definitions); + if (parent == null || match == null) { + return null; + } + return new FileContext(match.fileType(), match.baseName(), parent.getChildren()); + } + + private static @Nullable FileMatch matchFile( + @NotNull VirtualFile file, + @NotNull List definitions + ) { + String fileName = file.getName(); + List longestSuffixFirst = definitions.stream() + .sorted(Comparator.comparingInt((FileTypeDefinition definition) -> definition.suffix().length()).reversed()) + .toList(); + + for (FileTypeDefinition definition : longestSuffixFirst) { + String suffix = "." + definition.suffix(); + int suffixStart = fileName.length() - suffix.length(); + if (suffixStart > 0 && fileName.regionMatches(true, suffixStart, suffix, 0, suffix.length())) { + return new FileMatch(definition, fileName.substring(0, suffixStart)); + } + } + return null; + } + + private static @Nullable VirtualFile findSibling( + @NotNull String baseName, + @NotNull FileTypeDefinition targetType, + VirtualFile @NotNull [] siblings + ) { + String targetName = baseName + "." + targetType.suffix(); + for (VirtualFile sibling : siblings) { + if (sibling.isValid() + && !sibling.isDirectory() + && targetName.equalsIgnoreCase(sibling.getName())) { + return sibling; + } + } + return null; + } + + private static List createFileTypeDefinitions(QuickSwitchSettings settings) { + List definitions = new ArrayList<>(); + Set usedSuffixes = new HashSet<>(); + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + for (QuickSwitchFileType fileType : BUILT_IN_TYPES) { + if (fileType.category() == category) { + definitions.add(new FileTypeDefinition(category, fileType.suffix(), fileType)); + usedSuffixes.add(fileType.suffix().toLowerCase(java.util.Locale.ROOT)); + } + } + + String customSuffix = settings.getCustomSuffix(category); + if (!customSuffix.isBlank() + && usedSuffixes.add(customSuffix.toLowerCase(java.util.Locale.ROOT))) { + definitions.add(new FileTypeDefinition(category, customSuffix, null)); + } + } + return definitions; + } + + private static boolean isEnabled(FileTypeDefinition definition, QuickSwitchSettings settings) { + return definition.builtInType() != null + ? settings.isFileTypeEnabled(definition.builtInType()) + : settings.isCustomSuffixEnabled(definition.category()); + } + + private record FileTypeDefinition( + QuickSwitchFileType.Category category, + String suffix, + @Nullable QuickSwitchFileType builtInType + ) { } + + private record FileMatch(FileTypeDefinition fileType, String baseName) { } + + private record FileContext( + FileTypeDefinition currentType, + String baseName, + VirtualFile[] siblings + ) { } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchCategoryAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchCategoryAction.java new file mode 100644 index 0000000..2bbc4fe --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchCategoryAction.java @@ -0,0 +1,55 @@ +package patrick.kelleter.angularcliquickswitch; + +import com.intellij.openapi.actionSystem.ActionUpdateThread; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.project.DumbAwareAction; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.NotNull; + +public abstract class QuickSwitchCategoryAction extends DumbAwareAction { + private final QuickSwitchFileType.Category category; + + QuickSwitchCategoryAction(@NotNull QuickSwitchFileType.Category category) { + this.category = category; + } + + @Override + public @NotNull ActionUpdateThread getActionUpdateThread() { + return ActionUpdateThread.BGT; + } + + @Override + public void update(@NotNull AnActionEvent event) { + Project project = event.getProject(); + VirtualFile file = event.getData(CommonDataKeys.VIRTUAL_FILE); + event.getPresentation().setEnabled( + project != null + && !project.isDisposed() + && QuickSwitchAction.isSwitchable(file, QuickSwitchSettings.getInstance()) + ); + } + + @Override + public void actionPerformed(@NotNull AnActionEvent event) { + Project project = event.getProject(); + VirtualFile currentFile = event.getData(CommonDataKeys.VIRTUAL_FILE); + if (project == null || project.isDisposed() || currentFile == null) { + return; + } + + QuickSwitchSettings settings = QuickSwitchSettings.getInstance(); + VirtualFile targetFile = QuickSwitchAction.findTargetFile(currentFile, category, settings); + if (targetFile == null) { + return; + } + + QuickSwitchAction.navigate( + project, + currentFile, + targetFile, + settings.isClosePreviousTab() + ); + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchConfigurable.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchConfigurable.java new file mode 100644 index 0000000..c7beaa3 --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchConfigurable.java @@ -0,0 +1,269 @@ +package patrick.kelleter.angularcliquickswitch; + +import com.intellij.openapi.options.Configurable; +import com.intellij.openapi.options.ConfigurationException; +import com.intellij.ui.components.JBTextField; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NotNull; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.border.Border; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.GridLayout; +import java.util.EnumMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.Set; + +public final class QuickSwitchConfigurable implements Configurable { + private static final ResourceBundle BRANDING = ResourceBundle.getBundle( + "patrick.kelleter.angularcliquickswitch.QuickSwitchBranding" + ); + + private JCheckBox closePreviousTabCheckBox; + private Map fileTypeCheckBoxes; + private Map customEnabledCheckBoxes; + private Map customSuffixFields; + + @Override + public @Nls String getDisplayName() { + return BRANDING.getString("pluginName"); + } + + @Override + public @NotNull JComponent createComponent() { + JPanel rootPanel = new JPanel(); + rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.Y_AXIS)); + + JPanel generalPanel = createSectionPanel("General"); + closePreviousTabCheckBox = new JCheckBox("Close the previous tab after switching"); + closePreviousTabCheckBox.setToolTipText( + "The target opens first; IntelliJ may also close copies of the previous file in other editor splits." + ); + generalPanel.add(closePreviousTabCheckBox); + allowHorizontalStretch(generalPanel); + rootPanel.add(generalPanel); + rootPanel.add(Box.createVerticalStrut(12)); + + fileTypeCheckBoxes = new EnumMap<>(QuickSwitchFileType.class); + customEnabledCheckBoxes = new EnumMap<>(QuickSwitchFileType.Category.class); + customSuffixFields = new EnumMap<>(QuickSwitchFileType.Category.class); + JPanel extensionsPanel = createSectionPanel("Supported Extensions"); + JPanel categoriesPanel = new JPanel(new GridLayout( + 1, + QuickSwitchFileType.Category.values().length, + 24, + 0 + )); + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + JPanel categoryPanel = new JPanel(); + categoryPanel.setLayout(new BoxLayout(categoryPanel, BoxLayout.Y_AXIS)); + JLabel categoryLabel = new JLabel(categoryDisplayName(category)); + categoryLabel.setFont(categoryLabel.getFont().deriveFont(Font.BOLD)); + categoryPanel.add(categoryLabel); + categoryPanel.add(Box.createVerticalStrut(3)); + + JPanel extensionListPanel = new JPanel(); + extensionListPanel.setLayout(new BoxLayout(extensionListPanel, BoxLayout.Y_AXIS)); + + for (QuickSwitchFileType fileType : QuickSwitchFileType.values()) { + if (fileType.category() == category) { + JCheckBox checkBox = new JCheckBox("." + fileType.suffix()); + checkBox.setAlignmentX(Component.LEFT_ALIGNMENT); + fileTypeCheckBoxes.put(fileType, checkBox); + extensionListPanel.add(checkBox); + } + } + + extensionListPanel.add(Box.createVerticalStrut(4)); + JPanel customPanel = new JPanel(); + customPanel.setLayout(new BoxLayout(customPanel, BoxLayout.X_AXIS)); + customPanel.setAlignmentX(Component.LEFT_ALIGNMENT); + JCheckBox customEnabledCheckBox = new JCheckBox(); + customEnabledCheckBox.getAccessibleContext().setAccessibleName( + "Enable custom " + categoryDisplayName(category).toLowerCase(Locale.ROOT) + " suffix" + ); + JBTextField customSuffixField = new JBTextField(7); + customSuffixField.getEmptyText().setText(".custom"); + customSuffixField.setToolTipText("Enter a suffix such as .tsx or .component.html"); + customEnabledCheckBox.addActionListener(event -> + customSuffixField.setEnabled(customEnabledCheckBox.isSelected())); + customEnabledCheckBoxes.put(category, customEnabledCheckBox); + customSuffixFields.put(category, customSuffixField); + customPanel.add(customEnabledCheckBox); + customPanel.add(customSuffixField); + customPanel.setMaximumSize(customPanel.getPreferredSize()); + extensionListPanel.add(customPanel); + extensionListPanel.setMaximumSize(extensionListPanel.getPreferredSize()); + categoryPanel.add(extensionListPanel); + + categoriesPanel.add(categoryPanel); + } + + allowHorizontalStretch(categoriesPanel); + extensionsPanel.add(categoriesPanel); + allowHorizontalStretch(extensionsPanel); + rootPanel.add(extensionsPanel); + rootPanel.add(Box.createVerticalGlue()); + return rootPanel; + } + + @Override + public boolean isModified() { + QuickSwitchSettings settings = QuickSwitchSettings.getInstance(); + if (closePreviousTabCheckBox != null + && Configurable.isCheckboxModified(closePreviousTabCheckBox, settings.isClosePreviousTab())) { + return true; + } + + if (fileTypeCheckBoxes != null && fileTypeCheckBoxes.entrySet().stream() + .anyMatch(entry -> Configurable.isCheckboxModified( + entry.getValue(), + settings.isFileTypeEnabled(entry.getKey()) + ))) { + return true; + } + + if (customEnabledCheckBoxes == null || customSuffixFields == null) { + return false; + } + + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + if (Configurable.isCheckboxModified( + customEnabledCheckBoxes.get(category), + settings.isCustomSuffixEnabled(category) + ) || !customSuffixFields.get(category).getText().trim() + .equals(formatSuffix(settings.getCustomSuffix(category)))) { + return true; + } + } + return false; + } + + @Override + public void apply() throws ConfigurationException { + Map customSuffixes = validateCustomSuffixes(); + QuickSwitchSettings settings = QuickSwitchSettings.getInstance(); + if (closePreviousTabCheckBox != null) { + settings.setClosePreviousTab(closePreviousTabCheckBox.isSelected()); + } + if (fileTypeCheckBoxes != null) { + fileTypeCheckBoxes.forEach((fileType, checkBox) -> + settings.setFileTypeEnabled(fileType, checkBox.isSelected())); + } + if (customEnabledCheckBoxes != null && customSuffixFields != null) { + customSuffixes.forEach((category, suffix) -> { + settings.setCustomSuffix(category, suffix, customEnabledCheckBoxes.get(category).isSelected()); + customSuffixFields.get(category).setText(formatSuffix(suffix)); + }); + } + } + + @Override + public void reset() { + QuickSwitchSettings settings = QuickSwitchSettings.getInstance(); + if (closePreviousTabCheckBox != null) { + closePreviousTabCheckBox.setSelected(settings.isClosePreviousTab()); + } + if (fileTypeCheckBoxes != null) { + fileTypeCheckBoxes.forEach((fileType, checkBox) -> + checkBox.setSelected(settings.isFileTypeEnabled(fileType))); + } + if (customEnabledCheckBoxes != null && customSuffixFields != null) { + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + boolean enabled = settings.isCustomSuffixEnabled(category); + customEnabledCheckBoxes.get(category).setSelected(enabled); + customSuffixFields.get(category).setText(formatSuffix(settings.getCustomSuffix(category))); + customSuffixFields.get(category).setEnabled(enabled); + } + } + } + + @Override + public void disposeUIResources() { + closePreviousTabCheckBox = null; + fileTypeCheckBoxes = null; + customEnabledCheckBoxes = null; + customSuffixFields = null; + } + + private static JPanel createSectionPanel(String title) { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + Border titleBorder = BorderFactory.createTitledBorder(title); + Border padding = BorderFactory.createEmptyBorder(8, 12, 10, 12); + panel.setBorder(BorderFactory.createCompoundBorder(titleBorder, padding)); + return panel; + } + + private static void allowHorizontalStretch(JComponent component) { + component.setAlignmentX(Component.LEFT_ALIGNMENT); + component.setMaximumSize(new Dimension(Integer.MAX_VALUE, component.getPreferredSize().height)); + } + + private Map validateCustomSuffixes() throws ConfigurationException { + Map normalizedSuffixes = + new EnumMap<>(QuickSwitchFileType.Category.class); + Set usedSuffixes = new HashSet<>(); + for (QuickSwitchFileType fileType : QuickSwitchFileType.values()) { + usedSuffixes.add(fileType.suffix().toLowerCase(Locale.ROOT)); + } + + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + String enteredSuffix = customSuffixFields.get(category).getText().trim().toLowerCase(Locale.ROOT); + String suffix = normalizeSuffix(enteredSuffix); + boolean enabled = customEnabledCheckBoxes.get(category).isSelected(); + if (enabled && enteredSuffix.isEmpty()) { + throw new ConfigurationException(categoryDisplayName(category) + " custom suffix cannot be empty."); + } + if (!enteredSuffix.isEmpty() && !enteredSuffix.startsWith(".")) { + throw new ConfigurationException( + categoryDisplayName(category) + " custom suffix must start with a dot." + ); + } + if (!enteredSuffix.isEmpty() + && !enteredSuffix.matches("\\.[a-z0-9_-]+(?:\\.[a-z0-9_-]+)*")) { + throw new ConfigurationException( + categoryDisplayName(category) + " custom suffix contains invalid characters." + ); + } + if (!suffix.isEmpty() && !usedSuffixes.add(suffix)) { + throw new ConfigurationException("Custom suffix ." + suffix + " is already configured."); + } + normalizedSuffixes.put(category, suffix); + } + return normalizedSuffixes; + } + + private static String normalizeSuffix(String value) { + String suffix = value.trim().toLowerCase(Locale.ROOT); + if (suffix.startsWith(".")) { + suffix = suffix.substring(1); + } + return suffix; + } + + private static String formatSuffix(String suffix) { + return suffix.isEmpty() ? "" : "." + suffix; + } + + private static String categoryDisplayName(QuickSwitchFileType.Category category) { + return switch (category) { + case CONTROLLER -> BRANDING.getString("category.controller"); + case TEMPLATE -> BRANDING.getString("category.template"); + case STYLE -> BRANDING.getString("category.style"); + case TESTS -> BRANDING.getString("category.tests"); + }; + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchControllersAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchControllersAction.java new file mode 100644 index 0000000..829f51f --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchControllersAction.java @@ -0,0 +1,7 @@ +package patrick.kelleter.angularcliquickswitch; + +public final class QuickSwitchControllersAction extends QuickSwitchCategoryAction { + public QuickSwitchControllersAction() { + super(QuickSwitchFileType.Category.CONTROLLER); + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchFileType.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchFileType.java new file mode 100644 index 0000000..a1a2a98 --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchFileType.java @@ -0,0 +1,51 @@ +package patrick.kelleter.angularcliquickswitch; + +enum QuickSwitchFileType { + TYPESCRIPT(Category.CONTROLLER, "ts", true), + JAVASCRIPT(Category.CONTROLLER, "js", true), + + HTML(Category.TEMPLATE, "html", true), + PHP(Category.TEMPLATE, "php", true), + HAML(Category.TEMPLATE, "haml", true), + JADE(Category.TEMPLATE, "jade", true), + PUG(Category.TEMPLATE, "pug", true), + SLIM(Category.TEMPLATE, "slim", true), + + CSS(Category.STYLE, "css", true), + SASS(Category.STYLE, "sass", true), + SCSS(Category.STYLE, "scss", true), + LESS(Category.STYLE, "less", true), + STYLUS(Category.STYLE, "styl", true), + + TYPESCRIPT_SPEC(Category.TESTS, "spec.ts", false), + JAVASCRIPT_SPEC(Category.TESTS, "spec.js", false); + + enum Category { + CONTROLLER, + TEMPLATE, + STYLE, + TESTS + } + + private final Category category; + private final String suffix; + private final boolean enabledByDefault; + + QuickSwitchFileType(Category category, String suffix, boolean enabledByDefault) { + this.category = category; + this.suffix = suffix; + this.enabledByDefault = enabledByDefault; + } + + Category category() { + return category; + } + + String suffix() { + return suffix; + } + + boolean enabledByDefault() { + return enabledByDefault; + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchMarkupAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchMarkupAction.java new file mode 100644 index 0000000..8d8dc8c --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchMarkupAction.java @@ -0,0 +1,7 @@ +package patrick.kelleter.angularcliquickswitch; + +public final class QuickSwitchMarkupAction extends QuickSwitchCategoryAction { + public QuickSwitchMarkupAction() { + super(QuickSwitchFileType.Category.TEMPLATE); + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettings.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettings.java new file mode 100644 index 0000000..45b916a --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettings.java @@ -0,0 +1,130 @@ +package patrick.kelleter.angularcliquickswitch; + +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.components.PersistentStateComponent; +import com.intellij.openapi.components.Service; +import com.intellij.openapi.components.SettingsCategory; +import com.intellij.openapi.components.State; +import com.intellij.openapi.components.Storage; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +@Service(Service.Level.APP) +@State( + name = "AngularCliQuickSwitchSettings", + storages = @Storage("angularCliQuickSwitch.xml"), + category = SettingsCategory.PLUGINS +) +public final class QuickSwitchSettings implements PersistentStateComponent { + public static final class SettingsState { + public boolean closePreviousTab; + public Set disabledFileTypes = new HashSet<>(); + public Set enabledOptInFileTypes = new HashSet<>(); + public Map customSuffixes = new HashMap<>(); + public Set enabledCustomCategories = new HashSet<>(); + } + + private volatile SettingsState state = new SettingsState(); + + public static @NotNull QuickSwitchSettings getInstance() { + return ApplicationManager.getApplication().getService(QuickSwitchSettings.class); + } + + @Override + public @NotNull SettingsState getState() { + return state; + } + + @Override + public void loadState(@NotNull SettingsState state) { + if (state.disabledFileTypes == null) { + state.disabledFileTypes = new HashSet<>(); + } + if (state.enabledOptInFileTypes == null) { + state.enabledOptInFileTypes = new HashSet<>(); + } + if (state.customSuffixes == null) { + state.customSuffixes = new HashMap<>(); + } + if (state.enabledCustomCategories == null) { + state.enabledCustomCategories = new HashSet<>(); + } + this.state = state; + } + + public boolean isClosePreviousTab() { + return state.closePreviousTab; + } + + public void setClosePreviousTab(boolean closePreviousTab) { + SettingsState newState = copyState(); + newState.closePreviousTab = closePreviousTab; + state = newState; + } + + boolean isFileTypeEnabled(@NotNull QuickSwitchFileType fileType) { + SettingsState currentState = state; + return fileType.enabledByDefault() + ? !currentState.disabledFileTypes.contains(fileType.name()) + : currentState.enabledOptInFileTypes.contains(fileType.name()); + } + + void setFileTypeEnabled(@NotNull QuickSwitchFileType fileType, boolean enabled) { + SettingsState newState = copyState(); + if (fileType.enabledByDefault()) { + if (enabled) { + newState.disabledFileTypes.remove(fileType.name()); + } else { + newState.disabledFileTypes.add(fileType.name()); + } + } else if (enabled) { + newState.enabledOptInFileTypes.add(fileType.name()); + } else { + newState.enabledOptInFileTypes.remove(fileType.name()); + } + state = newState; + } + + boolean isCustomSuffixEnabled(@NotNull QuickSwitchFileType.Category category) { + return state.enabledCustomCategories.contains(category.name()); + } + + @NotNull String getCustomSuffix(@NotNull QuickSwitchFileType.Category category) { + return state.customSuffixes.getOrDefault(category.name(), ""); + } + + void setCustomSuffix( + @NotNull QuickSwitchFileType.Category category, + @NotNull String suffix, + boolean enabled + ) { + SettingsState newState = copyState(); + if (suffix.isEmpty()) { + newState.customSuffixes.remove(category.name()); + } else { + newState.customSuffixes.put(category.name(), suffix); + } + + if (enabled) { + newState.enabledCustomCategories.add(category.name()); + } else { + newState.enabledCustomCategories.remove(category.name()); + } + state = newState; + } + + private SettingsState copyState() { + SettingsState currentState = state; + SettingsState newState = new SettingsState(); + newState.closePreviousTab = currentState.closePreviousTab; + newState.disabledFileTypes = new HashSet<>(currentState.disabledFileTypes); + newState.enabledOptInFileTypes = new HashSet<>(currentState.enabledOptInFileTypes); + newState.customSuffixes = new HashMap<>(currentState.customSuffixes); + newState.enabledCustomCategories = new HashSet<>(currentState.enabledCustomCategories); + return newState; + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchStylesAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchStylesAction.java new file mode 100644 index 0000000..8ffc29b --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchStylesAction.java @@ -0,0 +1,7 @@ +package patrick.kelleter.angularcliquickswitch; + +public final class QuickSwitchStylesAction extends QuickSwitchCategoryAction { + public QuickSwitchStylesAction() { + super(QuickSwitchFileType.Category.STYLE); + } +} diff --git a/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchTestsAction.java b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchTestsAction.java new file mode 100644 index 0000000..f2f8fdd --- /dev/null +++ b/src/main/java/patrick/kelleter/angularcliquickswitch/QuickSwitchTestsAction.java @@ -0,0 +1,7 @@ +package patrick.kelleter.angularcliquickswitch; + +public final class QuickSwitchTestsAction extends QuickSwitchCategoryAction { + public QuickSwitchTestsAction() { + super(QuickSwitchFileType.Category.TESTS); + } +} diff --git a/src/main/plugin/plugin.xml b/src/main/plugin/plugin.xml new file mode 100644 index 0000000..89aad17 --- /dev/null +++ b/src/main/plugin/plugin.xml @@ -0,0 +1,43 @@ + + @PLUGIN_ID@ + @PLUGIN_NAME@ + Patrick Kelleter + + + + com.intellij.modules.platform + @INCOMPATIBLE_PLUGIN_ID@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml deleted file mode 100755 index 5fb7547..0000000 --- a/src/main/resources/META-INF/plugin.xml +++ /dev/null @@ -1,28 +0,0 @@ - - patrick.kelleter.angular-cli-quick-switch - Angular CLI QuickSwitch - Patrick Kelleter - - - - - Updated docs
- ]]> -
- - - - com.intellij.modules.lang - - - - - - - - - -
\ No newline at end of file diff --git a/src/main/resources/META-INF/pluginIcon.svg b/src/main/resources/META-INF/pluginIcon.svg new file mode 100644 index 0000000..fa6fbe2 --- /dev/null +++ b/src/main/resources/META-INF/pluginIcon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/patrick/kelleter/angularcliquickswitch/QuickSwitchBranding.properties b/src/main/resources/patrick/kelleter/angularcliquickswitch/QuickSwitchBranding.properties new file mode 100644 index 0000000..983e0bf --- /dev/null +++ b/src/main/resources/patrick/kelleter/angularcliquickswitch/QuickSwitchBranding.properties @@ -0,0 +1,5 @@ +pluginName=@PLUGIN_NAME@ +category.controller=@CONTROLLER_CATEGORY_NAME@ +category.template=@TEMPLATE_CATEGORY_NAME@ +category.style=Style +category.tests=Tests diff --git a/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchActionTest.java b/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchActionTest.java new file mode 100644 index 0000000..602fca5 --- /dev/null +++ b/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchActionTest.java @@ -0,0 +1,279 @@ +package patrick.kelleter.angularcliquickswitch; + +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.testFramework.fixtures.BasePlatformTestCase; + +import java.util.Arrays; + +public final class QuickSwitchActionTest extends BasePlatformTestCase { + public void testCyclesThroughExistingCounterparts() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile html = addFile("example.component.html"); + VirtualFile stylesheet = addFile("example.component.scss"); + + assertTarget(html, QuickSwitchAction.findTargetFile(typescript)); + assertTarget(stylesheet, QuickSwitchAction.findTargetFile(html)); + assertTarget(typescript, QuickSwitchAction.findTargetFile(stylesheet)); + } + + public void testUsesConfiguredExtensionOrder() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile javascript = addFile("example.component.js"); + addFile("example.component.html"); + + assertTarget(javascript, QuickSwitchAction.findTargetFile(typescript)); + } + + public void testReturnsNullForUnsupportedExtension() { + VirtualFile markdown = addFile("example.component.md"); + addFile("example.component.ts"); + + assertNull(QuickSwitchAction.findTargetFile(markdown)); + } + + public void testReturnsNullWithoutCounterpart() { + VirtualFile typescript = addFile("example.component.ts"); + + assertNull(QuickSwitchAction.findTargetFile(typescript)); + } + + public void testSupportsUppercaseExtensions() { + VirtualFile typescript = addFile("example.component.TS"); + VirtualFile html = addFile("example.component.HTML"); + + assertTarget(html, QuickSwitchAction.findTargetFile(typescript)); + } + + public void testHandlesDotsInParentDirectory() { + VirtualFile typescript = addFile("feature.v2/example.component.ts"); + VirtualFile html = addFile("feature.v2/example.component.html"); + + assertTarget(html, QuickSwitchAction.findTargetFile(typescript)); + } + + public void testSkipsDirectoriesNamedLikeCounterparts() { + VirtualFile typescript = addFile("example.component.ts"); + myFixture.addFileToProject("example.component.html/nested.txt", ""); + VirtualFile stylesheet = addFile("example.component.css"); + + assertTarget(stylesheet, QuickSwitchAction.findTargetFile(typescript)); + } + + public void testSkipsDisabledFileType() { + VirtualFile html = addFile("example.component.html"); + addFile("example.component.scss"); + VirtualFile typescript = addFile("example.component.ts"); + + VirtualFile target = QuickSwitchAction.findTargetFile( + html, + fileType -> fileType.enabledByDefault() && fileType != QuickSwitchFileType.SCSS + ); + + assertTarget(typescript, target); + } + + public void testCanSwitchAwayFromDisabledFileType() { + VirtualFile stylesheet = addFile("example.component.scss"); + VirtualFile typescript = addFile("example.component.ts"); + + VirtualFile target = QuickSwitchAction.findTargetFile( + stylesheet, + fileType -> fileType.enabledByDefault() && fileType != QuickSwitchFileType.SCSS + ); + + assertTarget(typescript, target); + } + + public void testSkipsSpecFileByDefault() { + VirtualFile typescript = addFile("example.component.ts"); + addFile("example.component.spec.ts"); + VirtualFile html = addFile("example.component.html"); + + assertTarget(html, QuickSwitchAction.findTargetFile(typescript)); + } + + public void testCyclesThroughEnabledSpecFile() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile spec = addFile("example.component.spec.ts"); + + VirtualFile target = QuickSwitchAction.findTargetFile( + typescript, + fileType -> fileType.enabledByDefault() || fileType == QuickSwitchFileType.TYPESCRIPT_SPEC + ); + + assertTarget(spec, target); + assertTarget(typescript, QuickSwitchAction.findTargetFile( + spec, + fileType -> fileType.enabledByDefault() || fileType == QuickSwitchFileType.TYPESCRIPT_SPEC + )); + } + + public void testJumpsDirectlyToFirstTestFile() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile typescriptSpec = addFile("example.component.spec.ts"); + addFile("example.component.spec.js"); + + VirtualFile target = QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.TESTS + ); + + assertTarget(typescriptSpec, target); + } + + public void testCyclesOnlyWithinTestFiles() { + VirtualFile typescriptSpec = addFile("example.component.spec.ts"); + VirtualFile javascriptSpec = addFile("example.component.spec.js"); + addFile("example.component.ts"); + + assertTarget(javascriptSpec, QuickSwitchAction.findTargetFile( + typescriptSpec, + QuickSwitchFileType.Category.TESTS + )); + assertTarget(typescriptSpec, QuickSwitchAction.findTargetFile( + javascriptSpec, + QuickSwitchFileType.Category.TESTS + )); + } + + public void testJumpsDirectlyToFirstControllerFile() { + VirtualFile html = addFile("example.component.html"); + VirtualFile typescript = addFile("example.component.ts"); + addFile("example.component.js"); + + assertTarget(typescript, QuickSwitchAction.findTargetFile( + html, + QuickSwitchFileType.Category.CONTROLLER + )); + } + + public void testJumpsDirectlyToFirstStyleFile() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile css = addFile("example.component.css"); + addFile("example.component.scss"); + + assertTarget(css, QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.STYLE + )); + } + + public void testJumpsDirectlyToFirstMarkupFile() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile html = addFile("example.component.html"); + addFile("example.component.pug"); + + assertTarget(html, QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.TEMPLATE + )); + } + + public void testCategoryShortcutDoesNotReopenOnlyCurrentFile() { + VirtualFile typescript = addFile("example.component.ts"); + + assertNull(QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.CONTROLLER + )); + } + + public void testMainCycleIncludesEnabledCustomSuffix() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.CONTROLLER, "tsx", true); + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile tsx = addFile("example.component.tsx"); + + assertTarget(tsx, QuickSwitchAction.findTargetFile(typescript, settings)); + } + + public void testMainCycleSkipsDisabledCustomSuffix() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.CONTROLLER, "tsx", false); + VirtualFile typescript = addFile("example.component.ts"); + addFile("example.component.tsx"); + VirtualFile html = addFile("example.component.html"); + + assertTarget(html, QuickSwitchAction.findTargetFile(typescript, settings)); + } + + public void testCanSwitchAwayFromDisabledCustomSuffix() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.CONTROLLER, "tsx", false); + VirtualFile tsx = addFile("example.component.tsx"); + VirtualFile html = addFile("example.component.html"); + + assertTarget(html, QuickSwitchAction.findTargetFile(tsx, settings)); + } + + public void testCategoryShortcutIncludesEnabledCustomSuffix() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.STYLE, "pcss", true); + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile pcss = addFile("example.component.pcss"); + + assertTarget(pcss, QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.STYLE, + settings + )); + } + + public void testCompoundCustomSuffixUsesComponentBaseName() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.TEMPLATE, "view.html", true); + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile customTemplate = addFile("example.component.view.html"); + + assertTarget(customTemplate, QuickSwitchAction.findTargetFile( + typescript, + QuickSwitchFileType.Category.TEMPLATE, + settings + )); + assertTarget(typescript, QuickSwitchAction.findTargetFile(customTemplate, settings)); + } + + public void testKeepsPreviousTabOpen() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile html = addFile("example.component.html"); + FileEditorManager fileEditorManager = FileEditorManager.getInstance(getProject()); + fileEditorManager.openFile(typescript, true); + + QuickSwitchAction.navigate(getProject(), typescript, html, false); + + assertOpen(fileEditorManager, typescript); + assertOpen(fileEditorManager, html); + } + + public void testClosesPreviousTabAfterOpeningTarget() { + VirtualFile typescript = addFile("example.component.ts"); + VirtualFile html = addFile("example.component.html"); + FileEditorManager fileEditorManager = FileEditorManager.getInstance(getProject()); + fileEditorManager.openFile(typescript, true); + + QuickSwitchAction.navigate(getProject(), typescript, html, true); + + assertNotOpen(fileEditorManager, typescript); + assertOpen(fileEditorManager, html); + } + + private VirtualFile addFile(String path) { + return myFixture.addFileToProject(path, "").getVirtualFile(); + } + + private void assertTarget(VirtualFile expected, VirtualFile actual) { + assertNotNull(actual); + assertEquals(expected.getPath(), actual.getPath()); + } + + private void assertOpen(FileEditorManager fileEditorManager, VirtualFile file) { + assertTrue(Arrays.stream(fileEditorManager.getOpenFiles()) + .anyMatch(openFile -> openFile.getPath().equals(file.getPath()))); + } + + private void assertNotOpen(FileEditorManager fileEditorManager, VirtualFile file) { + assertFalse(Arrays.stream(fileEditorManager.getOpenFiles()) + .anyMatch(openFile -> openFile.getPath().equals(file.getPath()))); + } +} diff --git a/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettingsTest.java b/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettingsTest.java new file mode 100644 index 0000000..c94f8f5 --- /dev/null +++ b/src/test/java/patrick/kelleter/angularcliquickswitch/QuickSwitchSettingsTest.java @@ -0,0 +1,96 @@ +package patrick.kelleter.angularcliquickswitch; + +import junit.framework.TestCase; + +public final class QuickSwitchSettingsTest extends TestCase { + public void testKeepsTabsOpenByDefault() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + + assertFalse(settings.isClosePreviousTab()); + } + + public void testUsesFileTypeDefaults() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + + for (QuickSwitchFileType fileType : QuickSwitchFileType.values()) { + assertEquals(fileType.suffix(), fileType.enabledByDefault(), settings.isFileTypeEnabled(fileType)); + } + } + + public void testCustomSuffixesAreDisabledAndEmptyByDefault() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + + for (QuickSwitchFileType.Category category : QuickSwitchFileType.Category.values()) { + assertFalse(settings.isCustomSuffixEnabled(category)); + assertEquals("", settings.getCustomSuffix(category)); + } + } + + public void testLoadsPersistedClosePreference() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + QuickSwitchSettings.SettingsState state = new QuickSwitchSettings.SettingsState(); + state.closePreviousTab = true; + + settings.loadState(state); + + assertTrue(settings.isClosePreviousTab()); + } + + public void testUpdatesClosePreference() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setFileTypeEnabled(QuickSwitchFileType.SCSS, false); + + settings.setClosePreviousTab(true); + + assertTrue(settings.isClosePreviousTab()); + assertTrue(settings.getState().closePreviousTab); + assertFalse(settings.isFileTypeEnabled(QuickSwitchFileType.SCSS)); + } + + public void testPersistsFileTypeOverrides() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + + settings.setFileTypeEnabled(QuickSwitchFileType.SCSS, false); + settings.setFileTypeEnabled(QuickSwitchFileType.TYPESCRIPT_SPEC, true); + + assertFalse(settings.isFileTypeEnabled(QuickSwitchFileType.SCSS)); + assertTrue(settings.isFileTypeEnabled(QuickSwitchFileType.TYPESCRIPT_SPEC)); + assertTrue(settings.getState().disabledFileTypes.contains(QuickSwitchFileType.SCSS.name())); + assertTrue(settings.getState().enabledOptInFileTypes.contains(QuickSwitchFileType.TYPESCRIPT_SPEC.name())); + } + + public void testLoadsPersistedFileTypeOverrides() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + QuickSwitchSettings.SettingsState state = new QuickSwitchSettings.SettingsState(); + state.disabledFileTypes.add(QuickSwitchFileType.HTML.name()); + state.enabledOptInFileTypes.add(QuickSwitchFileType.JAVASCRIPT_SPEC.name()); + + settings.loadState(state); + + assertFalse(settings.isFileTypeEnabled(QuickSwitchFileType.HTML)); + assertTrue(settings.isFileTypeEnabled(QuickSwitchFileType.JAVASCRIPT_SPEC)); + } + + public void testPersistsCustomSuffix() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + + settings.setCustomSuffix(QuickSwitchFileType.Category.CONTROLLER, "tsx", true); + + assertTrue(settings.isCustomSuffixEnabled(QuickSwitchFileType.Category.CONTROLLER)); + assertEquals("tsx", settings.getCustomSuffix(QuickSwitchFileType.Category.CONTROLLER)); + assertEquals( + "tsx", + settings.getState().customSuffixes.get(QuickSwitchFileType.Category.CONTROLLER.name()) + ); + } + + public void testDisabledCustomSuffixRetainsItsValue() { + QuickSwitchSettings settings = new QuickSwitchSettings(); + settings.setCustomSuffix(QuickSwitchFileType.Category.STYLE, "pcss", true); + + settings.setCustomSuffix(QuickSwitchFileType.Category.STYLE, "pcss", false); + + assertFalse(settings.isCustomSuffixEnabled(QuickSwitchFileType.Category.STYLE)); + assertEquals("pcss", settings.getCustomSuffix(QuickSwitchFileType.Category.STYLE)); + } +}